io.dropwizard.setup.Environment Java Examples

The following examples show how to use io.dropwizard.setup.Environment. 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: MainApplication.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
/***
 * The context path must be set before configuring swagger
 * @param environment
 */
void configureSwagger(Environment environment, String basePath) {
  environment.jersey().register(new ApiListingResource());
  environment.jersey().register(new SwaggerJsonBareService());
  environment.jersey().register(new SwaggerSerializers());
  ScannerFactory.setScanner(new DefaultJaxrsScanner());
  environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
  BeanConfig config = new BeanConfig();

  // api specific configuration
  config.setTitle("SciGraph");
  config.setVersion("1.0.1");
  config.setResourcePackage("io.scigraph.services.resources");
  config.setScan(true);
  // TODO: Fix this so the swagger client generator can work correctly
  config.setBasePath("/" + basePath);
}
 
Example #2
Source File: GuiceBundle.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
@Override
public void run(final Configuration configuration, final Environment environment) throws Exception {
    // deep configuration parsing (config paths resolution)
    final GuiceyRunner runner = new GuiceyRunner(context, configuration, environment);

    // process guicey bundles
    runner.runBundles();
    // prepare guice modules for injector creation
    runner.prepareModules();
    // create injector
    runner.createInjector(injectorFactory,
            runner.analyzeAndRepackageBindings());
    // install extensions by instance
    runner.installExtensions();
    // inject command fields
    runner.injectCommands();

    runner.runFinished();
}
 
Example #3
Source File: App.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
@Override
public void run(AppConfiguration configuration, Environment environment) throws Exception {
    configuration.getZipkinClient().setTimeout(Duration.seconds(50));
    configuration.getZipkinClient().setConnectionRequestTimeout(Duration.seconds(50));

    Brave brave = configuration.getZipkinFactory().build(environment).get();

    final Client client = new ZipkinClientBuilder(environment, brave)
            .build(configuration.getZipkinClient());

    new MySQLStatementInterceptorManagementBean(brave.clientTracer());

    /**
     * Database
     */
    createDatabase();
    DatabaseUtils.executeDatabaseScript("init.sql");

    UserDAO userDAO = new UserDAO();

    // Register resources
    environment.jersey().register(new HelloHandler());
    environment.jersey().register(new SyncHandler(client));
    environment.jersey().register(new AsyncHandler(client, brave));
    environment.jersey().register(new UsersHandler(userDAO, client, brave));
}
 
Example #4
Source File: IronTestApplication.java    From irontest with Apache License 2.0 6 votes vote down vote up
private void createSampleResources(IronTestConfiguration configuration, Environment environment) {
    final JdbiFactory jdbiFactory = new JdbiFactory();
    final Jdbi jdbi = jdbiFactory.build(environment, configuration.getSampleDatabase(), "sampleDatabase");

    //  create DAO objects
    final ArticleDAO articleDAO = jdbi.onDemand(ArticleDAO.class);

    //  create database tables
    articleDAO.createTableIfNotExists();

    //  register APIs
    environment.jersey().register(new ArticleResource(articleDAO));

    //  register SOAP web services
    jaxWsBundle.publishEndpoint(new EndpointBuilder("/article", new ArticleSOAP(articleDAO)));
}
 
Example #5
Source File: PlannerApplication.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
@Override
public void run(PlannerConfiguration plannerConfiguration, Environment environment) throws Exception {
    PlanResource pr = new PlanResource( plannerConfiguration );
    RePlanResource rpr = new RePlanResource(plannerConfiguration.getDiscovererURL(),
                                            plannerConfiguration.getDeployableProviders());
    DamGenResource dgr = new DamGenResource(plannerConfiguration.getMonitorGeneratorURL(),
                                            plannerConfiguration.getMonitorGeneratorPort(),
                                            plannerConfiguration.getSlaGeneratorURL(),
                                            plannerConfiguration.getInfluxdbURL(),
                                            plannerConfiguration.getInfluxdbPort(),
                                            plannerConfiguration.getInfluxdbDatabase(),
                                            plannerConfiguration.getInfluxdbUsername(),
                                            plannerConfiguration.getInfluxdbPassword(),
                                            plannerConfiguration.getGrafanaUsername(),
                                            plannerConfiguration.getGrafanaPassword(),
                                            plannerConfiguration.getGrafanaEndpoint());

    environment.jersey().register(pr);
    environment.jersey().register(rpr);
    environment.jersey().register(dgr);

    //TODO: add health ckecks
}
 
Example #6
Source File: AdvancedAssetBundle.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
    public void run(T configuration, Environment environment) throws Exception {
        for (AssetConfiguration assetConf : configuration.getAssets()) {
            String resourcePath = assetConf.getResourcePath();
//            Preconditions.checkArgument(resourcePath.startsWith("/"), "%s is not an absolute path", resourcePath);
            Preconditions.checkArgument(!"/".equals(resourcePath), "%s is the classpath root", resourcePath);
            resourcePath = resourcePath.endsWith("/") ? resourcePath : (resourcePath + '/');
            String uriPath = assetConf.getUriPath();
            uriPath = uriPath.endsWith("/") ? uriPath : (uriPath + '/');
            LOGGER.info("Registering AssetBundle with name: {} for path {}", assetConf.getAssetsName(), uriPath + '*');
            HttpServlet assetServlet = null;
            switch (assetConf.getType()) {
                case "filesystem":
                    assetServlet = getFileAssetServlet(assetConf, resourcePath, uriPath);
                    break;
                case "classpath":
                    assetServlet = getClasspathAssetServlet(assetConf,resourcePath,uriPath);
                    break;
                case "http":
                    assetServlet = getHttpAssetServlet(assetConf, resourcePath, uriPath);
                    break;
            }
            environment.servlets().addServlet(assetConf.getAssetsName(), assetServlet).addMapping(uriPath + '*');
        }
    }
 
Example #7
Source File: AlarmStateTransitionHandler.java    From monasca-persister with Apache License 2.0 6 votes vote down vote up
@Inject
public AlarmStateTransitionHandler(Repo<AlarmStateTransitionedEvent> alarmRepo,
                                   Environment environment,
                                   @Assisted PipelineConfig configuration,
                                   @Assisted("threadId") String threadId,
                                   @Assisted("batchSize") int batchSize) {

  super(configuration, environment, threadId, batchSize);

  this.alarmRepo = alarmRepo;

  this.alarmStateTransitionCounter =
      environment.metrics()
          .counter(this.handlerName + "." + "alarm-state-transitions-added-to-batch-counter");

}
 
Example #8
Source File: SoaBundle.java    From soabase with Apache License 2.0 6 votes vote down vote up
private void checkAdminGuiceFeature(final Environment environment, final JerseyEnvironment jerseyEnvironment)
{
    try
    {
        Feature feature = new Feature()
        {
            @Override
            public boolean configure(FeatureContext context)
            {
                for ( Object obj : environment.jersey().getResourceConfig().getSingletons() )
                {
                    if ( obj instanceof InternalFeatureRegistrations )
                    {
                        ((InternalFeatureRegistrations)obj).apply(context);
                    }
                }
                return true;
            }
        };
        jerseyEnvironment.register(feature);
    }
    catch ( Exception ignore )
    {
        // ignore - GuiceBundle not added
    }
}
 
Example #9
Source File: UsefulApplicationUrlsTableFormatter.java    From verify-service-provider with MIT License 6 votes vote down vote up
private static List<ApplicationUrlsGenerator> extractTableRowForDefaultServer(Environment environment, ServerConnector connector) {
    String protocol = connector.getDefaultProtocol();
    int port = connector.getLocalPort();

    if ("admin".equals(connector.getName())) {
        String adminContextPath = environment.getAdminContext().getContextPath();

        return ImmutableList.of(
            new ApplicationUrlsGenerator(ADMIN_URL_TYPE, isHttps(protocol), port, adminContextPath),
            new ApplicationUrlsGenerator(HEALTHCHECK_URL_TYPE, isHttps(protocol), port, adminContextPath)
        );
    }

    return ImmutableList.of(
        new ApplicationUrlsGenerator(APPLICATION_URL_TYPE, isHttps(protocol), port, environment.getApplicationContext().getContextPath())
    );
}
 
Example #10
Source File: UsefulApplicationUrlsTableFormatter.java    From verify-service-provider with MIT License 6 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 #11
Source File: StreamlineApplication.java    From streamline with Apache License 2.0 6 votes vote down vote up
@Override
public void run(StreamlineConfiguration configuration, Environment environment) throws Exception {
    AbstractServerFactory sf = (AbstractServerFactory) configuration.getServerFactory();
    // disable all default exception mappers
    sf.setRegisterDefaultExceptionMappers(false);

    environment.jersey().register(GenericExceptionMapper.class);

    registerResources(configuration, environment, getSubjectFromLoginImpl(configuration));

    if (configuration.isEnableCors()) {
        List<String> urlPatterns = configuration.getCorsUrlPatterns();
        if (urlPatterns != null && !urlPatterns.isEmpty()) {
            enableCORS(environment, urlPatterns);
        }
    }

    setupCustomTrustStore(configuration);

    addSecurityHeaders(environment);

    addServletFilters(configuration, environment);

}
 
Example #12
Source File: ParametersInjectionGuiceyTest.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
@Test
void checkAllPossibleParams(Application app,
                            AutoScanApplication app2,
                            Configuration conf,
                            TestConfiguration conf2,
                            Environment env,
                            ObjectMapper mapper,
                            Injector injector,
                            ClientSupport clientSupport,
                            DummyService service,
                            @Jit JitService jit) {
    assertNotNull(app);
    assertNotNull(app2);
    assertNotNull(conf);
    assertNotNull(conf2);
    assertNotNull(env);
    assertNotNull(mapper);
    assertNotNull(injector);
    assertNotNull(clientSupport);
    assertNotNull(service);
    assertNotNull(jit);
}
 
Example #13
Source File: MockApplication.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
public void run(MockConfiguration configuration, Environment environment) throws Exception
{
    AbstractBinder abstractBinder = new AbstractBinder()
    {
        @Override
        protected void configure()
        {
            bind(new MockHK2Injected()).to(MockHK2Injected.class);
        }
    };
    environment.jersey().register(abstractBinder);
    environment.jersey().register(MockResource.class);
    LifeCycle.Listener listener = new AbstractLifeCycle.AbstractLifeCycleListener()
    {
        @Override
        public void lifeCycleStarted(LifeCycle event)
        {
            System.out.println("Starting...");
            startedLatch.countDown();
        }
    };
    environment.lifecycle().addLifeCycleListener(listener);
}
 
Example #14
Source File: DBIFactory.java    From dropwizard-java8 with Apache License 2.0 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 OptionalArgumentFactory(configuration.getDriverClass()));
    dbi.registerContainerFactory(new OptionalContainerFactory());
    dbi.registerArgumentFactory(new LocalDateArgumentFactory());
    dbi.registerArgumentFactory(new OptionalLocalDateArgumentFactory());
    dbi.registerArgumentFactory(new LocalDateTimeArgumentFactory());
    dbi.registerArgumentFactory(new OptionalLocalDateTimeArgumentFactory());
    dbi.registerMapper(new LocalDateMapper());
    dbi.registerMapper(new LocalDateTimeMapper());

    final Optional<TimeZone> tz = Optional.ofNullable(databaseTimeZone().orNull());
    dbi.registerArgumentFactory(new InstantArgumentFactory(tz));
    dbi.registerArgumentFactory(new OptionalInstantArgumentFactory(tz));
    dbi.registerMapper(new InstantMapper(tz));


    return dbi;
}
 
Example #15
Source File: StreamlineApplication.java    From streamline with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void addServletFilters(StreamlineConfiguration configuration, Environment environment) {
    List<ServletFilterConfiguration> servletFilterConfigurations = configuration.getServletFilters();
    if (servletFilterConfigurations != null && !servletFilterConfigurations.isEmpty()) {
        for (ServletFilterConfiguration servletFilterConfiguration: servletFilterConfigurations) {
            try {
                addServletFilter(environment, servletFilterConfiguration.getClassName(),
                        (Class<? extends Filter>) Class.forName(servletFilterConfiguration.getClassName()),
                        servletFilterConfiguration.getParams());
            } catch (Exception e) {
                LOG.error("Error occurred while adding servlet filter {}", servletFilterConfiguration);
                throw new RuntimeException(e);
            }
        }
    } else {
        LOG.info("No servlet filters configured");
    }
}
 
Example #16
Source File: RateLimitBundle.java    From ratelimitj with Apache License 2.0 6 votes vote down vote up
@Override
public void run(final Configuration configuration,
                final Environment environment) {

    environment.jersey().register(new RateLimitingFactoryProvider.Binder(requestRateLimiterFactory));
    environment.jersey().register(new RateLimited429EnforcerFeature());

    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() {
        }

        @Override
        public void stop() throws Exception {
            requestRateLimiterFactory.close();
        }
    });
}
 
Example #17
Source File: TaskScanner.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void scanAndAdd(Environment environment, Injector injector, Reflections reflections) {
    Set<Class<? extends Task>> taskClasses = reflections.getSubTypesOf(Task.class);
    for (Class<? extends Task> task : taskClasses) {
        environment.admin().addTask(injector.getInstance(task));
        LOGGER.info("Added task: " + task);
    }
}
 
Example #18
Source File: SoaBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
private void addMetrics(Environment environment)
{
    Metric metric = new Gauge<Double>()
    {
        private double lastValue = 0.0;

        @Override
        public Double getValue()
        {
            try
            {
                MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
                ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
                AttributeList list = mbs.getAttributes(name, new String[]{"SystemCpuLoad"});
                if ( (list != null) && (list.size() > 0) )
                {
                    // unfortunately, this bean reports bad values occasionally. Filter them out.
                    Object value = list.asList().get(0).getValue();
                    double d = (value instanceof Number) ? ((Number)value).doubleValue() : 0.0;
                    d = ((d > 0.0) && (d < 1.0)) ? d : lastValue;
                    lastValue = d;
                    return d;
                }
            }
            catch ( Exception ignore )
            {
                // ignore
            }
            return lastValue;
        }
    };
    environment.metrics().register("system.cpu.load", metric);
}
 
Example #19
Source File: HelloWorldService.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void run(HelloWorldConfiguration config, Environment environment) throws UnknownHostException {
    if ("com.mysql.cj.jdbc.Driver".equals(config.getDatabaseConfiguration().getDriverClass())) { // register below for default dropwizard test only
        environment.jersey().register(new JsonResource()); // Test type 1: JSON serialization
        environment.jersey().register(new TextResource()); // Test type 6: Plaintext
    }
    environment.jersey().register(new WorldResource(new WorldHibernateImpl(hibernate.getSessionFactory()))); // Test types 2, 3 & 5: Single database query, Multiple database queries & Database updates
    environment.jersey().register(new FortuneResource(new FortuneHibernateImpl(hibernate.getSessionFactory()))); // Test type 4: Fortunes
}
 
Example #20
Source File: RandomPortsListener.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public void onRun(final Configuration configuration,
                  final Environment environment,
                  final DropwizardTestSupport<Configuration> rule) throws Exception {
    final ServerFactory server = configuration.getServerFactory();
    if (server instanceof SimpleServerFactory) {
        ((HttpConnectorFactory) ((SimpleServerFactory) server).getConnector()).setPort(0);
    } else {
        final DefaultServerFactory dserv = (DefaultServerFactory) server;
        ((HttpConnectorFactory) dserv.getApplicationConnectors().get(0)).setPort(0);
        ((HttpConnectorFactory) dserv.getAdminConnectors().get(0)).setPort(0);
    }
}
 
Example #21
Source File: TenacityConfiguredBundle.java    From tenacity with Apache License 2.0 5 votes vote down vote up
protected void configureHystrix(T configuration, Environment environment) {
    final ServerFactory serverFactory = configuration.getServerFactory();
    final Duration shutdownGracePeriod =
            (serverFactory instanceof AbstractServerFactory)
            ? ((AbstractServerFactory) serverFactory).getShutdownGracePeriod()
            : Duration.seconds(30L);
    environment.lifecycle().manage(new ManagedHystrix(shutdownGracePeriod));
}
 
Example #22
Source File: ServiceMain.java    From helios with Apache License 2.0 5 votes vote down vote up
protected static Environment createEnvironment(final String name) {
  final Validator validator = Validation
      .byProvider(HibernateValidator.class)
      .configure()
      .addValidatedValueHandler(new OptionalValidatedValueUnwrapper())
      .buildValidatorFactory()
      .getValidator();
  return new Environment(name,
      Jackson.newObjectMapper(),
      validator,
      new MetricRegistry(),
      Thread.currentThread().getContextClassLoader());
}
 
Example #23
Source File: WorkshopApplication.java    From java-perf-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void run(WorkshopConfiguration configuration, Environment environment) {
    final WorkshopResource resource = new WorkshopResource(configuration);
    environment.jersey().register(resource);
    environment.healthChecks().register("remoteService", new RemoteServiceHealthCheck(configuration));
    environment.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
}
 
Example #24
Source File: SoaBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
static <T> T checkManaged(Environment environment, T obj)
{
    if ( obj instanceof Managed )
    {
        environment.lifecycle().manage((Managed)obj);
    }
    return obj;
}
 
Example #25
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 #26
Source File: ServiceModule.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Provides @Singleton @Readonly ManagedDataSource readonlyDataSource(Environment environment,
    KeywhizConfig config) {
  DataSourceFactory dataSourceFactory = config.getReadonlyDataSourceFactory();
  ManagedDataSource dataSource = dataSourceFactory.build(environment.metrics(), "db-readonly");
  environment.lifecycle().manage(dataSource);

  environment.healthChecks().register("db-readonly-health",
      new JooqHealthCheck(dataSource, RETURN_UNHEALTHY));

  return dataSource;
}
 
Example #27
Source File: GrpcServerFactory.java    From dropwizard-grpc with Apache License 2.0 5 votes vote down vote up
/**
 * @param environment to use
 * @return A {@link ServerBuilder}, with port and optional transport security set from the configuration. To use
 *         this, add gRPC services to the server, then call build(). The returned server is lifecycle-managed in the
 *         given {@link Environment}.
 */
public ServerBuilder<?> builder(final Environment environment) {
    final ServerBuilder<?> originBuilder;
    final ServerBuilder<?> dropwizardBuilder;
    originBuilder = ServerBuilder.forPort(port);
    dropwizardBuilder = new DropwizardServerBuilder(environment, originBuilder, shutdownPeriod);
    if (certChainFile != null && privateKeyFile != null) {
        dropwizardBuilder.useTransportSecurity(certChainFile.toFile(), privateKeyFile.toFile());
    }
    return dropwizardBuilder;
}
 
Example #28
Source File: KTSDApplication.java    From kudu-ts with Apache License 2.0 5 votes vote down vote up
@Override
public void run(KTSDConfiguration configuration,
                Environment environment) throws Exception {
  ManagedKuduTS ts = new ManagedKuduTS(configuration);
  environment.lifecycle().manage(ts);
  environment.jersey().register(new PutResource(ts.ts(), environment.getObjectMapper()));
  environment.jersey().register(new QueryResource(ts.ts(), environment.getObjectMapper()));
  environment.jersey().register(new SuggestResource(ts.ts()));
}
 
Example #29
Source File: ServerApplication.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static void enableRequestResponseLogging(final Environment environment) {
  environment
      .jersey()
      .register(
          new LoggingFeature(
              Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME),
              Level.INFO,
              LoggingFeature.Verbosity.PAYLOAD_ANY,
              LoggingFeature.DEFAULT_MAX_ENTITY_SIZE));
}
 
Example #30
Source File: RateLimitApplication.java    From ratelimitj with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) {

    environment.jersey().register(new LoginResource());
    environment.jersey().register(new UserResource());
    environment.jersey().register(new TrekResource());

    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<PrincipalImpl>()
                    .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class));
}