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

com.hubspot.dropwizard.guice.DropwizardEnvironmentModule Maven / Gradle / Ivy

There is a newer version: 1.3.5.0
Show newest version
package com.hubspot.dropwizard.guice;

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

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() {
    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 Provider {
    @Override
    public T get() {
      if (configuration == null) {
        throw new ProvisionException(ILLEGAL_DROPWIZARD_MODULE_STATE);
      }
      return configuration;
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy