Java Code Examples for io.dropwizard.setup.Environment

The following are top voted examples for showing how to use io.dropwizard.setup.Environment. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: talk-observing-distributed-systems   File: WorkerServiceApplication.java   Source Code and License 9 votes vote down vote up
public void run(Configuration configuration, Environment environment) throws Exception {
  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();

  final Tracer tracer = getTracer();
  final Tracer metricsTracer = io.opentracing.contrib.metrics.Metrics.decorate(tracer, reporter);
  GlobalTracer.register(metricsTracer);

  final DynamicFeature tracing = new ServerTracingDynamicFeature.Builder(metricsTracer).build();
  environment.jersey().register(tracing);

  final Properties producerConfigs = new Properties();
  producerConfigs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "tweets-kafka:9092");
  producerConfigs.put(ProducerConfig.ACKS_CONFIG, "all");
  producerConfigs.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
  final KafkaProducer<Long, String> kafkaProducer =
      new KafkaProducer<>(producerConfigs, new LongSerializer(), new StringSerializer());
  final Producer<Long, String> tracingKafkaProducer =
      new TracingKafkaProducer<>(kafkaProducer, metricsTracer);
  final ObjectMapper objectMapper = environment.getObjectMapper();
  final TweetEventRepository tweetRepository = new KafkaTweetEventRepository(tracingKafkaProducer, objectMapper);
  final TweetsService tweetsService = new TweetsService(tweetRepository);
  final TweetsResource tweetsResource = new TweetsResource(tweetsService);
  environment.jersey().register(tweetsResource);
}
 
Example 2
Project: jdbishard   File: JDBIManager.java   Source Code and License 6 votes vote down vote up
/**
 * @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;
}
 
Example 3
Project: verify-matching-service-adapter   File: MatchingServiceAdapterApplication.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 4
Project: dropwizard-mybatis   File: MyBatisFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Project: event-sourcing-cqrs-examples   File: BankServiceApplication.java   Source Code and License 6 votes vote down vote up
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));
}
 
Example 6
Project: dropwizard-vavr   File: VavrDBIFactory.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 7
Project: talk-observing-distributed-systems   File: HelloWorldMonolithApp.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 8
Project: dropwizard-mybatis   File: DefaultSqlSessionFactoryProvider.java   Source Code and License 6 votes vote down vote up
/**
 * 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));
}
 
Example 9
Project: jdbishard   File: TestApp.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 10
Project: stroom-query   File: AuditedQueryBundle.java   Source Code and License 6 votes vote down vote up
@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);
        }
    });
}
 
Example 11
Project: plateyplatey-server   File: App.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 12
Project: stroom-stats   File: HealthChecks.java   Source Code and License 6 votes vote down vote up
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));
    }
 
Example 13
Project: amigo-chatbot   File: RiaBotServiceApplication.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 14
Project: amigo-chatbot   File: DBConfig.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 15
Project: amigo-chatbot   File: ChatbotServiceApplication.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 16
Project: amigo-chatbot   File: DBConfig.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 17
Project: outland   File: GuiceApplication.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 18
Project: talk-observing-distributed-systems   File: TweetsServiceApplication.java   Source Code and License 6 votes vote down vote up
public void run(Configuration configuration, Environment environment) {
  final CollectorRegistry collectorRegistry = new CollectorRegistry();
  collectorRegistry.register(new DropwizardExports(environment.metrics()));

  final PrometheusMetricsReporter reporter =
      PrometheusMetricsReporter.newMetricsReporter()
          .withCollectorRegistry(collectorRegistry)
          .withConstLabel("service", getName())
          .build();

  final Tracer tracer = getTracer();
  final Tracer metricsTracer = io.opentracing.contrib.metrics.Metrics.decorate(tracer, reporter);
  GlobalTracer.register(metricsTracer);

  final String jdbcUrl = "jdbc:tracing:postgresql://tweets-db/postgres";
  final String jdbcUsername = "postgres";
  final String jdbcPassword = "example";
  final TweetsRepository tweetsRepository = new JooqPostgresTweetsRepository(jdbcUrl, jdbcUsername, jdbcPassword);
  final TweetsService tweetsService = new TweetsService(tweetsRepository);
  final TweetsResource tweetsResource = new TweetsResource(tweetsService);

  environment.jersey().register(tweetsResource);

  final DynamicFeature tracing = new ServerTracingDynamicFeature.Builder(metricsTracer).build();
  environment.jersey().register(tracing);

  environment.admin()
      .addServlet("metrics", new MetricsServlet(collectorRegistry))
      .addMapping("/metrics");
}
 
Example 19
Project: outland   File: ServerSuite.java   Source Code and License 6 votes vote down vote up
@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()
                  );
                }
              };
            }
 
Example 20
Project: dropwizard-dsegraph   File: DseGraphFactory.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 21
Project: haystack-client-java   File: HelloWorldApplication.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 22
Project: verify-service-provider   File: VerifyServiceProviderApplication.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 23
Project: dropwizard-mybatis   File: MyBatisFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 24
Project: echo   File: ExecutionEngine.java   Source Code and License 5 votes vote down vote up
@Override
public void run(ExecutionEngineConfiguration config, Environment env) {
    ResourceDirectoryClientFactory factory = new ResourceDirectoryClientFactory(
            config.getRdClientconfig().getRdAddress(),
            config.getRdClientconfig().getPortNumber()
    );
    env.jersey().register(new EchoApplicationResource(factory));
}
 
Example 25
Project: minebox   File: MinebdApplication.java   Source Code and License 5 votes vote down vote up
@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);

    }
 
Example 26
Project: verify-service-provider   File: UsefulApplicationUrlsTableFormatter.java   Source Code and License 5 votes vote down vote up
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()
        )
    );
}
 
Example 27
Project: verify-service-provider   File: UsefulApplicationUrlsTableFormatter.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 28
Project: verify-hub   File: StubEventSinkApplication.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 29
Project: talk-observing-distributed-systems   File: HelloWorldServiceApp.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 30
Project: verify-hub   File: SamlProxyModule.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 31
Project: talk-observing-distributed-systems   File: IndexerServiceApplication.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 32
Project: verify-hub   File: SamlProxyModule.java   Source Code and License 5 votes vote down vote up
@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;
    });
}
 
Example 33
Project: verify-hub   File: SamlProxyModule.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 34
Project: verify-hub   File: EventSinkProxy.java   Source Code and License 5 votes vote down vote up
@Inject
public EventSinkProxy(
        JsonClient jsonClient,
        @EventSink URI eventSinkUri,
        Environment environment) {
    this.jsonClient = jsonClient;
    this.eventSinkUri = eventSinkUri;
    this.environment = environment;
}
 
Example 35
Project: verify-hub   File: PolicyApplication.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 36
Project: verify-hub   File: PolicyApplication.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 37
Project: tools   File: MinebdApplication.java   Source Code and License 5 votes vote down vote up
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");
}
 
Example 38
Project: verify-hub   File: PolicyModule.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 39
Project: verify-hub   File: SamlEngineApplication.java   Source Code and License 5 votes vote down vote up
@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, "/*");
}
 
Example 40
Project: verify-hub   File: SamlEngineModule.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 41
Project: http-progressive-download-examples   File: ResourcesClient.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 42
Project: soundwave   File: ApiApplication.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 43
Project: verify-hub   File: SamlSoapProxyModule.java   Source Code and License 5 votes vote down vote up
@Provides @Singleton
public ExecutorService getMatchingServiceExecutorService(Environment environment, SamlSoapProxyConfiguration configuration) {
    return environment.lifecycle()
            .executorService("Matching service caller %s")
            .maxThreads(configuration.getMatchingServiceExecutor().getMaxPoolSize())
            .minThreads(configuration.getMatchingServiceExecutor().getCorePoolSize())
            .keepAliveTime(configuration.getMatchingServiceExecutor().getKeepAliveDuration())
            .build();
}
 
Example 44
Project: verify-hub   File: SamlSoapProxyApplication.java   Source Code and License 5 votes vote down vote up
@Override
public void run(SamlSoapProxyConfiguration configuration, Environment environment) throws Exception {
    IdaSamlBootstrap.bootstrap();
    environment.getObjectMapper().setDateFormat(new ISO8601DateFormat());
    registerResources(environment);
    environment.servlets().addFilter("Logging SessionId registration Filter", SessionIdQueryParamLoggingFilter.class).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
 
Example 45
Project: verify-service-provider   File: VerifyServiceProviderFactory.java   Source Code and License 5 votes vote down vote up
public VerifyServiceProviderFactory(
    VerifyServiceProviderConfiguration configuration,
    Environment environment
) {
    this.environment = environment;
    this.configuration = configuration;
    this.responseFactory = new ResponseFactory(
        configuration.getSamlPrimaryEncryptionKey(),
        configuration.getSamlSecondaryEncryptionKey());
    this.dateTimeComparator = new DateTimeComparator(configuration.getClockSkew());
    this.entityIdService = new EntityIdService(configuration.getServiceEntityIds());
    this.manifestReader = new ManifestReader();
}
 
Example 46
Project: talk-observing-distributed-systems   File: TranslationServiceApp.java   Source Code and License 5 votes vote down vote up
public void run(Configuration configuration, Environment environment) {
  // Dependency Injection
  final HelloTranslationRepository repository = new HelloTranslationRepository();
  final HelloTranslationResource resource = new HelloTranslationResource(repository);

  // Register HTTP Resource
  environment.jersey().register(resource);
}
 
Example 47
Project: etomica   File: EtomicaServer.java   Source Code and License 5 votes vote down vote up
private static void configureCors(Environment env) {
    final FilterRegistration.Dynamic cors = env.servlets().addFilter("CORS", CrossOriginFilter.class);

    cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD");
    cors.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true");

    // Add URL mapping
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
 
Example 48
Project: stroom-stats   File: App.java   Source Code and License 5 votes vote down vote up
private void registerResources(final Environment environment) {
    LOGGER.info("Registering API");
    environment.jersey().register(new QueryResource(
            injector.getInstance(HBaseClient.class),
            injector.getInstance(DataSourceService.class),
            injector.getInstance(ServiceDiscoverer.class),
            injector.getInstance(StroomPropertyService.class)));
}
 
Example 49
Project: dropwizard-pagination   File: PaginationApplication.java   Source Code and License 5 votes vote down vote up
@Override
public void run(final PaginationConfiguration configuration,
                final Environment environment) {
    final ItemsResource resource = new ItemsResource();
    environment.jersey().register(resource);
    environment.jersey().register(DeclarativeLinkingFeature.class);
}
 
Example 50
Project: verify-matching-service-adapter   File: MatchingServiceAdapterModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Singleton
@Named(VERIFY_METADATA_RESOLVER)
private MetadataResolver getVerifyMetadataResolver(Environment environment, MatchingServiceAdapterConfiguration configuration) {
    MetadataResolver metadataResolver = new DropwizardMetadataResolverFactory().createMetadataResolver(environment, configuration.getMetadataConfiguration());
    environment.healthChecks().register("VerifyMetadataHealthCheck", new MetadataHealthCheck(metadataResolver, configuration.getMetadataConfiguration().getExpectedEntityId()));
    return metadataResolver;
}
 
Example 51
Project: stroom-stats   File: HeadlessTestApp.java   Source Code and License 5 votes vote down vote up
@Override
public void run(Config config, Environment environment) {

    injector = Guice.createInjector(new StroomStatsServiceModule(config, hibernateBundle.getSessionFactory()));

    //log all the property service properties
    StroomPropertyService stroomPropertyService = injector.getInstance(StroomPropertyService.class);
    LOGGER.info("All property service properties:");
    stroomPropertyService.dumpAllProperties(LOGGER::info);
}
 
Example 52
Project: soren-subscriber   File: SorenSubscriberApplication.java   Source Code and License 5 votes vote down vote up
@Override
public void run(final SorenSubscriberConfiguration configuration, final Environment environment) {
    // Registering DAOs and creating Guice
    Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            DBIFactory factory = new DBIFactory();
            DBI dbi = factory.build(environment, configuration.getDataSourceFactory(), DATABASE_TYPE.value);
            SorenSubscriberDAO sorenSubscriberDAO = dbi.onDemand(SorenSubscriberDAO.class);
            bind(SorenSubscriberDAO.class).toInstance(sorenSubscriberDAO);
        }
    });

    // Swagger doc endpoint
    environment.jersey().register(new ApiListingResource());

    // Health Check registration
    environment.jersey().register(injector.getInstance(SubscriberHealthCheck.class));

    // Resources registration
    environment.jersey().register(injector.getInstance(SubscriberResource.class));

    environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

    BeanConfig config = new BeanConfig();
    config.setTitle("Swagger sample app");
    config.setVersion("1.0.0");
    config.setResourcePackage("org.vahid.resources");
    config.setScan(true);
}
 
Example 53
Project: amigo-chatbot   File: UserServiceApplication.java   Source Code and License 5 votes vote down vote up
@Override
public void run(UserServiceConfiguration userServiceConfiguration, Environment environment) throws Exception {


    dbClient = userServiceConfiguration.getDbConfig().build(environment);
    log.info("Connected to db: " + dbClient.getConnectString());
    /*
     * Setup basic authentication against DB table.
     */
    environment.jersey().register(new AuthDynamicFeature(
            new BasicCredentialAuthFilter.Builder<PrincipalUser>()
                    .setAuthenticator(new SimpleAuthenticator(dbClient))
                    .setRealm("amigo_user")
                    .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalUser.class));

    environment.healthChecks().register("database", new DBHealthCheck(dbClient));
    /*
     * Register resources with jersey.
     */
    final UserResource userResource = new UserResource(dbClient);

    /*
     * Setup jersey environment.
     */
    environment.jersey().setUrlPattern(EndpointUtils.ENDPOINT_ROOT + "/*");
    environment.jersey().register(userResource);
    log.info("Done with all initializations for user service");
}
 
Example 54
Project: outland   File: ServerMain.java   Source Code and License 5 votes vote down vote up
@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 FeatureModule(configuration.featureTable),
      new GroupModule()
  );
}
 
Example 55
Project: outland   File: ServerMain.java   Source Code and License 5 votes vote down vote up
@Override
protected void applicationOnRun(ServerConfiguration configuration, Environment environment,
    Injector injector) {

  enableContentEncodingGzip(environment);
  configureAuth(configuration.auth, environment, injector);
}
 
Example 56
Project: talk-observing-distributed-systems   File: HelloWorldClientApp.java   Source Code and License 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) {
  // Instantiate Http Client
  final HttpClient httpClient = HttpClientBuilder.create().build();

  // Dependency Injection
  final HelloWorldClient helloWorldClient = new HelloWorldClient(httpClient);
  final GreetingService greetingService = new GreetingService(helloWorldClient);

  // Register Greeting Service
  environment.jersey().register(greetingService);
}
 
Example 57
Project: oacc-example-securetodo   File: SecureTodoApplication.java   Source Code and License 5 votes vote down vote up
@Override
public void run(final SecureTodoConfiguration configuration,
                final Environment environment) {
   final DBIFactory dbiFactory = new DBIFactory();
   final DBI todoJdbi = dbiFactory.build(environment, configuration.getTodoDbDataSourceFactory(), "todoDb");
   final TodoUserDAO todoUserDao = todoJdbi.onDemand(TodoUserDAO.class);
   final TodoItemDAO todoItemDao = todoJdbi.onDemand(TodoItemDAO.class);

   final AccessControlContextFactory accessControlContextFactory = configuration.getAccessControlContextFactory();
   accessControlContextFactory.initialize(environment, configuration.getOaccDbDataSourceFactory(), "oacc");

   environment.jersey().register(new TodoUserResource(new TodoUserService(todoUserDao, accessControlContextFactory)));
   environment.jersey().register(new TodoItemResource(new TodoItemService(todoItemDao)));

   environment.jersey().register(new AuthDynamicFeature(
         new BasicCredentialAuthFilter.Builder<OaccPrincipal>()
               .setAuthenticator(new OaccBasicAuthenticator(accessControlContextFactory))
               .setRealm("OACC Basic Authentication")
               .buildAuthFilter()));
   // to use @Auth to inject a custom Principal type into a resource:
   environment.jersey().register(new AuthValueFactoryProvider.Binder<>(OaccPrincipal.class));

   environment.jersey().register(new AuthorizationExceptionMapper(environment.metrics()));
   environment.jersey().register(new IllegalArgumentExceptionMapper(environment.metrics()));
   environment.jersey().register(new InvalidCredentialsExceptionMapper(environment.metrics()));
   environment.jersey().register(new NotAuthenticatedExceptionMapper(environment.metrics()));
}
 
Example 58
Project: oacc-example-securetodo   File: AccessControlContextFactory.java   Source Code and License 5 votes vote down vote up
public void initialize(Environment environment, PooledDataSourceFactory dataSourceFactory, String name) {
   dataSource = dataSourceFactory.build(environment.metrics(), name);
   bCryptPasswordEncryptor = BCryptPasswordEncryptor.newInstance(12);
   environment.lifecycle().manage(dataSource);
   environment.healthChecks().register(name,
                                       new DataSourceHealthCheck(environment.getHealthCheckExecutorService(),
                                                                 dataSourceFactory.getValidationQueryTimeout()
                                                                       .orElse(Duration.seconds(5)),
                                                                 dataSource,
                                                                 dataSourceFactory.getValidationQuery()));
}
 
Example 59
Project: dropwizard-hikaricp-benchmark   File: BenchApplication.java   Source Code and License 5 votes vote down vote up
@Override
public void run(final BenchConfiguration config,
                final Environment environment) {
    final DBIFactory factory = new DBIFactory();
    final Optional<PooledDataSourceFactory> tomcatFactory = config.getTomcatFactory().map(x -> x);

    config.getHikariFactory().ifPresent(x -> x.setHealthCheckRegistry(environment.healthChecks()));
    final Optional<PooledDataSourceFactory> hikariFactory = config.getHikariFactory().map(x -> x);
    final PooledDataSourceFactory datasource = tomcatFactory.orElse(hikariFactory.orElse(null));
    final DBI jdbi = factory.build(environment, datasource, "postgresql");
    jdbi.registerMapper(new QuestionMapper());
    final QuestionQuery dao = jdbi.onDemand(QuestionQuery.class);
    environment.jersey().register(new QuestionResource(dao));
}
 
Example 60
Project: crnk-framework   File: DropwizardService.java   Source Code and License 5 votes vote down vote up
@Override
public void run(DropwizardConfiguration dropwizardConfiguration, Environment environment) throws Exception {
	environment.jersey().property(CrnkProperties.RESOURCE_SEARCH_PACKAGE, dropwizardConfiguration.crnk.searchPackage);

	CrnkFeature crnkFeature = new CrnkFeature();
	environment.jersey().register(crnkFeature);
}