Search in sources :

Example 1 with JsonHandler

use of org.apache.jackrabbit.commons.json.JsonHandler in project sling by apache.

the class JcrResourceBundle method loadJsonDictionary.

private void loadJsonDictionary(Resource resource, final Map<String, Object> targetDictionary) {
    log.info("Loading json dictionary: {}", resource.getPath());
    // use streaming parser (we don't need the dict in memory twice)
    JsonParser parser = new JsonParser(new JsonHandler() {

        private String key;

        @Override
        public void key(String key) throws IOException {
            this.key = key;
        }

        @Override
        public void value(String value) throws IOException {
            targetDictionary.put(key, value);
        }

        @Override
        public void object() throws IOException {
        }

        @Override
        public void endObject() throws IOException {
        }

        @Override
        public void array() throws IOException {
        }

        @Override
        public void endArray() throws IOException {
        }

        @Override
        public void value(boolean value) throws IOException {
        }

        @Override
        public void value(long value) throws IOException {
        }

        @Override
        public void value(double value) throws IOException {
        }
    });
    final InputStream stream = resource.adaptTo(InputStream.class);
    if (stream != null) {
        String encoding = "utf-8";
        final ResourceMetadata metadata = resource.getResourceMetadata();
        if (metadata.getCharacterEncoding() != null) {
            encoding = metadata.getCharacterEncoding();
        }
        try {
            parser.parse(stream, encoding);
        } catch (IOException e) {
            log.warn("Could not parse i18n json dictionary {}: {}", resource.getPath(), e.getMessage());
        } finally {
            try {
                stream.close();
            } catch (IOException ignore) {
            }
        }
    } else {
        log.warn("Not a json file: {}", resource.getPath());
    }
}
Also used : InputStream(java.io.InputStream) JsonHandler(org.apache.jackrabbit.commons.json.JsonHandler) IOException(java.io.IOException) ResourceMetadata(org.apache.sling.api.resource.ResourceMetadata) JsonParser(org.apache.jackrabbit.commons.json.JsonParser)

Aggregations

IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 JsonHandler (org.apache.jackrabbit.commons.json.JsonHandler)1 JsonParser (org.apache.jackrabbit.commons.json.JsonParser)1 ResourceMetadata (org.apache.sling.api.resource.ResourceMetadata)1