Java Code Examples for io.dropwizard.setup.Environment#metrics()

The following examples show how to use io.dropwizard.setup.Environment#metrics() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ArmeriaServerFactory.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public Server build(Environment environment) {
    Objects.requireNonNull(environment, "environment");
    printBanner(environment.getName());
    final MetricRegistry metrics = environment.metrics();
    final ThreadPool threadPool = createThreadPool(metrics);
    final Server server = buildServer(environment.lifecycle(), threadPool);

    final JerseyEnvironment jersey = environment.jersey();
    if (!isJerseyEnabled()) {
        jersey.disable();
    }

    addDefaultHandlers(server, environment, metrics);
    serverBuilder = buildServerBuilder(server, metrics);
    return server;
}
 
Example 2
Source File: BreakerboxService.java    From breakerbox with Apache License 2.0 6 votes vote down vote up
private static void setupLdapAuth(LdapConfiguration ldapConfiguration, Environment environment) {
    final LdapAuthenticator ldapAuthenticator = new LdapAuthenticator(ldapConfiguration);
    final CachingAuthenticator<BasicCredentials, User> cachingAuthenticator =
            new CachingAuthenticator<>(
                    environment.metrics(),
                    TenacityAuthenticator.wrap(
                            new ResourceAuthenticator(ldapAuthenticator), BreakerboxDependencyKey.BRKRBX_LDAP_AUTH),
                    ldapConfiguration.getCachePolicy()
            );
    environment.jersey().register(new AuthDynamicFeature(
                    new BasicCredentialAuthFilter.Builder<User>()
                            .setAuthenticator(cachingAuthenticator)
                            .setRealm("breakerbox")
                            .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
}
 
Example 3
Source File: JdbiStore.java    From breakerbox with Apache License 2.0 6 votes vote down vote up
public JdbiStore(JdbiConfiguration storeConfiguration,
                 Environment environment,
                 DBI database) {
    super(storeConfiguration, environment);
    database.registerArgumentFactory(new DependencyIdArgumentFactory());
    database.registerArgumentFactory(new ServiceIdArgumentFactory());
    database.registerArgumentFactory(new TenacityConfigurationArgumentFactory(environment.getObjectMapper()));
    database.registerArgumentFactory(new DateTimeArgumentFactory());

    dependencyDB = database.onDemand(DependencyDB.class);
    serviceDB = database.onDemand(ServiceDB.class);

    this.configuration = storeConfiguration;

    metricRegistry = environment.metrics();
}
 
Example 4
Source File: ExampleAppTest.java    From dropwizard-auth-ldap with Apache License 2.0 6 votes vote down vote up
@Override
public void run(ExampleAppConfiguration configuration, Environment environment) throws Exception {
    final LdapConfiguration ldapConfiguration = configuration.getLdapConfiguration();

    Authenticator<BasicCredentials, User> ldapAuthenticator = new CachingAuthenticator<>(
            environment.metrics(),
            new ResourceAuthenticator(new LdapAuthenticator(ldapConfiguration)),
            ldapConfiguration.getCachePolicy());

    environment.jersey().register(new AuthDynamicFeature(
            new BasicCredentialAuthFilter.Builder<User>()
                    .setAuthenticator(ldapAuthenticator)
                    .setRealm("LDAP")
                    .buildAuthFilter()));

    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));

    environment.healthChecks().register("ldap", new LdapHealthCheck<>(
            new ResourceAuthenticator(new LdapCanAuthenticate(ldapConfiguration))));
}
 
Example 5
Source File: RabbitMQBundle.java    From dropwizard-experiment with MIT License 6 votes vote down vote up
@Override
public void run(HasRabbitMQConfiguration configuration, Environment environment) throws Exception {
    RabbitMQConfiguration rabbitMQ = configuration.getRabbitMq();
    factory.setHost(rabbitMQ.getHost());
    factory.setVirtualHost(rabbitMQ.getVirtualHost());
    factory.setUsername(rabbitMQ.getUsername());
    factory.setPassword(rabbitMQ.getPassword());
    factory.setPort(rabbitMQ.getPort());
    factory.setAutomaticRecoveryEnabled(true);

    log.info("Connecting to RabbitMQ on '{}' with username '{}'.", factory.getHost(), factory.getUsername());

    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.basicQos(1);

    environment.lifecycle().manage(this);
    environment.healthChecks().register("rabbitmq", new RabbitMQHealthCheck(this));
    metrics = environment.metrics();
}
 
Example 6
Source File: MetricsStashStateListener.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Environment environment, PluginServerMetadata pluginServerMetadata, Void ignore) {
    MetricRegistry metricRegistry = environment.metrics();
    _stashParticipantMeter = metricRegistry.meter(MetricRegistry.name("bv.emodb.scan", "ScanUploader", "scan-started"));
    _stashStartedMeter = metricRegistry.meter(MetricRegistry.name("bv.emodb.scan", "ScanUploader", "scan-participant"));
    _stashCompletedMeter = metricRegistry.meter(MetricRegistry.name("bv.emodb.scan", "ScanUploader", "scan-completed"));
    _tashCanceledMeter = metricRegistry.meter(MetricRegistry.name("bv.emodb.scan", "ScanUploader", "scan-canceled"));
}
 
Example 7
Source File: SoaBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
private void initJerseyAdmin(SoaConfiguration configuration, SoaFeaturesImpl features, Ports ports, final Environment environment, AbstractBinder binder)
{
    if ( (configuration.getAdminJerseyPath() == null) || !ports.adminPort.hasPort() )
    {
        return;
    }

    String jerseyRootPath = configuration.getAdminJerseyPath();
    if ( !jerseyRootPath.endsWith("/*") )
    {
        if ( jerseyRootPath.endsWith("/") )
        {
            jerseyRootPath += "*";
        }
        else
        {
            jerseyRootPath += "/*";
        }
    }

    DropwizardResourceConfig jerseyConfig = new DropwizardResourceConfig(environment.metrics());
    jerseyConfig.setUrlPattern(jerseyRootPath);

    JerseyContainerHolder jerseyServletContainer = new JerseyContainerHolder(new ServletContainer(jerseyConfig));
    environment.admin().addServlet("soa-admin-jersey", jerseyServletContainer.getContainer()).addMapping(jerseyRootPath);

    JerseyEnvironment jerseyEnvironment = new JerseyEnvironment(jerseyServletContainer, jerseyConfig);
    features.putNamed(jerseyEnvironment, JerseyEnvironment.class, SoaFeatures.ADMIN_NAME);
    jerseyEnvironment.register(SoaApis.class);
    jerseyEnvironment.register(DiscoveryApis.class);
    jerseyEnvironment.register(DynamicAttributeApis.class);
    jerseyEnvironment.register(LoggingApis.class);
    jerseyEnvironment.register(binder);
    jerseyEnvironment.setUrlPattern(jerseyConfig.getUrlPattern());
    jerseyEnvironment.register(new JacksonMessageBodyProvider(environment.getObjectMapper()));

    checkCorsFilter(configuration, environment.admin());
    checkAdminGuiceFeature(environment, jerseyEnvironment);
}
 
Example 8
Source File: RufusApplication.java    From rufus with MIT License 4 votes vote down vote up
@Override
public void run(RufusConfiguration conf, Environment env) throws Exception {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(env, conf.getDataSourceFactory(), DB_SOURCE);

    final UserDao userDao = jdbi.onDemand(UserDao.class);
    final ArticleDao articleDao = jdbi.onDemand(ArticleDao.class);

    final FeedProcessorImpl processor = FeedProcessorImpl.newInstance(articleDao);
    final FeedParser parser = new FeedParser(articleDao, processor);

    final JwtConsumer jwtConsumer = new JwtConsumerBuilder()
        .setAllowedClockSkewInSeconds(30)
        .setRequireExpirationTime()
        .setRequireSubject()
        .setVerificationKey(new HmacKey(VERIFICATION_KEY))
        .setRelaxVerificationKeyValidation()
        .build();
    final CachingJwtAuthenticator<User> cachingJwtAuthenticator = new CachingJwtAuthenticator<>(
        env.metrics(),
        new JwtAuthenticator(userDao),
        conf.getAuthenticationCachePolicy()
    );

    env.jersey().register(new ArticleResource(userDao, articleDao, processor, parser));
    env.jersey().register(
        new UserResource(
            new BasicAuthenticator(userDao),
            new TokenGenerator(VERIFICATION_KEY),
            userDao,
            articleDao
        )
    );

    //route source
    env.jersey().setUrlPattern(ROOT_PATH);

    env.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
    env.jersey().register(new AuthDynamicFeature(
        new JwtAuthFilter.Builder<User>()
            .setJwtConsumer(jwtConsumer)
            .setRealm(REALM)
            .setPrefix(BEARER)
            .setAuthenticator(cachingJwtAuthenticator)
            .buildAuthFilter()
    ));
}
 
Example 9
Source File: PublicApi.java    From pay-publicapi with MIT License 4 votes vote down vote up
@Override
public void run(PublicApiConfig configuration, Environment environment) {
    initialiseSSLSocketFactory();

    final Injector injector = Guice.createInjector(new PublicApiModule(configuration, environment));

    environment.healthChecks().register("ping", new Ping());

    environment.jersey().register(injector.getInstance(HealthCheckResource.class));
    environment.jersey().register(injector.getInstance(PaymentsResource.class));
    environment.jersey().register(injector.getInstance(DirectDebitEventsResource.class));
    environment.jersey().register(injector.getInstance(PaymentRefundsResource.class));
    environment.jersey().register(injector.getInstance(RequestDeniedResource.class));
    environment.jersey().register(injector.getInstance(MandatesResource.class));
    environment.jersey().register(injector.getInstance(SearchRefundsResource.class));
    environment.jersey().register(injector.getInstance(DirectDebitPaymentsResource.class));
    environment.jersey().register(injector.getInstance(TransactionsResource.class));
    environment.jersey().register(injector.getInstance(TelephonePaymentNotificationResource.class));
    environment.jersey().register(new InjectingValidationFeature(injector));
    environment.jersey().register(injector.getInstance(ReturnUrlValidator.class));

    environment.jersey().register(injector.getInstance(RateLimiterFilter.class));
    environment.jersey().register(injector.getInstance(LoggingMDCRequestFilter.class));

    environment.servlets().addFilter("ClearMdcValuesFilter", injector.getInstance(ClearMdcValuesFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    environment.servlets().addFilter("AuthorizationValidationFilter", injector.getInstance(AuthorizationValidationFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    environment.servlets().addFilter("LoggingFilter", injector.getInstance(LoggingFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    /*
       Turn off 'FilteringJacksonJaxbJsonProvider' which overrides dropwizard JacksonMessageBodyProvider.
       Fails on Integration tests if not disabled. 
           - https://github.com/dropwizard/dropwizard/issues/1341
    */
    environment.jersey().property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, Boolean.TRUE);

    CachingAuthenticator<String, Account> cachingAuthenticator = new CachingAuthenticator<>(
            environment.metrics(),
            injector.getInstance(AccountAuthenticator.class),
            configuration.getAuthenticationCachePolicy());

    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<Account>()
                    .setAuthenticator(cachingAuthenticator)
                    .setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Account.class));

    attachExceptionMappersTo(environment.jersey());

    initialiseMetrics(configuration, environment);

    //health check removed as redis is not a mandatory dependency
    environment.healthChecks().unregister("redis");
}
 
Example 10
Source File: BaragonDataModule.java    From Baragon with Apache License 2.0 4 votes vote down vote up
@Provides
@Singleton
public MetricRegistry provideRegistry(Environment environment) {
  return environment.metrics();
}
 
Example 11
Source File: SnowizardApplication.java    From snowizard with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void run(final SnowizardConfiguration config,
        final Environment environment) throws Exception {

    environment.jersey().register(new SnowizardExceptionMapper());
    environment.jersey().register(new ProtocolBufferMessageBodyProvider());

    if (config.isCORSEnabled()) {
        final FilterRegistration.Dynamic filter = environment.servlets()
                .addFilter("CrossOriginFilter", CrossOriginFilter.class);
        filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),
                true, "/*");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM,
                "GET");
    }

    final IdWorker worker = new IdWorker(config.getWorkerId(),
            config.getDatacenterId(), 0L, config.validateUserAgent(),
            environment.metrics());

    environment.metrics().register(
            MetricRegistry.name(SnowizardApplication.class, "worker_id"),
            new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return config.getWorkerId();
                }
            });

    environment.metrics()
    .register(
            MetricRegistry.name(SnowizardApplication.class,
                    "datacenter_id"), new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return config.getDatacenterId();
                }
            });

    // health check
    environment.healthChecks().register("empty", new EmptyHealthCheck());

    // resources
    environment.jersey().register(new IdResource(worker));
    environment.jersey().register(new PingResource());
    environment.jersey().register(new VersionResource());
}