Java 类io.dropwizard.setup.Environment 实例源码

项目:jdbishard    文件:JDBIManager.java   
/**
 * @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;
}
项目:verify-matching-service-adapter    文件:MatchingServiceAdapterApplication.java   
@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);
}
项目:verify-service-provider    文件:UsefulApplicationUrlsTableFormatter.java   
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()
        )
    );
}
项目:dropwizard-mybatis    文件:MyBatisFactory.java   
/**
 * 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;
}
项目:event-sourcing-cqrs-examples    文件:BankServiceApplication.java   
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));
}
项目:dropwizard-vavr    文件:VavrDBIFactory.java   
@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;
}
项目:talk-observing-distributed-systems    文件:HelloWorldMonolithApp.java   
@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");
}
项目:dropwizard-mybatis    文件:DefaultSqlSessionFactoryProvider.java   
/**
 * 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));
}
项目:jdbishard    文件:TestApp.java   
@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();
}
项目:stroom-query    文件:AuditedQueryBundle.java   
@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);
        }
    });
}
项目:plateyplatey-server    文件:App.java   
@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");
}
项目:stroom-stats    文件:HealthChecks.java   
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));
    }
项目:amigo-chatbot    文件:RiaBotServiceApplication.java   
@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");
}
项目:amigo-chatbot    文件:DBConfig.java   
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;
}
项目:amigo-chatbot    文件:ChatbotServiceApplication.java   
@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");
}
项目:amigo-chatbot    文件:DBConfig.java   
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;
}
项目:outland    文件:GuiceApplication.java   
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;
}
项目:outland    文件:ServerSuite.java   
@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()
                  );
                }
              };
            }
项目:dropwizard-dsegraph    文件:DseGraphFactory.java   
@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;
}
项目:haystack-client-java    文件:HelloWorldApplication.java   
@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);
}
项目:verify-service-provider    文件:VerifyServiceProviderApplication.java   
@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));
}
项目:dropwizard-mybatis    文件:MyBatisFactory.java   
/**
 * 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;
}
项目:echo    文件:ExecutionEngine.java   
@Override
public void run(ExecutionEngineConfiguration config, Environment env) {
    ResourceDirectoryClientFactory factory = new ResourceDirectoryClientFactory(
            config.getRdClientconfig().getRdAddress(),
            config.getRdClientconfig().getPortNumber()
    );
    env.jersey().register(new EchoApplicationResource(factory));
}
项目:minebox    文件:MinebdApplication.java   
@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);

    }
项目:verify-service-provider    文件:UsefulApplicationUrlsTableFormatter.java   
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());
}
项目:verify-hub    文件:StubEventSinkApplication.java   
@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);
}
项目:talk-observing-distributed-systems    文件:HelloWorldServiceApp.java   
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);
}
项目:verify-hub    文件:SamlProxyModule.java   
@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;
}
项目:talk-observing-distributed-systems    文件:IndexerServiceApplication.java   
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);
}
项目:verify-hub    文件:SamlProxyModule.java   
@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;
    });
}
项目:verify-hub    文件:SamlProxyModule.java   
@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);
}
项目:verify-hub    文件:EventSinkProxy.java   
@Inject
public EventSinkProxy(
        JsonClient jsonClient,
        @EventSink URI eventSinkUri,
        Environment environment) {
    this.jsonClient = jsonClient;
    this.eventSinkUri = eventSinkUri;
    this.environment = environment;
}
项目:verify-hub    文件:PolicyApplication.java   
@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);
}
项目:verify-hub    文件:PolicyApplication.java   
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);
}
项目:tools    文件:MinebdApplication.java   
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");
}
项目:verify-hub    文件:PolicyModule.java   
@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);
}
项目:verify-hub    文件:SamlEngineApplication.java   
@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, "/*");
}
项目:verify-hub    文件:SamlEngineModule.java   
@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;
}
项目:http-progressive-download-examples    文件:ResourcesClient.java   
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);
}
项目:soundwave    文件:ApiApplication.java   
@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);
}