io.dropwizard.Configuration Java Examples

The following examples show how to use io.dropwizard.Configuration. 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: TestGuiceyAppExtension.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
@SuppressWarnings({"unchecked", "checkstyle:Indentation"})
private <C extends Configuration> DropwizardTestSupport<C> create(
        final ExtensionContext context,
        final Class<? extends Application> app,
        final String configPath,
        final String configPrefix,
        final String... overrides) {
    // NOTE: DropwizardTestSupport.ServiceListener listeners would be called ONLY on start!
    return new DropwizardTestSupport<>((Class<? extends Application<C>>) app,
            configPath,
            configPrefix,
            application -> {
                final TestCommand<C> cmd = new TestCommand<>(application);
                // need to hold command itself in order to properly shutdown it later
                getExtensionStore(context).put(TestCommand.class, cmd);
                return cmd;
            },
            ConfigOverrideUtils.convert(configPrefix, overrides));
}
 
Example #2
Source File: GoodbyeApp.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
protected void internalRun(Configuration configuration, Environment environment)
{
    Metric metric = new Gauge<Integer>()
    {
        final Random random = new Random();

        @Override
        public Integer getValue()
        {
            return random.nextInt(100);
        }
    };
    environment.metrics().register("goodbye-random", metric);

    environment.jersey().register(GoodbyeResource.class);
    JerseyEnvironment adminJerseyEnvironment = SoaBundle.getFeatures(environment).getNamedRequired(JerseyEnvironment.class, SoaFeatures.ADMIN_NAME);
    adminJerseyEnvironment.register(GoodbyeAdminResource.class);
}
 
Example #3
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 #4
Source File: ServiceModule.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
@Override protected void configure() {
  // Initialize the BouncyCastle security provider for cryptography support.
  BouncyCastle.require();

  bind(Clock.class).toInstance(Clock.systemUTC());

  install(new CookieModule(config.getCookieKey()));
  install(new CryptoModule(config.getDerivationProviderClass(), config.getContentKeyStore()));

  bind(CookieConfig.class).annotatedWith(SessionCookie.class)
      .toInstance(config.getSessionCookieConfig());

  // TODO(justin): Consider https://github.com/HubSpot/dropwizard-guice.
  bind(Environment.class).toInstance(environment);
  bind(Configuration.class).toInstance(config);
  bind(KeywhizConfig.class).toInstance(config);
}
 
Example #5
Source File: MyApp.java    From dropwizard-websockets with MIT License 6 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws InvalidKeySpecException, NoSuchAlgorithmException, ServletException, DeploymentException {
    environment.lifecycle().addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {

        @Override
        public void lifeCycleStarted(LifeCycle event) {
            cdl.countDown();
        }
    });
    environment.jersey().register(new MyResource());
    environment.healthChecks().register("alive", new HealthCheck() {
        @Override
        protected HealthCheck.Result check() throws Exception {
            return HealthCheck.Result.healthy();
        }
    });

    // Using ServerEndpointConfig lets you inject objects to the websocket endpoint:
    final ServerEndpointConfig config = ServerEndpointConfig.Builder.create(EchoServer.class, "/extends-ws").build();
    // config.getUserProperties().put(Environment.class.getName(), environment);
    // Then you can get it from the Session object
    // - obj = session.getUserProperties().get("objectName");            
    websocketBundle.addEndpoint(config);
}
 
Example #6
Source File: DynamicAttributesBundle.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception
{
    SoaConfiguration soaConfiguration = ComposedConfigurationAccessor.access(configuration, environment, SoaConfiguration.class);

    updateInstanceName(soaConfiguration);
    List<String> scopes = Lists.newArrayList();
    scopes.add(soaConfiguration.getInstanceName());
    scopes.add(soaConfiguration.getServiceName());
    scopes.addAll(soaConfiguration.getScopes());
    environment.getApplicationContext().setAttribute(DynamicAttributesBundle.Scopes.class.getName(), new Scopes(scopes));

    // attributes must be allocated first - Discovery et al might need them
    DynamicAttributes attributes = StandardAttributesContainer.wrapAttributes(SoaBundle.checkManaged(environment, soaConfiguration.getAttributesFactory().build(configuration, environment, scopes)), SoaBundle.hasAdminKey);
    environment.getApplicationContext().setAttribute(DynamicAttributes.class.getName(), attributes);
}
 
Example #7
Source File: ConfigBindingsRenderer.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
private void renderRootTypes(final BindingsConfig config, final StringBuilder res) {
    if (tree.getRootTypes().size() == 1 && config.isShowCustomConfigOnly()) {
        // only Configuration binding exists
        return;
    }
    res.append(NEWLINE).append(NEWLINE).append(TAB)
            .append("Configuration object bindings:").append(NEWLINE);
    for (Class type : tree.getRootTypes()) {
        if (config.isShowCustomConfigOnly() && type.equals(Configuration.class)) {
            continue;
        }
        res.append(TAB).append(TAB)
                .append(CONFIG).append(SPACE).append(type.getSimpleName())
                .append(NEWLINE);
    }
}
 
Example #8
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 #9
Source File: ConfigTreeBuilder.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
/**
 * Analyze configuration object to extract bindable parts.
 *
 * @param bootstrap     bootstrap instance
 * @param configuration configuration instance
 * @param introspect    true to introspect configuration object and extract values by path and unique
 *                      sub configurations
 * @return parsed configuration info
 */
public static ConfigurationTree build(final Bootstrap bootstrap,
                                      final Configuration configuration,
                                      final boolean introspect) {
    final List<Class> roots = resolveRootTypes(new ArrayList<>(), configuration.getClass());
    if (introspect) {
        final List<ConfigPath> content = resolvePaths(
                bootstrap.getObjectMapper().getSerializationConfig(),
                null,
                new ArrayList<>(),
                configuration.getClass(),
                configuration,
                GenericsResolver.resolve(configuration.getClass()));
        final List<ConfigPath> uniqueContent = resolveUniqueTypePaths(content);
        return new ConfigurationTree(roots, content, uniqueContent);
    } else {
        return new ConfigurationTree(roots);
    }
}
 
Example #10
Source File: ParametersInjectionDwTest.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 client,
                            DummyService service,
                            @Jit JitService jit) {
    assertNotNull(app);
    assertNotNull(app2);
    assertNotNull(conf);
    assertNotNull(conf2);
    assertNotNull(env);
    assertNotNull(mapper);
    assertNotNull(injector);
    assertNotNull(client);
    assertNotNull(service);
    assertNotNull(jit);
    assertEquals(client.getPort(), 8080);
    assertEquals(client.getAdminPort(), 8081);
}
 
Example #11
Source File: ComposedConfigurationAccessor.java    From soabase with Apache License 2.0 5 votes vote down vote up
public static ComposedConfigurationAccessor getAccessor(Configuration configuration, Environment environment)
{
    ComposedConfigurationAccessor accessor = (ComposedConfigurationAccessor)environment.getApplicationContext().getAttribute(ComposedConfigurationAccessor.class.getName());
    if ( accessor == null )
    {
        accessor = new ComposedConfigurationAccessor(configuration);
        environment.getApplicationContext().setAttribute(ComposedConfigurationAccessor.class.getName(), accessor);
    }
    return accessor;
}
 
Example #12
Source File: SoaBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
private LoggingReader initLogging(Configuration configuration) throws IOException
{
    Set<File> mainFiles = Sets.newHashSet();
    Set<File> archiveDirectories = Sets.newHashSet();
    LoggingFactory loggingFactory = configuration.getLoggingFactory();
    if ( loggingFactory instanceof DefaultLoggingFactory )
    {
        for ( AppenderFactory appenderFactory : ((DefaultLoggingFactory)loggingFactory).getAppenders() )
        {
            if ( appenderFactory instanceof FileAppenderFactory )
            {
                FileAppenderFactory fileAppenderFactory = (FileAppenderFactory)appenderFactory;
                if ( fileAppenderFactory.getCurrentLogFilename() != null )
                {
                    mainFiles.add(new File(fileAppenderFactory.getCurrentLogFilename()).getCanonicalFile());
                }

                if ( fileAppenderFactory.getArchivedLogFilenamePattern() != null )
                {
                    File archive = new File(fileAppenderFactory.getArchivedLogFilenamePattern()).getParentFile().getCanonicalFile();
                    archiveDirectories.add(archive);
                }
            }
        }
    }

    if ( (mainFiles.size() == 0) && (archiveDirectories.size() == 0) )
    {
        log.warn("No log files found in config");
    }

    return new LoggingReader(mainFiles, archiveDirectories);
}
 
Example #13
Source File: ZooKeeperDiscoveryFactory.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Override
public Discovery build(Configuration configuration, Environment environment, SoaInfo soaInfo)
{
    SoaFeatures features = SoaBundle.getFeatures(environment);
    CuratorFramework curatorFramework = features.getNamedRequired(CuratorFramework.class, SoaFeatures.DEFAULT_NAME);
    SoaConfiguration soaConfiguration = ComposedConfigurationAccessor.access(configuration, environment, SoaConfiguration.class);
    return new ZooKeeperDiscovery(curatorFramework, this, soaInfo, environment, soaConfiguration.getDeploymentGroups());
}
 
Example #14
Source File: ClientSupportDwTest.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
    environment.jersey().register(Resource.class);
    environment.servlets().addServlet("test", new Servlet(false))
            .addMapping("/servlet");
    environment.admin().addServlet("testAdmin", new Servlet(true))
            .addMapping("/servlet");
}
 
Example #15
Source File: RateLimitBundleTest.java    From dropwizard-ratelimit with Apache License 2.0 5 votes vote down vote up
@Override
public RateLimitConfiguration getRateLimitConfiguration(Configuration configuration) {
    RateLimitConfiguration conf = new RateLimitConfiguration();
    conf.setRedisHost("localhost");
    conf.setRedisPort(6379);
    return conf;
}
 
Example #16
Source File: BankServiceApplication.java    From event-sourcing-cqrs-examples with MIT License 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
  registerFilters(environment);
  registerExceptionMappers(environment);
  registerHypermediaSupport(environment);
  registerResources(environment);
}
 
Example #17
Source File: RateLimitApplication.java    From ratelimitj with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(Bootstrap<Configuration> bootstrap) {
    redisClient = RedisClient.create("redis://localhost:7006");
    RequestRateLimiterFactory factory = new RedisRateLimiterFactory(redisClient);

    //RequestRateLimiterFactory factory = new InMemoryRateLimiterFactory();

    bootstrap.addBundle(new RateLimitBundle(factory));
}
 
Example #18
Source File: HelloApp.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Override
protected void internalRun(Configuration configuration, Environment environment)
{
    ClientBuilder builder = new ClientBuilder(environment);
    builder.buildJerseyClient(new JerseyClientConfiguration(), "jersey");
    builder.buildHttpClient(new HttpClientConfiguration(), "apache");

    environment.jersey().register(HelloResourceJersey.class);
    environment.jersey().register(HelloResourceApache.class);
}
 
Example #19
Source File: ExampleApplication.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(Bootstrap<Configuration> bootstrap)
{
    // Use the StandardInjectorProvider unless you need special behavior - you can pass as many modules as you like
    InjectorProvider<Configuration> injectorProvider = new StandardInjectorProvider<>(new ExampleJerseyGuiceModule());
    bootstrap.addBundle(new GuiceBundle<>(injectorProvider));
}
 
Example #20
Source File: TestApplication.java    From dropwizard-guicier with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(final Bootstrap<Configuration> bootstrap) {
    final GuiceBundle<Configuration> jersey2GuiceBundle = GuiceBundle.defaultBuilder(Configuration.class)
        .modules(new TestModule())
        .build();
    bootstrap.addBundle(jersey2GuiceBundle);
}
 
Example #21
Source File: HK2LinkerTest.java    From dropwizard-guicier with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    Environment environment = new Environment("test env", objectMapper, null, new MetricRegistry(), null);
    GuiceBundle guiceBundle = GuiceBundle.defaultBuilder(Configuration.class)
        .modules(new TestModule())
        .build();
    Bootstrap bootstrap = mock(Bootstrap.class);
    when(bootstrap.getObjectMapper()).thenReturn(objectMapper);
    guiceBundle.initialize(bootstrap);
    guiceBundle.run(new Configuration(), environment);

    injector = guiceBundle.getInjector();
    serviceLocator = injector.getInstance(ServiceLocator.class);
}
 
Example #22
Source File: BreakerboxDashboardBundle.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
    //TODO: NEED TO DISABLE GZIP for text/event-stream

    environment.servlets().addServlet("mock.stream", new MockStreamServlet()).addMapping("/tenacity/mock.stream");
    environment.servlets().addServlet("proxy.stream", new ProxyStreamServlet()).addMapping("/tenacity/proxy.stream");
}
 
Example #23
Source File: DropwizardEnvironmentModule.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void configure() {
    javax.inject.Provider<T> provider = new CustomConfigurationProvider();
    bind(configurationClass).toProvider(provider);
    if (configurationClass != Configuration.class) {
        bind(Configuration.class).toProvider(provider);
    }
}
 
Example #24
Source File: MailBundle.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Initializes the environment.
 *
 * @param configuration the configuration object
 * @param environment   the io.robe.admin's {@link io.dropwizard.setup.Environment}
 * @throws Exception if something goes wrong
 */
@Override
public void run(T configuration, Environment environment) throws Exception {
    if (configuration.getMail() != null && configuration instanceof HasMailConfiguration && configuration instanceof Configuration) {
     MailManager.setSender(new MailSender(configuration.getMail()));
    } else {
        LOGGER.warn("Bundle included but no configuration (mail) found at yml.");
    }
}
 
Example #25
Source File: RobeHibernateBundleTest.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
@Order(order = 9)
public void configure() {
    org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
    RobeHibernateBundle.getInstance().configure(configuration);
    Assert.assertEquals(configuration, RobeHibernateBundle.getInstance().getConfiguration());
}
 
Example #26
Source File: ConfigTreeBuilder.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * Analyze configuration class structure to extract all classes in hierarchy with all custom
 * interfaces (ignoring, for example Serializable or something like this).
 *
 * @param roots all collected types so far
 * @param type  type to analyze
 * @return all collected types
 */
@SuppressWarnings("unchecked")
private static List<Class> resolveRootTypes(final List<Class> roots, final Class type) {
    roots.add(type);
    if (type == Configuration.class) {
        return roots;
    }
    for (Class iface : type.getInterfaces()) {
        if (isInStopPackage(iface)) {
            continue;
        }
        roots.add(iface);
    }
    return resolveRootTypes(roots, type.getSuperclass());
}
 
Example #27
Source File: ConfigurationContext.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * @param configuration dropwizard configuration instance
 * @param environment   dropwizard environment instance
 */
public void runPhaseStarted(final Configuration configuration, final Environment environment) {
    this.configuration = configuration;
    this.configurationTree = ConfigTreeBuilder
            .build(bootstrap, configuration, option(BindConfigurationByPath));
    this.environment = environment;
    // register in shared state just in case
    this.sharedState.put(Configuration.class, configuration);
    this.sharedState.put(ConfigurationTree.class, configurationTree);
    this.sharedState.put(Environment.class, environment);
    this.sharedState.listen(environment);
    lifecycle().runPhase(configuration, configurationTree, environment);
}
 
Example #28
Source File: GuiceyRunner.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
public GuiceyRunner(final ConfigurationContext context,
                    final Configuration configuration,
                    final Environment environment) {
    guiceyTime = context.stat().timer(GuiceyTime);
    runTime = context.stat().timer(RunTime);

    context.runPhaseStarted(configuration, environment);
    this.context = context;
}
 
Example #29
Source File: GuiceyAppExtension.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@SuppressWarnings({"unchecked", "checkstyle:Indentation"})
private <C extends Configuration> DropwizardTestSupport<C> create(
        final Class<? extends Application> app,
        final String configPath,
        final ConfigOverride... overrides) {
    return new DropwizardTestSupport<C>((Class<? extends Application<C>>) app,
            configPath,
            (String) null,
            application -> {
                command = new TestCommand<>(application);
                return command;
            },
            overrides);
}
 
Example #30
Source File: TestParametersSupport.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("checkstyle:ReturnCount")
public boolean supportsParameter(final ParameterContext parameterContext,
                                 final ExtensionContext extensionContext) throws ParameterResolutionException {
    final Parameter parameter = parameterContext.getParameter();
    if (parameter.getAnnotations().length > 0) {
        if (AnnotationSupport.isAnnotated(parameter, Jit.class)) {
            return true;
        } else if (!isQualifierAnnotation(parameter.getAnnotations())) {
            // if any other annotation declared on the parameter - skip it (possibly other extension's parameter)
            return false;
        }
    }

    final Class<?> type = parameter.getType();
    if (Application.class.isAssignableFrom(type) || Configuration.class.isAssignableFrom(type)) {
        // special case when exact app or configuration class used
        return true;
    } else {
        for (Class<?> cls : supportedClasses) {
            if (type.equals(cls)) {
                return true;
            }
        }
    }

    // declared guice binding (by class only)
    return getInjector(extensionContext)
            .map(it -> it.getExistingBinding(getKey(parameter)) != null)
            .orElse(false);
}