|
| 1 | +package io.scalecube.config.source; |
| 2 | + |
| 3 | +import io.scalecube.config.ConfigProperty; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.TreeMap; |
| 6 | + |
| 7 | +public final class SystemEnvironmentSingleVariableConfigSource implements ConfigSource { |
| 8 | + |
| 9 | + private static final String VAR_NAME = "SETTINGS"; |
| 10 | + |
| 11 | + private static final String DELIMITER = ";"; |
| 12 | + private static final String SEPARATOR = "="; |
| 13 | + |
| 14 | + private final String varName; |
| 15 | + private final String delimiter; |
| 16 | + private final String separator; |
| 17 | + |
| 18 | + private Map<String, ConfigProperty> loadedConfig; |
| 19 | + |
| 20 | + public SystemEnvironmentSingleVariableConfigSource() { |
| 21 | + this(VAR_NAME, DELIMITER, SEPARATOR); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Constructor. |
| 26 | + * |
| 27 | + * @param varName varName |
| 28 | + * @param delimiter delimiter |
| 29 | + * @param separator separator |
| 30 | + */ |
| 31 | + public SystemEnvironmentSingleVariableConfigSource( |
| 32 | + String varName, String delimiter, String separator) { |
| 33 | + this.varName = varName; |
| 34 | + this.delimiter = delimiter; |
| 35 | + this.separator = separator; |
| 36 | + } |
| 37 | + |
| 38 | + @Override |
| 39 | + public Map<String, ConfigProperty> loadConfig() { |
| 40 | + if (loadedConfig != null) { |
| 41 | + return loadedConfig; |
| 42 | + } |
| 43 | + |
| 44 | + Map<String, ConfigProperty> result = new TreeMap<>(); |
| 45 | + |
| 46 | + String settings = System.getenv(varName); |
| 47 | + |
| 48 | + if (settings != null && !settings.isEmpty()) { |
| 49 | + for (String str : settings.split(delimiter)) { |
| 50 | + String[] split = str.split(separator); |
| 51 | + if (split.length != 2) { |
| 52 | + break; |
| 53 | + } |
| 54 | + |
| 55 | + String propName = split[0]; |
| 56 | + String propValue = split[1]; |
| 57 | + |
| 58 | + // store value as system property under mapped name |
| 59 | + System.setProperty(propName, propValue); |
| 60 | + result.put(propName, LoadedConfigProperty.forNameAndValue(propName, propValue)); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return loadedConfig = result; |
| 65 | + } |
| 66 | +} |
0 commit comments