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

com.opsbears.webcomponents.configuration.EnvironmentConfigurationLoader Maven / Gradle / Ivy

There is a newer version: 1.0.0-alpha14
Show newest version
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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy