Java Code Examples for io.dropwizard.setup.Environment

The following examples show how to use io.dropwizard.setup.Environment. These examples are extracted from open source projects. 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 Project: dropwizard-guicey   Source File: GuiceBundle.java    License: 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 2
Source Project: hawkular-apm   Source File: App.java    License: 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 3
Source Project: SeaCloudsPlatform   Source File: PlannerApplication.java    License: 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 4
Source Project: soabase   Source File: SoaBundle.java    License: 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 5
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 6
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 7
Source Project: streamline   Source File: StreamlineApplication.java    License: 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 8
Source Project: soabase   Source File: MockApplication.java    License: 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 9
Source Project: streamline   Source File: StreamlineApplication.java    License: 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 10
Source Project: ratelimitj   Source File: RateLimitBundle.java    License: 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 11
Source Project: SciGraph   Source File: MainApplication.java    License: 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 12
Source Project: dropwizard-java8   Source File: DBIFactory.java    License: 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 13
Source Project: dropwizard-guicey   Source File: ParametersInjectionGuiceyTest.java    License: 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 14
@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 15
@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 16
Source Project: irontest   Source File: IronTestApplication.java    License: 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 17
Source Project: judgels   Source File: SealtielApplication.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run(SealtielApplicationConfiguration config, Environment env) throws Exception {
    SealtielConfiguration sealtielConfig = config.getSealtielConfig();
    SealtielComponent component = DaggerSealtielComponent.builder()
            .sealtielModule(new SealtielModule(sealtielConfig))
            .rabbitMQModule(new RabbitMQModule(sealtielConfig.getRabbitMQConfig()))
            .build();

    env.jersey().register(JudgelsJerseyFeature.INSTANCE);

    env.jersey().register(component.pingResource());
    env.jersey().register(component.messageResource());

    env.healthChecks().register("rabbitmq", component.rabbitmqHealthCheck());
}
 
Example 18
Source Project: emodb   Source File: MetricsStashStateListener.java    License: 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 19
Source Project: triplea   Source File: ServerApplication.java    License: 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 20
Source Project: microservices-comparison   Source File: HelloModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
public Client createHttpClient(Environment environment, DropwizardServerConfiguration configuration) {
    if (client == null) {
        client = new JerseyClientBuilder(environment).using(configuration.getJerseyClientConfiguration()).build("internal client");
    }
    return client;
}
 
Example 21
Source Project: robe   Source File: WebSocketScanner.java    License: 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<?>> wsClasses = reflections.getTypesAnnotatedWith(RobeWebSocket.class);
    for (Class<?> ws : wsClasses) {
        RobeWebSocket ann = ws.getAnnotation(RobeWebSocket.class);
        String path = ann.path() + (ann.subPaths() ? "/*" : "");
        path = path.charAt(0) != '/' ? path = "/" + path : path;
        environment.servlets().addServlet(ann.path(), new WebSocketServlet((Class<WebSocket>) ws)).addMapping(path);
        LOGGER.info("Added websocket: " + ws);
    }

}
 
Example 22
Source Project: dropwizard-mongo   Source File: MongoFactory.java    License: Apache License 2.0 5 votes vote down vote up
private List<ServerAddress> buildServerAddresses(List<ServerAddressBuilder> conns, Environment env) throws UnknownHostException {
    final List<ServerAddress> sal = new ArrayList<>(conns.size());
    for(ServerAddressBuilder factory : conns) {
        sal.add(factory.build(env));
    }

    return sal;
}
 
Example 23
@Override
public void run(DashboardTestConfiguration configuration, Environment environment) throws Exception {
    // Generating  HTTP Clients
    Client jerseyClient = new JerseyClientBuilder(environment).using(configuration.getJerseyClientConfiguration())
            .build(getName());

    // Configuring HealthChecks
    environment.healthChecks().register(getName(), new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return Result.healthy();
        }
    });
}
 
Example 24
Source Project: fabric-api   Source File: BlockExplorerApp.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run(BlockExplorerConfiguration configuration, Environment environment) throws Exception {
    BCSAPI api = hyperLedgerBundle.getBCSAPI();
    final FilterRegistration.Dynamic cors =
            environment.servlets().addFilter("CORS", CrossOriginFilter.class);

    // Configure CORS parameters
    cors.setInitParameter("allowedOrigins", "*");
    cors.setInitParameter("allowedHeaders", "*");
    cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    // Add URL mapping
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    environment.jersey().register(new ExplorerResource(api));
}
 
Example 25
Source Project: soabase   Source File: SqlBundle.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run(T configuration, Environment environment) throws Exception
{
    SqlConfiguration sqlConfiguration = ComposedConfigurationAccessor.access(configuration, environment, SqlConfiguration.class);
    try
    {
        try ( InputStream stream = Resources.getResource(sqlConfiguration.getMybatisConfigUrl()).openStream() )
        {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
            Configuration mybatisConfiguration = sqlSessionFactory.getConfiguration();
            mybatisConfiguration.addMapper(AttributeEntityMapper.class);
            final SqlSession session = sqlSessionFactory.openSession(true);

            SoaBundle.getFeatures(environment).putNamed(session, SqlSession.class, sqlConfiguration.getName());
            Managed managed = new Managed()
            {
                @Override
                public void start() throws Exception
                {

                }

                @Override
                public void stop() throws Exception
                {
                    session.close();
                }
            };
            environment.lifecycle().manage(managed);
        }
    }
    catch ( Exception e )
    {
        log.error("Could not initialize MyBatis", e);
        throw new RuntimeException(e);
    }
}
 
Example 26
Source Project: crnk-framework   Source File: DropwizardService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run(DropwizardConfiguration dropwizardConfiguration, Environment environment) {
	// here we make use of a module as example instead of using service discovery (CDI, Spring, etc.)
	// tag::docs[]
	SimpleModule module = new SimpleModule("example");
	module.addRepository(new ProjectRepository());

	CrnkFeature crnkFeature = new CrnkFeature();
	crnkFeature.addModule(module);

	environment.jersey().register(crnkFeature);
	// end::docs[]
}
 
Example 27
Source Project: keywhiz   Source File: StatusResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  this.registry = mock(HealthCheckRegistry.class);
  this.environment = mock(Environment.class);
  this.keywhizConfig = mock(KeywhizConfig.class);

  when(environment.healthChecks()).thenReturn(registry);
  when(keywhizConfig.getStatusCacheExpiry()).thenReturn(Duration.ofSeconds(1));

  this.status = new StatusResource(keywhizConfig, environment);
}
 
Example 28
Source Project: triplea   Source File: ServerApplication.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Jdbi createJdbi(final AppConfig configuration, final Environment environment) {
  final JdbiFactory factory = new JdbiFactory();
  final Jdbi jdbi =
      factory.build(environment, configuration.getDatabase(), "postgresql-connection-pool");
  JdbiDatabase.registerRowMappers(jdbi);

  if (configuration.isLogSqlStatements()) {
    JdbiDatabase.registerSqlLogger(jdbi);
  }
  return jdbi;
}
 
Example 29
Source Project: pay-publicapi   Source File: PublicApi.java    License: MIT License 5 votes vote down vote up
private void initialiseMetrics(PublicApiConfig configuration, Environment environment) {
    GraphiteSender graphiteUDP = new GraphiteUDP(configuration.getGraphiteHost(), Integer.parseInt(configuration.getGraphitePort()));
    GraphiteReporter.forRegistry(environment.metrics())
            .prefixedWith(SERVICE_METRICS_NODE)
            .build(graphiteUDP)
            .start(GRAPHITE_SENDING_PERIOD_SECONDS, TimeUnit.SECONDS);
}
 
Example 30
Source Project: soabase   Source File: ExampleAppBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run(ExampleConfiguration configuration, Environment environment) throws Exception
{
    environment.lifecycle().manage(this);

    internalRun(configuration, environment);

    SoaInfo info = SoaBundle.getFeatures(environment).getSoaInfo();
    System.err.println("Main port: " + info.getMainPort());
    System.err.println("Admin port: " + info.getAdminPort());
}