/** * @param shardService Your shard service. * @param shardRegistry Your shard registry. * @param dbiRegistry Your DBI registry. * @param daoRegistry Your DAO registry. * @param dropwizardDbiFactory Your dropwizard application's DBI Factory. * @param dropwizardEnvironment Your dropwizard application's environment. * @param dropwizardDSFactory Your dropwizard application's datasource factory. * @param DBIInitializer We call your initializer immediately after dropwizardDbiFactory builds your * DBI. @see jdbishard.jdbi.NoOpDBIInitializer. * @param humanFriendlyShardNamer We register metrics for each shard connection given the human * friendly name. @see jdbishard.sharding.IdOnlyShardNamer. */ @Inject public JDBIManager( ShardService<ShardIdT, KeyT> shardService, ShardRegistry<ShardIdT, KeyT> shardRegistry, DBIRegistry<ShardIdT> dbiRegistry, DAORegistry<ShardIdT> daoRegistry, DBIFactory dropwizardDbiFactory, Environment dropwizardEnvironment, DataSourceFactory dropwizardDSFactory, DBIInitializer DBIInitializer, HumanFriendlyShardNamer humanFriendlyShardNamer) { this.shardService = shardService; this.shardRegistry = shardRegistry; this.dbiRegistry = dbiRegistry; this.daoRegistry = daoRegistry; this.dropwizardDbiFactory = dropwizardDbiFactory; this.dropwizardEnvironment = dropwizardEnvironment; this.dropwizardDSFactory = dropwizardDSFactory; this.DBIInitializer = DBIInitializer; this.humanFriendlyShardNamer = humanFriendlyShardNamer; }
@Override public final void run(MatchingServiceAdapterConfiguration configuration, Environment environment) { IdaSamlBootstrap.bootstrap(); environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); environment.jersey().register(LocalMetadataResource.class); environment.jersey().register(MatchingServiceResource.class); environment.jersey().register(UnknownUserAttributeQueryResource.class); environment.jersey().register(SamlOverSoapExceptionMapper.class); environment.jersey().register(ExceptionExceptionMapper.class); MatchingServiceAdapterHealthCheck healthCheck = new MatchingServiceAdapterHealthCheck(); environment.healthChecks().register(healthCheck.getName(), healthCheck); }
private static List<ApplicationUrlsGenerator> extractRowsForSimpleServer(Environment environment, ServerConnector connector) { return ImmutableList.of( new ApplicationUrlsGenerator( APPLICATION_URL_TYPE, isHttps(connector.getDefaultProtocol()), connector.getLocalPort(), environment.getApplicationContext().getContextPath() ), new ApplicationUrlsGenerator( ADMIN_URL_TYPE, isHttps(connector.getDefaultProtocol()), connector.getLocalPort(), environment.getAdminContext().getContextPath() ), new ApplicationUrlsGenerator( HEALTHCHECK_URL_TYPE, isHttps(connector.getDefaultProtocol()), connector.getLocalPort(), environment.getAdminContext().getContextPath() ) ); }
/** * Create an instance of MyBatis. * * @param environment The dropwizard environment * @param configuration The data source factory/configuration * @param dataSource The datasource you want to use. * @param name The name of this mybatis factory used for metrics * @return An instance of MyBatis. */ public final SqlSessionFactory build(Environment environment, DataSourceFactory configuration, ManagedDataSource dataSource, String name) { // Initialize validation query final String validationQuery = configuration.getValidationQuery(); // Build mybatis session factory TransactionFactory transactionFactory = new JdbcTransactionFactory(); org.apache.ibatis.mapping.Environment myBatisEnvironment = new org.apache.ibatis.mapping.Environment(ENV_NAME, transactionFactory, dataSource); Configuration mybatisConfiguration = new Configuration(myBatisEnvironment); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(mybatisConfiguration); // Setup managed data source and health checks environment.lifecycle().manage(dataSource); environment.healthChecks().register(name, new MyBatisHealthCheck(sessionFactory, validationQuery)); return sessionFactory; }
private void registerResources(Environment environment) { EventStore eventStore = new InMemoryEventStore(); EventBus eventBus = new AsyncEventBus(newSingleThreadExecutor()); // domain model AccountService accountService = new AccountService(eventStore, eventBus); environment.jersey().register(new AccountsResource(accountService)); environment.jersey().register(new AccountResource(accountService)); environment.jersey().register(new DepositsResource(accountService)); environment.jersey().register(new WithdrawalsResource(accountService)); ClientService clientService = new ClientService(eventStore); environment.jersey().register(new ClientsResource(clientService)); environment.jersey().register(new ClientResource(clientService)); // read model TransactionsRepository transactionsRepository = new InMemoryTransactionsRepository(); eventBus.register(new TransactionsListener(transactionsRepository)); environment.jersey().register(new AccountTransactionsResource(transactionsRepository)); AccountsRepository accountsRepository = new InMemoryAccountsRepository(); eventBus.register(new AccountsListener(accountsRepository)); environment.jersey().register(new ClientAccountsResource(accountsRepository)); }
@Override public DBI build(Environment environment, PooledDataSourceFactory configuration, ManagedDataSource dataSource, String name) { final DBI dbi = super.build(environment, configuration, dataSource, name); dbi.registerArgumentFactory(new ValueArgumentFactory(configuration.getDriverClass())); dbi.registerArgumentFactory(new OptionArgumentFactory(configuration.getDriverClass())); dbi.registerContainerFactory(new OptionContainerFactory()); // The order of container factories is important, least specific to most specific dbi.registerContainerFactory(new SeqContainerFactory()); dbi.registerContainerFactory(new IndexedSeqContainerFactory()); dbi.registerContainerFactory(new SetContainerFactory()); dbi.registerContainerFactory(new TreeContainerFactory()); dbi.registerContainerFactory(new ListContainerFactory()); dbi.registerContainerFactory(new ArrayContainerFactory()); dbi.registerContainerFactory(new QueueContainerFactory()); dbi.registerContainerFactory(new StreamContainerFactory()); dbi.registerContainerFactory(new VectorContainerFactory()); return dbi; }
@Override public void run(Configuration configuration, Environment environment) throws Exception { // Preparing Translation Service final TranslationService translationService = new TranslationService(); // Preparing Greeting Service and inject Translation final GreetingResource greetingService = new GreetingResource(translationService); // Register Greeting Service environment.jersey().register(greetingService); // Add Metrics Instrumentation to count requests final CollectorRegistry collectorRegistry = new CollectorRegistry(); collectorRegistry.register(new DropwizardExports(environment.metrics())); // Register Metrics Servlet environment.admin() .addServlet("metrics", new MetricsServlet(collectorRegistry)) .addMapping("/metrics"); }
/** * Create a new provider instance * * @param dropwizardEnvironment The dropwizard environment object * @param applicationName The application name * @param dataSourceFactories The MultiEnvAware datasource list used to create session factories from * @param typeHandlers The list of type handlers to configure with each session factory * @param sqlMappers The list of sql mappers to configure with each session factory */ private DefaultSqlSessionFactoryProvider(Environment dropwizardEnvironment, String applicationName, MultiEnvAware<ConfigurableLazyDataSourceFactory> dataSourceFactories, List<Class<?>> typeHandlers, List<Class<?>> sqlMappers, Map<Class<?>, Class<?>> typeClassToTypeHandlerClassMap, Map<String, Class<?>> typeToAliasClassMap, ObjectFactory objectFactory, Map<String, Object> mybatisConfigurationSettingsMap) { this.dropwizardEnvironment = dropwizardEnvironment; this.applicationName = applicationName; this.dataSourceFactories = dataSourceFactories; this.typeHandlers = typeHandlers; this.sqlMappers = sqlMappers; this.typeClassToTypeHandlerClassMap = typeClassToTypeHandlerClassMap; this.typeToAliasClassMap = typeToAliasClassMap; this.objectFactory = objectFactory; this.mybatisConfigurationSettings = mybatisConfigurationSettingsMap; sessionFactories = dataSourceFactories.convert((env, dataSource) -> buildSessionFactory(dataSource, env)); }
@Override public void run(TestAppConfig configuration, Environment environment) throws Exception { final ShardRegistry<String, UUID> shardRegistry = new ShardRegistry<>(); final DAORegistry<String> daoRegistry = new DAORegistry<>(); final DBIFactory dbiFactory = new DBIFactory(); jdbiManager = new JDBIManager<>( new StaticShardService(), shardRegistry, new DBIRegistry<>(), daoRegistry, dbiFactory, environment, configuration.getDataSourceFactory(), new NoOpDBIInitializer(), new IdOnlyShardNamer()); clientDAO = new ClientDAO(shardRegistry, daoRegistry); daoRegistry.registerType(ClientShardDAO.class); jdbiManager.updateObjects(); }
@Override public void run(final CONFIG configuration, final Environment environment) { environment.jersey().register(auditedQueryResourceClass); environment.jersey().register(auditedDocRefResourceClass); environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(QueryEventLoggingService.class).to(EventLoggingService.class); bind(queryServiceClass).to(QueryService.class); bind(docRefServiceClass).to(new ParameterizedTypeImpl(DocRefService.class, docRefEntityClass)); bind(AuthorisationServiceImpl.class).to(AuthorisationService.class); bind(configuration.getAuthorisationServiceConfig()).to(AuthorisationServiceConfig.class); bind(configuration.getTokenConfig()).to(TokenConfig.class); } }); }
@Override public void run(AppConfiguration appConfiguration, Environment environment) throws Exception { logger.info("Registering jersey HTTP API"); final URL configurationsDirURL = Helpers.getResourceURL("configurations/"); final URI configurationsDirURI = configurationsDirURL.toURI(); final ConfigurationDAO configurationDAO = new SimpleFilesystemConfigurationDAO(configurationsDirURI); final ConfigurationsResource configurationsResource = new ConfigurationsResource(configurationDAO); environment.jersey().register(configurationsResource); final URL documentsDirURL = Helpers.getResourceURL("documents/"); final URI documentsDirURI = documentsDirURL.toURI(); final DocumentDAO documentDAO = new SimpleFilesystemDocumentDAO(documentsDirURI); final DocumentsResource documentsResource = new DocumentsResource(documentDAO); environment.jersey().register(documentsResource); final URL platesDirURL = Helpers.getResourceURL("plates/"); final URI platesDirURI = platesDirURL.toURI(); final PlateDAO plateDAO = new SimpleFilesystemPlateDAO(platesDirURI); final PlatesResource platesResource = new PlatesResource(plateDAO); environment.jersey().register(platesResource); logger.info("HTTP API registered"); }
static void register(Environment environment, Injector injector) { register(environment, "QueryResource", () -> injector.getInstance(QueryResource.class)); register(environment, injector.getInstance(ServiceDiscoverer.class)); register(environment, injector.getInstance(ServiceDiscoveryRegistrar.class)); StatisticsFlatMappingService statisticsFlatMappingService = injector.getInstance(StatisticsFlatMappingService.class); register(environment, statisticsFlatMappingService); // StatisticsAggregationService statisticsAggregationService = injector.getInstance(StatisticsAggregationService.class); register(environment, statisticsAggregationService); register(environment, LogLevelInspector.INSTANCE); register(environment, injector.getInstance(StroomPropertyServiceHealthCheck.class)); register(environment, injector.getInstance(HBaseConnection.class)); }
@Override public void run(RiaBotServiceConfiguration riaBotServiceConfiguration, Environment environment) throws Exception { //Start the job scheduler JobManager.getInstance().startScheduler(); /* * Register resources with jersey. */ final RiaResource chatResource = new RiaResource(); /* * Setup jersey environment. */ environment.jersey().setUrlPattern(EndpointUtils.ENDPOINT_ROOT + "/*"); environment.jersey().register(chatResource); log.info("Done with all initializations for user service"); }
public DBClient build(Environment environment) { String dbServer = System.getenv("DB"); if (dbServer != null) { server = dbServer; } dbClient = dbFactory.create(server, port, dbName); log.info("Connected to db"); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { dbClient.useDB(dbName); } @Override public void stop() throws Exception { dbClient.close(); } }); return dbClient; }
@Override public void run(ChatbotConfiguration chatbotConfiguration, Environment environment) throws Exception { //Start the job scheduler JobManager.getInstance().startScheduler(); /* * Register resources with jersey. */ final ChatResource chatResource = new ChatResource(); /* * Setup jersey environment. */ environment.jersey().setUrlPattern(EndpointUtils.ENDPOINT_ROOT + "/*"); environment.jersey().register(chatResource); log.info("Done with all initializations for user service"); }
private Injector configureGuice(T configuration, Environment environment) throws Exception { // setup our core modules... appModules.add(new MetricRegistryModule(environment.metrics())); appModules.add(new ServletModule()); // ...and add the app's modules appModules.addAll(addModules(configuration, environment)); final Injector injector = Guice.createInjector(ImmutableList.copyOf(this.appModules)); // Taken from https://github.com/Squarespace/jersey2-guice/wiki#complex-example. HK2 is no fun. JerseyGuiceUtils.install((name, parent) -> { if (!name.startsWith("__HK2_Generated_")) { return null; } return injector.createChildInjector(Lists.newArrayList(new JerseyGuiceModule(name))) .getInstance(ServiceLocator.class); }); injector.injectMembers(this); registerWithInjector(environment, injector); return injector; }
@Override public Application<ServerConfiguration> newApplication() { return new ServerMain("outland.feature.server") { @Override protected List<Module> addModules( ServerConfiguration configuration, Environment environment) { return Lists.newArrayList( new ServerModule(configuration), new HystrixModule(), new RedisModule(configuration.redis), new DynamoDbModule(configuration.aws), new AuthModule(configuration.auth), new TestFeatureServiceModule(), new TestGroupModule() ); } }; }
@JsonIgnore public DseCluster build(Environment environment) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException { DseCluster.Builder builder = DseCluster.builder() .addContactPoints(contactPoints) .withGraphOptions(new GraphOptions().setGraphName(graphName)); if (null != userName && userName.length() > 0 && null != password && password.length() > 0) { builder = builder.withCredentials(userName, password); } if (null != sslTruststoreFile && sslTruststoreFile.length() > 0 && null != sslTruststorePassword && sslTruststorePassword.length() > 0) { builder = withSSL(builder); } DseCluster cluster = builder.build(); DseSession session = cluster.newSession(); environment.lifecycle().manage(new DseGraphManaged(cluster, getShutdownTimeout())); environment.healthChecks().register("dsegraph", new DseGraphHealthCheck(session, validationQuery, validationQueryTimeout)); return cluster; }
@Override public void run(final HelloWorldConfiguration configuration, final Environment environment) { final HaystackFeature haystackFeature = new HaystackFeature(configuration.getTracer().build()); environment.jersey().register(haystackFeature); final HelloWorldResource resource = new HelloWorldResource(configuration.getTemplate(), configuration.getDefaultName()); environment.jersey().register(resource); environment.jersey().register(new UntracedResource(configuration.getTemplate(), configuration.getDefaultName())); final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate()); environment.healthChecks().register("template", healthCheck); }
@Override public void run(VerifyServiceProviderConfiguration configuration, Environment environment) throws Exception { VerifyServiceProviderFactory factory = new VerifyServiceProviderFactory(configuration, environment); environment.jersey().register(new JerseyViolationExceptionMapper()); environment.jersey().register(new JsonProcessingExceptionMapper()); environment.jersey().register(new InvalidEntityIdExceptionMapper()); environment.jersey().register(factory.getVersionNumberResource()); environment.jersey().register(factory.getGenerateAuthnRequestResource()); environment.jersey().register(factory.getTranslateSamlResponseResource()); environment.healthChecks().register("hubMetadata", factory.getHubMetadataHealthCheck()); environment.healthChecks().register("msaMetadata", factory.getMsaMetadataHealthCheck()); environment.lifecycle().addServerLifecycleListener(new VerifyServiceProviderServerListener(environment)); }
/** * Create an instance of MyBatis. * * @param environment The dropwizard environment * @param config A Mybatis config object * @param dataSource * @param name The name of this mybatis factory used for metrics * @return An instance of MyBatis. */ public final SqlSessionFactory build(Environment environment, MyBatisConfiguration config, ManagedDataSource dataSource, String name) { SqlSessionFactory sessionFactory = null; // Try to use the mybatis configuration file if it is specified and exists. try (InputStream inputStream = Resources.getResourceAsStream(config.getConfigFile())) { sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException ioe) { // Build session factory from configuration values given in the dropwizard config. TransactionFactory transactionFactory = new JdbcTransactionFactory(); org.apache.ibatis.mapping.Environment myBatisEnvironment = new org.apache.ibatis.mapping.Environment(ENV_NAME, transactionFactory, dataSource); Configuration mybatisConfiguration = new Configuration(myBatisEnvironment); sessionFactory = new SqlSessionFactoryBuilder().build(mybatisConfiguration); } environment.lifecycle().manage(dataSource); environment.healthChecks().register(name, new MyBatisHealthCheck(sessionFactory, config.getConfig().getValidationQuery())); return sessionFactory; }
@Override public void run(ExecutionEngineConfiguration config, Environment env) { ResourceDirectoryClientFactory factory = new ResourceDirectoryClientFactory( config.getRdClientconfig().getRdAddress(), config.getRdClientconfig().getPortNumber() ); env.jersey().register(new EchoApplicationResource(factory)); }
@Override public void run(ApiConfig configuration, Environment environment) throws Exception { LOGGER.info("api started up"); injector = guiceBundle.getInjector(); JerseyEnvironment jersey = environment.jersey(); register(environment.lifecycle(), REFLECTIONS.getSubTypesOf(Managed.class)); // registers NbdServer // injector.getInstance(SessionFactory.class); //init DB installCorsFilter(environment); //init all Singletons semi-eagerly REFLECTIONS.getTypesAnnotatedWith(Singleton.class).forEach(injector::getInstance); final Set<Class<?>> resources = REFLECTIONS.getTypesAnnotatedWith(Path.class); register(jersey, resources); jersey.register(new LoggingExceptionMapper<Throwable>() { @Override protected String formatErrorMessage(long id, Throwable exception) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); return sw.toString(); } }); jersey.register(new JsonProcessingExceptionMapper(true)); jersey.register(new EarlyEofExceptionMapper()); final TrivialAuthenticator instance = injector.getInstance(TrivialAuthenticator.class); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<Principal>() .setAuthenticator(instance) .setAuthorizer((principal, role) -> false) .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); }
private static List<ApplicationUrlsGenerator> extractDetails(Environment environment, List<ServerConnector> connectors) { if (isSimpleServer(connectors)) { return extractRowsForSimpleServer(environment, connectors.get(0)); } return connectors.stream() .map(ServerConnector.class::cast) .flatMap(serverConnector -> extractTableRowForDefaultServer(environment, serverConnector).stream()) .collect(toList()); }
@Override public final void run(StubEventSinkConfiguration configuration, Environment environment) { environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); StubEventSinkHealthCheck healthCheck = new StubEventSinkHealthCheck(); environment.healthChecks().register(healthCheck.getName(), healthCheck); environment.jersey().register(EventSinkHubEventResource.class); environment.jersey().register(EventSinkHubEventTestResource.class); }
public void run(Configuration configuration, Environment environment) { // Preparing Http Client final HttpClient httpClient = HttpClientBuilder.create().build(); // Dependency Injection final HelloTranslationClient translationClient = new HelloTranslationClient(httpClient); final HelloWorldResource resource = new HelloWorldResource(translationClient); // Register Hello World Resource environment.jersey().register(resource); }
@Provides @Singleton @Named(VERIFY_METADATA_HEALTH_CHECK) public MetadataHealthCheck getVerifyMetadataHealthCheck( @Named("VerifyMetadataResolver") MetadataResolver metadataResolver, Environment environment, SamlProxyConfiguration configuration) { MetadataHealthCheck metadataHealthCheck = new MetadataHealthCheck(metadataResolver, configuration.getMetadataConfiguration().getExpectedEntityId()); environment.healthChecks().register(VERIFY_METADATA_HEALTH_CHECK, metadataHealthCheck); return metadataHealthCheck; }
public void run(Configuration configuration, Environment environment) throws Exception { // INSTRUMENTATION // Metrics Instrumentation final CollectorRegistry collectorRegistry = new CollectorRegistry(); collectorRegistry.register(new DropwizardExports(environment.metrics())); environment.admin() .addServlet("metrics", new MetricsServlet(collectorRegistry)) .addMapping("/metrics"); final PrometheusMetricsReporter reporter = PrometheusMetricsReporter.newMetricsReporter() .withCollectorRegistry(collectorRegistry) .withConstLabel("service", getName()) .build(); // Tracing Instrumentation final Tracer tracer = getTracer(); final Tracer metricsTracer = io.opentracing.contrib.metrics.Metrics.decorate(tracer, reporter); GlobalTracer.register(metricsTracer); final HttpHost httpHost = new HttpHost("tweets-elasticsearch", 9200); final RestClientBuilder restClientBuilder = RestClient.builder(httpHost).setHttpClientConfigCallback(new TracingHttpClientConfigCallback(metricsTracer)); final RestClient restClient = restClientBuilder.build(); final ElasticsearchTweetRepository elasticsearchRepository = new ElasticsearchTweetRepository(restClient); final Properties consumerConfigs = new Properties(); consumerConfigs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "tweets-kafka:9092"); consumerConfigs.put(ConsumerConfig.GROUP_ID_CONFIG, getName()); consumerConfigs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); consumerConfigs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); final KafkaConsumer<Long, String> kafkaConsumer = new KafkaConsumer<>(consumerConfigs, new LongDeserializer(), new StringDeserializer()); final TracingKafkaConsumer<Long, String> tracingKafkaConsumer = new TracingKafkaConsumer<>(kafkaConsumer, metricsTracer); final Runnable kafkaTweetEventConsumer = new KafkaTweetEventConsumer(tracingKafkaConsumer, elasticsearchRepository); final ExecutorService executorService = environment.lifecycle().executorService("kafka-consumer").build(); executorService.submit(kafkaTweetEventConsumer); }
@Provides @Singleton @Named(COUNTRY_METADATA_HEALTH_CHECK) public Optional<MetadataHealthCheck> getCountryMetadataHealthCheck( @Named("CountryMetadataResolver") Optional<MetadataResolver> metadataResolver, Environment environment, SamlProxyConfiguration configuration) { return metadataResolver.map(resolver -> { MetadataHealthCheck metadataHealthCheck = new MetadataHealthCheck(metadataResolver.get(), configuration.getCountryConfiguration().get().getMetadataConfiguration().getExpectedEntityId()); environment.healthChecks().register(COUNTRY_METADATA_HEALTH_CHECK, metadataHealthCheck); return metadataHealthCheck; }); }
@Provides @Singleton public JsonClient jsonClient(JsonResponseProcessor jsonResponseProcessor, Environment environment, SamlProxyConfiguration configuration) { Client client = new ClientProvider( environment, configuration.getJerseyClientConfiguration(), configuration.getEnableRetryTimeOutConnections(), "samlProxyClient").get(); ErrorHandlingClient errorHandlingClient = new ErrorHandlingClient(client); return new JsonClient(errorHandlingClient, jsonResponseProcessor); }
@Inject public EventSinkProxy( JsonClient jsonClient, @EventSink URI eventSinkUri, Environment environment) { this.jsonClient = jsonClient; this.eventSinkUri = eventSinkUri; this.environment = environment; }
@Override public void run(PolicyConfiguration configuration, Environment environment) throws Exception { environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); registerResources(configuration, environment); registerExceptionMappers(environment); environment.jersey().register(SessionIdPathParamLoggingFilter.class); }
private void registerExceptionMappers(Environment environment) { environment.jersey().register(SessionTimeoutExceptionMapper.class); environment.jersey().register(IdpDisabledExceptionMapper.class); environment.jersey().register(StateProcessingValidationExceptionMapper.class); environment.jersey().register(SessionNotFoundExceptionMapper.class); environment.jersey().register(SessionAlreadyExistingExceptionMapper.class); environment.jersey().register(InvalidSessionStateExceptionMapper.class); environment.jersey().register(PolicyApplicationExceptionMapper.class); environment.jersey().register(SessionCreationFailureExceptionMapper.class); environment.jersey().register(EidasCountryNotSupportedExceptionMapper.class); environment.jersey().register(EidasNotSupportedExceptionMapper.class); }
private void installCorsFilter(Environment environment) { FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORSFilter", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() + "*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,OPTIONS"); filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Origin, Content-Type, Accept, Authorization"); filter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true"); }
@Provides @Singleton public JsonClient jsonClient(JsonResponseProcessor jsonResponseProcessor, Environment environment, PolicyConfiguration configuration) { Client client = new ClientProvider( environment, configuration.getJerseyClientConfiguration(), configuration.getEnableRetryTimeOutConnections(), "policyClient").get(); ErrorHandlingClient errorHandlingClient = new ErrorHandlingClient(client); return new JsonClient(errorHandlingClient, jsonResponseProcessor); }
@Override public final void run(SamlEngineConfiguration configuration, Environment environment) { IdaSamlBootstrap.bootstrap(); environment.getObjectMapper().registerModule(new GuavaModule()); environment.getObjectMapper().setDateFormat(new ISO8601DateFormat()); // register resources registerResources(environment, configuration); // register exception mappers environment.jersey().register(SamlEngineExceptionMapper.class); environment.servlets().addFilter("Logging SessionId registration Filter", SessionIdQueryParamLoggingFilter.class).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
@Provides @Singleton @Named(VERIFY_METADATA_HEALTH_CHECK) private MetadataHealthCheck getVerifyMetadataHealthCheck( @Named("VerifyMetadataResolver") MetadataResolver metadataResolver, Environment environment, SamlEngineConfiguration configuration) { MetadataHealthCheck metadataHealthCheck = new MetadataHealthCheck(metadataResolver, configuration.getMetadataConfiguration().getExpectedEntityId()); environment.healthChecks().register(VERIFY_METADATA_HEALTH_CHECK, metadataHealthCheck); return metadataHealthCheck; }
public ResourcesClient(Environment environment, int port) { this.client = new JerseyClientBuilder(environment) .build(ResourcesClient.class.getName()) .property(CONNECT_TIMEOUT, 2000) .property(READ_TIMEOUT, 3000) .register(new LoggingFeature(getLogger(DEFAULT_LOGGER_NAME), INFO, PAYLOAD_ANY, 2048)); this.resourcesUrls = new ResourcesUrls(port); }
@Override public void run(final ApiConfiguration configuration, final Environment environment) { // Common initializations EsInstanceStore cmdbInstanceStore = new EsInstanceStore(); ServiceMappingStore serviceMappingStore = new EsServiceMappingStore(); InstanceCounterStore instanceCounterStore = new EsInstanceCounterStore(); // Health checks final EsHealthChecker esHealthChecker = new EsHealthChecker(cmdbInstanceStore); environment.healthChecks().register("cmdbStore", esHealthChecker); // Logging inbound request/response environment.jersey().register( new LoggingFilter(java.util.logging.Logger.getLogger("InboundRequestResponse"), true)); // Add API endpoints here final Instance instance = new Instance(cmdbInstanceStore); environment.jersey().register(instance); final Health health = new Health(); environment.jersey().register(health); final Query query = new Query(cmdbInstanceStore); environment.jersey().register(query); final InstanceCounter instanceCounter = new InstanceCounter(instanceCounterStore); environment.jersey().register(instanceCounter); final DailySnapshot dailySnapshot = new DailySnapshot(); environment.jersey().register(dailySnapshot); }