View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2014 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
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   * Reads i18n resources from JSON files.
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  }