-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #153 from scalecube/feature/SystemEnvironmentVaria…
…blesConfigSource Added SystemEnvironmentVariablesConfigSource
- Loading branch information
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
61 changes: 61 additions & 0 deletions
61
config/src/main/java/io/scalecube/config/source/SystemEnvironmentVariablesConfigSource.java
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package io.scalecube.config.source; | ||
|
||
import io.scalecube.config.ConfigProperty; | ||
import java.util.Map; | ||
import java.util.Objects; | ||
import java.util.TreeMap; | ||
import java.util.function.Consumer; | ||
|
||
public final class SystemEnvironmentVariablesConfigSource implements ConfigSource { | ||
|
||
private Map<String, ConfigProperty> loadedConfig; | ||
|
||
// from-to environment variables mappings | ||
private final Map<String, String> mappings = new TreeMap<>(); | ||
|
||
public SystemEnvironmentVariablesConfigSource(Consumer<Mapper> consumer) { | ||
consumer.accept(new MapperImpl()); | ||
} | ||
|
||
@Override | ||
public Map<String, ConfigProperty> loadConfig() { | ||
if (loadedConfig != null) { | ||
return loadedConfig; | ||
} | ||
|
||
Map<String, ConfigProperty> result = new TreeMap<>(); | ||
|
||
System.getenv() | ||
.forEach( | ||
(propName, propValue) -> { | ||
String dst = mappings.get(propName); | ||
if (dst != null) { | ||
// store value as system property under mapped name | ||
System.setProperty(dst, propValue); | ||
result.put(dst, LoadedConfigProperty.forNameAndValue(dst, propValue)); | ||
} else { | ||
result.put(propName, LoadedConfigProperty.forNameAndValue(propName, propValue)); | ||
} | ||
}); | ||
|
||
return loadedConfig = result; | ||
} | ||
|
||
// Stores mapping between environemnt variable name and corresponding system property name. | ||
interface Mapper { | ||
|
||
Mapper map(String src, String dst); | ||
} | ||
|
||
// Inner implementation class | ||
private class MapperImpl implements Mapper { | ||
|
||
@Override | ||
public Mapper map(String src, String dst) { | ||
Objects.requireNonNull(src); | ||
Objects.requireNonNull(dst); | ||
mappings.put(src, dst); | ||
return this; | ||
} | ||
} | ||
} |