Created
December 12, 2012 05:58
-
-
Save electrum/4265211 to your computer and use it in GitHub Desktop.
ConditionalModule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.base.Optional; | |
import com.google.inject.Binder; | |
import com.google.inject.Module; | |
import io.airlift.configuration.ConfigurationAwareModule; | |
import io.airlift.configuration.ConfigurationFactory; | |
import static com.google.common.base.Preconditions.checkNotNull; | |
import static com.google.common.base.Preconditions.checkState; | |
public class ConditionalModule | |
implements ConfigurationAwareModule | |
{ | |
public static ConfigurationAwareModule installIfPropertyDefined(Module module, String property) | |
{ | |
return new ConditionalModule(module, property, Optional.<String>absent()); | |
} | |
public static ConfigurationAwareModule installIfPropertyEquals(Module module, String property, String expectedValue) | |
{ | |
checkNotNull(expectedValue, "expectedValue is null"); | |
return new ConditionalModule(module, property, Optional.of(expectedValue)); | |
} | |
private final Module module; | |
private final String property; | |
private final Optional<String> expectedValue; | |
private ConfigurationFactory configurationFactory; | |
private ConditionalModule(Module module, String property, Optional<String> expectedValue) | |
{ | |
this.module = checkNotNull(module, "module is null"); | |
this.property = checkNotNull(property, "property is null"); | |
this.expectedValue = checkNotNull(expectedValue, "expectedValue is null"); | |
} | |
@Override | |
public void setConfigurationFactory(ConfigurationFactory configurationFactory) | |
{ | |
this.configurationFactory = checkNotNull(configurationFactory, "configurationFactory is null"); | |
configurationFactory.consumeProperty(property); | |
// consume properties if we are not going to install the module | |
if (!shouldInstall()) { | |
configurationFactory.registerConfigurationClasses(module); | |
} | |
} | |
@Override | |
public void configure(Binder binder) | |
{ | |
checkState(configurationFactory != null, "configurationFactory was not set"); | |
if (shouldInstall()) { | |
binder.install(module); | |
} | |
} | |
private boolean shouldInstall() | |
{ | |
if (expectedValue.isPresent()) { | |
return expectedValue.get().equals(configurationFactory.getProperties().get(property)); | |
} | |
return configurationFactory.getProperties().containsKey(property); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment