K8sSpecTemplate extends HashMap<String, Object> { public void loadProperties(Properties properties) { Set<Entry<Object, Object>> entries = properties.entrySet(); for (Entry entry : entries) { String key = (String) entry.getKey(); Object value = entry.getValue(); String[] keySplit = key.split("[.]"); Map<String, Object> target = this; for (int i = 0; i < keySplit.length - 1; i++) { if (!target.containsKey(keySplit[i])) { HashMap subEntry = new HashMap(); target.put(keySplit[i], subEntry); target = subEntry; } else { Object subEntry = target.get(keySplit[i]); if (!(subEntry instanceof Map)) { HashMap replace = new HashMap(); replace.put("_", subEntry); target.put(keySplit[i], replace); } target = (Map<String, Object>) target.get(keySplit[i]); } } if (target.get(keySplit[keySplit.length - 1]) instanceof Map) { ((Map) target.get(keySplit[keySplit.length - 1])).put("_", value); } else { target.put(keySplit[keySplit.length - 1], value); } } }  String render(File templateFile); String render(String template); void loadProperties(Properties properties);  }
@Test public void testLoadProperties() { K8sSpecTemplate template = new K8sSpecTemplate(); Properties p = new Properties(); p.put("k8s.intp.key1", "v1"); p.put("k8s.intp.key2", "v2"); p.put("k8s.key3", "v3"); p.put("key4", "v4"); template.loadProperties(p); assertEquals("v4", template.get("key4")); assertEquals("v3", ((Map) template.get("k8s")).get("key3")); assertEquals("v2", ((Map) ((Map) template.get("k8s")).get("intp")).get("key2")); assertEquals("v1", ((Map) ((Map) template.get("k8s")).get("intp")).get("key1")); }
@Test public void testLoadPropertyOverrideString() { K8sSpecTemplate template = new K8sSpecTemplate(); Properties p = new Properties(); p.put("k8s", "v1"); p.put("k8s.key1", "v2"); template.loadProperties(p); assertEquals("v1", ((Map) template.get("k8s")).get("_")); assertEquals("v2", ((Map) template.get("k8s")).get("key1")); }
@Test public void testLoadPropertyOverrideDict() { K8sSpecTemplate template = new K8sSpecTemplate(); Properties p = new Properties(); p.put("k8s.key1", "v2"); p.put("k8s", "v1"); template.loadProperties(p); assertEquals("v1", ((Map) template.get("k8s")).get("_")); assertEquals("v2", ((Map) template.get("k8s")).get("key1")); }
@Test public void testLoadPropertyWithMap() { K8sSpecTemplate template = new K8sSpecTemplate(); Properties p = new Properties(); p.put("k8s", ImmutableMap.of("k1", "v1")); template.loadProperties(p); assertEquals("v1", ((Map) template.get("k8s")).get("k1")); }