I need to have a ReloadableConfiguration that handles JSON files to read properties from a property file. Everything I tried, works fine for String or List but does not work for Map. It just returns null instead of a Map<String, String> object (or anything else) (see the value of "foo" in the example test case below).
The following test case summarizes everything that is implemented so far. The return value of configuration.getProperty("foo") is null. I also tried to use getCollection instead of getProperty and some other of the functions but it also fails in retrieving a map:
@Test
void testJsonConfigLoading() throws IOException {
// Create property file
Path configurationFile = Files.createTempFile("json-test-foo", ".properties");
String TEST_FILE_DIR = "my.test.dir";
System.setProperty(TEST_FILE_DIR, configurationFile.getParent().toString());
String prop = "{\"bla\": \"blubb\", \"foo\": {\"k1\": \"A\", \"k2\": \"B\"}}";
Files.write(configurationFile, prop.getBytes(), StandardOpenOption.WRITE);
// Create property reader
Parameters params = new Parameters();
ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> builder =
new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(JSONConfiguration.class)
.configure(
params
.fileBased()
.setFile(configurationFile.toFile())
);
ImmutableConfiguration configuration = new ReloadableConfiguration(builder);
// test simple string
String bla = configuration.getString("bla");
assertEquals("blubb", bla);
// test map
Object property = configuration.getProperty("foo");
assertNotNull(property); // <= here the test case fails since property is null
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(property);
Map<String, String> foo = mapper.readValue(json, Map.class);
Map<String, String> map1 = Stream.of(new String[][] {
{ "k1", "A" },
{ "k2", "B" },
}).collect(Collectors.toMap(data -> data[0], data -> data[1]));
assertEquals(map1, foo);
}
I tried different configuration parameters for the ConfigurationBuilder and different method to get something back from the configuration. But the return value of configuration.getProperty("foo") (or other getters) still remains null and not the expected Map<String, String>.
Yes, of course, I searched / read the user guide at https://commons.apache.org/proper/commons-configuration/userguide/user_guide.html but did not find anything that helped me further on. Any ideas on that?
Finally, I got it to work with following lines of code: