Skip to content

Commit 523ed87

Browse files
authored
Merge pull request #153 from scalecube/feature/SystemEnvironmentVariablesConfigSource
Added SystemEnvironmentVariablesConfigSource
2 parents 97be663 + bdeb9ea commit 523ed87

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package io.scalecube.config.source;
2+
3+
import io.scalecube.config.ConfigProperty;
4+
import java.util.Map;
5+
import java.util.Objects;
6+
import java.util.TreeMap;
7+
import java.util.function.Consumer;
8+
9+
public final class SystemEnvironmentVariablesConfigSource implements ConfigSource {
10+
11+
private Map<String, ConfigProperty> loadedConfig;
12+
13+
// from-to environment variables mappings
14+
private final Map<String, String> mappings = new TreeMap<>();
15+
16+
public SystemEnvironmentVariablesConfigSource(Consumer<Mapper> consumer) {
17+
consumer.accept(new MapperImpl());
18+
}
19+
20+
@Override
21+
public Map<String, ConfigProperty> loadConfig() {
22+
if (loadedConfig != null) {
23+
return loadedConfig;
24+
}
25+
26+
Map<String, ConfigProperty> result = new TreeMap<>();
27+
28+
System.getenv()
29+
.forEach(
30+
(propName, propValue) -> {
31+
String dst = mappings.get(propName);
32+
if (dst != null) {
33+
// store value as system property under mapped name
34+
System.setProperty(dst, propValue);
35+
result.put(dst, LoadedConfigProperty.forNameAndValue(dst, propValue));
36+
} else {
37+
result.put(propName, LoadedConfigProperty.forNameAndValue(propName, propValue));
38+
}
39+
});
40+
41+
return loadedConfig = result;
42+
}
43+
44+
// Stores mapping between environemnt variable name and corresponding system property name.
45+
interface Mapper {
46+
47+
Mapper map(String src, String dst);
48+
}
49+
50+
// Inner implementation class
51+
private class MapperImpl implements Mapper {
52+
53+
@Override
54+
public Mapper map(String src, String dst) {
55+
Objects.requireNonNull(src);
56+
Objects.requireNonNull(dst);
57+
mappings.put(src, dst);
58+
return this;
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)