com.opsbears.webcomponents.configuration.EnvironmentConfigurationLoader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of configuration Show documentation
Show all versions of configuration Show documentation
Utilities for creating and reading configuration options
package com.opsbears.webcomponents.configuration;
import javax.annotation.ParametersAreNonnullByDefault;
import java.security.InvalidParameterException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@ParametersAreNonnullByDefault
public class EnvironmentConfigurationLoader implements ConfigurationLoader {
private final Map env;
public EnvironmentConfigurationLoader(Map env) {
this.env = env;
}
@Override
public String getName() {
return "Environment variables";
}
@Override
public String getDescription() {
return "Set environment variables to be loaded as options.";
}
@Override
public String formatConfigurationOption(ConfigurationOption option) {
//noinspection unchecked
return option.getLongOption().toUpperCase().replaceAll("-", "_") + "=" + (option.getValueType().isAssignableFrom(Boolean.class)?"0|1":"VALUE");
}
@Override
public Configuration load(Configuration configuration) {
for (String key : env.keySet()) {
try {
ConfigurationOptionWithValue option = configuration.getOption(key);
Object value;
//noinspection unchecked
if (option.getValueType().isAssignableFrom(Boolean.class)) {
switch (env.get(key).toLowerCase()) {
case "0":
case "off":
case "no":
case "false":
value = false;
break;
case "1":
case "on":
case "yes":
case "true":
value = true;
break;
default:
throw new InvalidParameterException("Invalid value for boolean environment variable " + key + ": " + env.get(key));
}
} else {
value = env.get(key);
}
configuration = configuration.withOptionValue(key, value);
} catch (ConfigurationOptionNotFound ignored) {
}
}
return configuration;
}
}