All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.robe.guice.DropwizardEnvironmentModule Maven / Gradle / Ivy

There is a newer version: 0.5.0.0-1039
Show newest version
package io.robe.guice;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.ProvisionException;
import io.dropwizard.Configuration;
import io.dropwizard.setup.Environment;

//Copied from https://github.com/HubSpot/dropwizard-guice/blob/master/src/main/java/com/hubspot/dropwizard/guice/DropwizardEnvironmentModule.java
public class DropwizardEnvironmentModule extends AbstractModule {
    private static final String ILLEGAL_DROPWIZARD_MODULE_STATE = "The dropwizard environment has not yet been set. This is likely caused by trying to access the dropwizard environment during the bootstrap phase.";
    private T configuration;
    private Environment environment;
    private Class configurationClass;

    public DropwizardEnvironmentModule(Class configurationClass) {
        this.configurationClass = configurationClass;
    }

    @Override
    protected void configure() {
        javax.inject.Provider provider = new CustomConfigurationProvider();
        bind(configurationClass).toProvider(provider);
        if (configurationClass != Configuration.class) {
            bind(Configuration.class).toProvider(provider);
        }
    }

    public void setEnvironmentData(T configuration, Environment environment) {
        this.configuration = configuration;
        this.environment = environment;
    }

    @Provides
    public Environment providesEnvironment() {
        if (environment == null) {
            throw new ProvisionException(ILLEGAL_DROPWIZARD_MODULE_STATE);
        }
        return environment;
    }

    private class CustomConfigurationProvider implements javax.inject.Provider {
        @Override
        public T get() {
            if (configuration == null) {
                throw new ProvisionException(ILLEGAL_DROPWIZARD_MODULE_STATE);
            }
            return configuration;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy