From d095c9a03b7a8380d12b2ebf7fd6f54b0bdedc8e Mon Sep 17 00:00:00 2001 From: Mikhail Bobrutskov Date: Sat, 30 Sep 2023 21:11:25 +0200 Subject: [PATCH] added environment variables to config tree --- .../http/framework/WebApplication.java | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/wizzardo/http/framework/WebApplication.java b/src/main/java/com/wizzardo/http/framework/WebApplication.java index 93d8b87..a35e635 100644 --- a/src/main/java/com/wizzardo/http/framework/WebApplication.java +++ b/src/main/java/com/wizzardo/http/framework/WebApplication.java @@ -372,7 +372,42 @@ protected void loadDefaultDevelopmentConfiguration(Config config) { } protected void loadEnvironmentVariables(Config config) { - System.getenv().forEach(config::put); + outer: + for (Map.Entry entry : System.getenv().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + config.put(key, value); + + String[] keys = key.split("_"); + if (keys.length == 0) + continue; + + Config subConfig = config; + int last = keys.length - 1; + int i = 0; + try { + for (; i < last; i++) { + String part = keys[i]; + Optional k = subConfig.keySet().stream().filter(it -> it.equalsIgnoreCase(part)).findFirst(); + if (!k.isPresent()) + continue outer; + + subConfig = subConfig.config(k.get()); + } + + Optional k = subConfig.keySet().stream().filter(it -> it.equalsIgnoreCase(keys[last])).findFirst(); + if (!k.isPresent()) + continue; + subConfig.put(k.get(), value); + } catch (ClassCastException e) { + String k = ""; + for (int j = 0; j < i; j++) { + k += keys[j] + "."; + } + k += keys[i]; + System.out.println("WARNING! cannot overwrite config value " + k + "=" + subConfig.get(keys[i]) + " with new config " + key + "=" + value); + } + } } protected void loadSystemProperties(Config config) {