1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package io.wcm.maven.plugins.i18n.readers;
21
22 import java.io.File;
23 import java.io.IOException;
24 import java.nio.charset.StandardCharsets;
25 import java.util.HashMap;
26 import java.util.Map;
27
28 import org.apache.commons.io.IOUtils;
29
30 import io.wcm.maven.plugins.i18n.JsonUtil;
31 import jakarta.json.JsonObject;
32 import jakarta.json.JsonValue;
33
34
35
36
37 public class JsonI18nReader implements I18nReader {
38
39 @Override
40 public Map<String, String> read(File sourceFile) throws IOException {
41
42 String fileContent = IOUtils.toString(sourceFile.toURI().toURL(), StandardCharsets.UTF_8);
43 try {
44 JsonObject root = JsonUtil.fromString(fileContent);
45 Map<String, String> map = new HashMap<>();
46 parseJson(root, map, "");
47 return map;
48 }
49 catch (IOException ex) {
50 throw new IOException("Unable to read JSON from " + sourceFile.getAbsolutePath(), ex);
51 }
52 }
53
54 private void parseJson(JsonObject node, Map<String, String> map, String prefix) throws IOException {
55 for (Map.Entry<String, JsonValue> entry : node.entrySet()) {
56 String key = entry.getKey();
57 JsonValue value = entry.getValue();
58 switch (value.getValueType()) {
59 case OBJECT:
60 parseJson(value.asJsonObject(), map, prefix + key + ".");
61 break;
62 case STRING:
63 map.put(prefix + key, node.getString(key));
64 break;
65 default:
66 throw new IOException("Unsupported JSON value: " + node.getValueType());
67 }
68 }
69 }
70
71 }