JsonBasedPropertiesProvider extends FormatBasedPropertiesProvider { @Override public Properties getProperties(InputStream inputStream) { requireNonNull(inputStream); Properties properties = new Properties(); try { JSONTokener tokener = new JSONTokener(inputStream); if (tokener.end()) { return properties; } if (tokener.nextClean() == '"') { tokener.back(); properties.put("content", tokener.nextValue().toString()); } else { tokener.back(); JSONObject obj = new JSONObject(tokener); Map<String, Object> yamlAsMap = convertToMap(obj); properties.putAll(flatten(yamlAsMap)); } return properties; } catch (Exception e) { throw new IllegalStateException("Unable to load json configuration from provided stream", e); } }  @Override Properties getProperties(InputStream inputStream);  }
@Test void readsSingleValues() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_readsSingleValues.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThat(provider.getProperties(input)).containsOnly(MapEntry.entry("setting", "masterValue"), MapEntry.entry("integerSetting", 42)); } }
@Test void readsNestedValues() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_readsNestedValues.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThat(provider.getProperties(input)).containsOnly(MapEntry.entry("some.setting", "masterValue"), MapEntry.entry("some.integerSetting", 42)); } }
@Test void readsLists() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_readsLists.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThat(provider.getProperties(input)).containsOnly(MapEntry.entry("whitelist", "a,b,33"), MapEntry.entry("blacklist", "x,y,z")); } }
@Test void readsTextBlock() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_readsTextBlock.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThat(provider.getProperties(input)).containsExactly(MapEntry.entry("content", "I'm just a text block document")); } }
@Test void throwsForNonJsonFile() throws Exception { String path = "org/cfg4j/source/propertiesprovider/JsonBasedPropertiesProviderTest_throwsForNonJsonFile.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThatThrownBy(() -> provider.getProperties(input)).isExactlyInstanceOf(IllegalStateException.class); } }
@Test void throwsOnNullInput() throws Exception { String path = "org/cfg4j/source/propertiesprovider/nonexistent.json"; try (InputStream input = getClass().getClassLoader().getResourceAsStream(path)) { assertThatThrownBy(() -> provider.getProperties(input)).isExactlyInstanceOf(NullPointerException.class); } }