I18nDictionaryHumanTranslation.java 19.6 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.translation.api.TranslationException
 *  com.adobe.granite.translation.api.TranslationService
 *  com.google.gson.Gson
 *  com.google.gson.GsonBuilder
 *  com.google.gson.JsonElement
 *  com.google.gson.JsonObject
 *  com.google.gson.JsonParser
 *  javax.jcr.Binary
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.ValueFactory
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.wcm.translation.impl;

import com.adobe.cq.wcm.translation.impl.I18nDictionary;
import com.adobe.cq.wcm.translation.impl.I18nDictionaryTranslator;
import com.adobe.cq.wcm.translation.impl.TranslationObjectImpl;
import com.adobe.cq.wcm.translation.impl.TranslationRuleConfigurationFile;
import com.adobe.cq.wcm.translation.impl.TranslationUtils;
import com.adobe.granite.translation.api.TranslationException;
import com.adobe.granite.translation.api.TranslationService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class I18nDictionaryHumanTranslation
extends I18nDictionaryTranslator {
    private static final Logger logger = LoggerFactory.getLogger(I18nDictionaryHumanTranslation.class);
    private Element currentPropertiesElement;
    private Document currentDoc;

    public I18nDictionaryHumanTranslation(TranslationRuleConfigurationFile ruleFile, ResourceResolver resourceResolver) {
        super(ruleFile, null, resourceResolver);
        logger.trace("In function: I18nDictionaryHumanTranslation");
        this.currentPropertiesElement = null;
        this.currentDoc = null;
    }

    public Document generateXMLForI18nDictionary(Resource i18nDictResource) throws ParserConfigurationException, RepositoryException, TranslationException, TransformerException, IOException {
        logger.trace("In function: generateXMLForI18nDictionary");
        Document document = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        this.currentDoc = db.newDocument();
        Element rootElement = this.currentDoc.createElement(TranslationUtils.TRANSLATION_OBJECT_FILE_NODE);
        rootElement.setAttribute("fileType", TranslationObjectImpl.TranslationObjectType.I18NDICTIONARY.toString());
        if (i18nDictResource != null) {
            String strSourcePath = i18nDictResource.getPath();
            rootElement.setAttribute("sourcePath", strSourcePath);
        }
        this.currentDoc.appendChild(rootElement);
        this.currentPropertiesElement = this.currentDoc.createElement(TranslationUtils.TRANSLATION_OBJECT_PROPERTIES_NODE);
        if (i18nDictResource != null) {
            this.processI18nDictTranslationNode(i18nDictResource);
        }
        rootElement.appendChild(this.currentPropertiesElement);
        document = this.currentDoc;
        this.currentPropertiesElement = null;
        this.currentDoc = null;
        return document;
    }

    public Document generateXMLForComponentStrings(ArrayList<Resource> pageList) throws ParserConfigurationException, RepositoryException, TranslationException, TransformerException, IOException {
        logger.trace("In function: generateXMLForComponentStrings");
        Document document = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        this.currentDoc = db.newDocument();
        Element rootElement = this.currentDoc.createElement(TranslationUtils.TRANSLATION_OBJECT_FILE_NODE);
        rootElement.setAttribute("fileType", TranslationObjectImpl.TranslationObjectType.I18NCOMPONENTSTRINGDICT.toString());
        rootElement.setAttribute("sourcePath", TranslationObjectImpl.TranslationObjectType.I18NCOMPONENTSTRINGDICT.toString());
        this.currentDoc.appendChild(rootElement);
        this.currentPropertiesElement = this.currentDoc.createElement(TranslationUtils.TRANSLATION_OBJECT_PROPERTIES_NODE);
        HashMap<String, String> componentStringSet = this.extractComponentStringMapFromResourceList(pageList);
        this.exportComponentStrings(componentStringSet);
        rootElement.appendChild(this.currentPropertiesElement);
        document = this.currentDoc;
        this.currentPropertiesElement = null;
        this.currentDoc = null;
        return document;
    }

    @Override
    protected boolean processI18nJson(Resource i18NDict) {
        logger.trace("In function: processI18nJson");
        boolean bSave = false;
        JsonParser parser = new JsonParser();
        InputStream jsonStream = (InputStream)i18NDict.adaptTo(InputStream.class);
        try {
            InputStreamReader srcReader = new InputStreamReader(jsonStream, "UTF-8");
            JsonObject srcJsonObject = parser.parse((Reader)srcReader).getAsJsonObject();
            Set srcJsonEntries = srcJsonObject.entrySet();
            for (Map.Entry entry : srcJsonEntries) {
                Element propElement = this.currentDoc.createElement(TranslationUtils.TRANSLATION_OBJECT_PROPERTY_NODE);
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_MULTI_VALUE, "false");
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_PROPERTY_NAME, (String)entry.getKey());
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_NODE_PATH, i18NDict.getPath());
                propElement.setTextContent(((JsonElement)entry.getValue()).getAsString());
                this.currentPropertiesElement.appendChild(propElement);
                bSave = true;
            }
        }
        catch (UnsupportedEncodingException e) {
            logger.error("Failed to process json", (Throwable)e);
            bSave = false;
        }
        return bSave;
    }

    @Override
    protected boolean processI18nJcrNodes(Resource i18NJcrDict) {
        logger.trace("In function: processI18nJcrNodes");
        boolean bSave = false;
        Iterable childList = i18NJcrDict.getChildren();
        for (Resource child : childList) {
            try {
                if (!I18nDictionary.isI18nEntry(child)) continue;
                Element propElement = this.currentDoc.createElement(TranslationUtils.TRANSLATION_OBJECT_PROPERTY_NODE);
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_MULTI_VALUE, "false");
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_PROPERTY_NAME, "sling:message");
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_NODE_PATH, child.getPath());
                String value = TranslationUtils.getAttribute(child, "sling:message", String.class);
                propElement.setTextContent(value);
                this.currentPropertiesElement.appendChild(propElement);
                bSave = true;
            }
            catch (RepositoryException e) {
                logger.error("Repository exception while reading I18n Entry", (Throwable)e);
            }
        }
        return bSave;
    }

    protected boolean exportComponentStrings(HashMap<String, String> componentStringMap) {
        logger.trace("In function: exportComponentStrings");
        boolean bSave = false;
        if (componentStringMap != null && componentStringMap.size() > 0) {
            for (Map.Entry<String, String> componentStringEntry : componentStringMap.entrySet()) {
                Element propElement = this.currentDoc.createElement(TranslationUtils.TRANSLATION_OBJECT_PROPERTY_NODE);
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_MULTI_VALUE, "false");
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_PROPERTY_NAME, componentStringEntry.getKey());
                propElement.setAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_NODE_PATH, TranslationObjectImpl.TranslationObjectType.I18NCOMPONENTSTRINGDICT.toString());
                propElement.setTextContent(componentStringEntry.getValue());
                this.currentPropertiesElement.appendChild(propElement);
                bSave = true;
            }
        }
        return bSave;
    }

    public void importI18nDictionaryStream(InputStream inputStream, Resource i18nDictResource, ResourceResolver resourceResolver) throws IOException, RepositoryException, ParserConfigurationException, SAXException {
        logger.trace("In function: importI18nDictionaryStream");
        if (TranslationUtils.checkFileExtension((Node)i18nDictResource.adaptTo(Node.class), ".json")) {
            this.importI18nJSONFromXMLStream(inputStream, i18nDictResource);
        } else {
            this.importI18nJCREntriesFromXMLStream(inputStream, i18nDictResource, resourceResolver);
        }
    }

    public void importI18nComponentStringDict(InputStream inputStream, ResourceResolver resourceResolver) throws IOException, RepositoryException, ParserConfigurationException, SAXException {
        logger.trace("In function: importI18nComponentStringDict");
        String language = this.ruleFile.getDestinationLanguage();
        Resource i18nDict = I18nDictionary.getOrCreateI18nDictionaryResource(resourceResolver, "/apps/i18n/", language, null, true);
        if (i18nDict != null) {
            this.importI18nNewJSONFromXMLStream(inputStream, i18nDict);
            resourceResolver.commit();
        }
    }

    private void importI18nJSONFromXMLStream(InputStream inputStream, Resource i18nDictResource) throws IOException, RepositoryException, ParserConfigurationException, SAXException {
        logger.trace("In function: importI18nJSONFromXMLStream");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(inputStream);
        org.w3c.dom.Node rootNode = doc.getFirstChild();
        Element rootElement = (Element)rootNode;
        if (TranslationUtils.TRANSLATION_OBJECT_FILE_NODE.equals(rootElement.getNodeName())) {
            String strSourcePath = rootElement.getAttribute("sourcePath");
            String strFileType = rootElement.getAttribute("fileType");
            boolean bValid = false;
            if (strSourcePath.equals(i18nDictResource.getPath()) && strFileType != null && !strFileType.isEmpty() && strFileType.equals(TranslationObjectImpl.TranslationObjectType.I18NDICTIONARY.toString())) {
                bValid = true;
            }
            if (bValid) {
                JsonObject translatedJsonObject = new JsonObject();
                JsonObject inputJsonObject = I18nDictionaryHumanTranslation.generateI18nJSONFromXML(rootNode);
                JsonParser parser = new JsonParser();
                InputStream srcJsonStream = (InputStream)i18nDictResource.adaptTo(InputStream.class);
                InputStreamReader srcJsonReader = new InputStreamReader(srcJsonStream, "UTF-8");
                JsonObject srcJsonObject = parser.parse((Reader)srcJsonReader).getAsJsonObject();
                Set srcJsonEntries = srcJsonObject.entrySet();
                for (Map.Entry srcJsonEntry : srcJsonEntries) {
                    JsonElement element;
                    if (inputJsonObject.has((String)srcJsonEntry.getKey())) {
                        element = inputJsonObject.get((String)srcJsonEntry.getKey());
                        String translation = element.getAsString();
                        translatedJsonObject.addProperty((String)srcJsonEntry.getKey(), translation);
                        continue;
                    }
                    element = srcJsonObject.get((String)srcJsonEntry.getKey());
                    translatedJsonObject.addProperty((String)srcJsonEntry.getKey(), element.getAsString());
                }
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                ByteArrayInputStream translatedJsonStream = new ByteArrayInputStream(gson.toJson((JsonElement)translatedJsonObject).getBytes(Charset.forName("UTF-8")));
                Node jsonJcrContent = ((Node)i18nDictResource.adaptTo(Node.class)).getNode("jcr:content");
                jsonJcrContent.setProperty("jcr:data", jsonJcrContent.getSession().getValueFactory().createBinary((InputStream)translatedJsonStream));
            }
        }
    }

    private void importI18nNewJSONFromXMLStream(InputStream inputStream, Resource i18nDictResource) throws IOException, RepositoryException, ParserConfigurationException, SAXException {
        logger.trace("In function: importI18nNewJSONFromXMLStream");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(inputStream);
        org.w3c.dom.Node rootNode = doc.getFirstChild();
        Element rootElement = (Element)rootNode;
        if (TranslationUtils.TRANSLATION_OBJECT_FILE_NODE.equals(rootElement.getNodeName())) {
            String strFileType = rootElement.getAttribute("fileType");
            boolean bValid = false;
            if (strFileType != null && !strFileType.isEmpty() && strFileType.equals(TranslationObjectImpl.TranslationObjectType.I18NCOMPONENTSTRINGDICT.toString())) {
                bValid = true;
            }
            if (bValid) {
                JsonObject inputJsonObject = I18nDictionaryHumanTranslation.generateI18nJSONFromXML(rootNode);
                Set inputJsonEntries = inputJsonObject.entrySet();
                JsonParser parser = new JsonParser();
                InputStream existingJsonStream = (InputStream)i18nDictResource.adaptTo(InputStream.class);
                InputStreamReader existingJsonReader = new InputStreamReader(existingJsonStream, "UTF-8");
                JsonObject existingJsonObject = parser.parse((Reader)existingJsonReader).getAsJsonObject();
                for (Map.Entry jsonEntry : inputJsonEntries) {
                    existingJsonObject.addProperty((String)jsonEntry.getKey(), ((JsonElement)jsonEntry.getValue()).getAsString());
                }
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                ByteArrayInputStream translatedJsonStream = new ByteArrayInputStream(gson.toJson((JsonElement)existingJsonObject).getBytes(Charset.forName("UTF-8")));
                Node jsonJcrContent = ((Node)i18nDictResource.adaptTo(Node.class)).getNode("jcr:content");
                jsonJcrContent.setProperty("jcr:data", jsonJcrContent.getSession().getValueFactory().createBinary((InputStream)translatedJsonStream));
            }
        }
    }

    private static JsonObject generateI18nJSONFromXML(org.w3c.dom.Node xmlRoot) {
        logger.trace("In function: generateI18nJSONFromXML");
        NodeList rootChildNodeList = xmlRoot.getChildNodes();
        JsonObject jsonObject = new JsonObject();
        for (int rootIndex = 0; rootIndex < rootChildNodeList.getLength(); ++rootIndex) {
            org.w3c.dom.Node propertiesNode = rootChildNodeList.item(rootIndex);
            if (propertiesNode == null || !TranslationUtils.TRANSLATION_OBJECT_PROPERTIES_NODE.equals(propertiesNode.getNodeName())) continue;
            NodeList translationList = propertiesNode.getChildNodes();
            for (int translationIndex = 0; translationIndex < translationList.getLength(); ++translationIndex) {
                org.w3c.dom.Node translation = translationList.item(translationIndex);
                if (!StringUtils.equals((CharSequence)TranslationUtils.TRANSLATION_OBJECT_PROPERTY_NODE, (CharSequence)translation.getNodeName())) continue;
                Element translationElement = (Element)translation;
                String key = translationElement.getAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_PROPERTY_NAME);
                String value = translationElement.getTextContent();
                jsonObject.addProperty(key, value);
            }
        }
        return jsonObject;
    }

    private void importI18nJCREntriesFromXMLStream(InputStream inputStream, Resource i18nDictResource, ResourceResolver resourceResolver) throws IOException, RepositoryException, ParserConfigurationException, SAXException {
        logger.trace("In function: importI18nJCREntriesFromXMLStream");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(inputStream);
        org.w3c.dom.Node rootNode = doc.getFirstChild();
        Element rootElement = (Element)rootNode;
        if (TranslationUtils.TRANSLATION_OBJECT_FILE_NODE.equals(rootElement.getNodeName())) {
            String strSourcePath = rootElement.getAttribute("sourcePath");
            String strFileType = rootElement.getAttribute("fileType");
            boolean bValid = false;
            if (strSourcePath.equals(i18nDictResource.getPath()) && strFileType != null && !strFileType.isEmpty() && strFileType.equals(TranslationObjectImpl.TranslationObjectType.I18NDICTIONARY.toString())) {
                bValid = true;
            }
            if (bValid) {
                NodeList rootChildNodeList = rootNode.getChildNodes();
                for (int rootIndex = 0; rootIndex < rootChildNodeList.getLength(); ++rootIndex) {
                    org.w3c.dom.Node propertiesNode = rootChildNodeList.item(rootIndex);
                    if (propertiesNode == null || !TranslationUtils.TRANSLATION_OBJECT_PROPERTIES_NODE.equals(propertiesNode.getNodeName())) continue;
                    NodeList translationList = propertiesNode.getChildNodes();
                    for (int translationIndex = 0; translationIndex < translationList.getLength(); ++translationIndex) {
                        Element translationElement;
                        String propertyName;
                        org.w3c.dom.Node translation = translationList.item(translationIndex);
                        if (!StringUtils.equals((CharSequence)TranslationUtils.TRANSLATION_OBJECT_PROPERTY_NODE, (CharSequence)translation.getNodeName()) || !StringUtils.equals((CharSequence)(propertyName = (translationElement = (Element)translation).getAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_PROPERTY_NAME)), (CharSequence)"sling:message")) continue;
                        String i18nEntryPath = translationElement.getAttribute(TranslationUtils.ATTRIBUTE_TRANSLATION_NODE_PATH);
                        String slingMessage = translationElement.getTextContent();
                        Node i18nEntry = (Node)resourceResolver.getResource(i18nEntryPath).adaptTo(Node.class);
                        i18nEntry.setProperty("sling:message", slingMessage);
                    }
                }
            }
        }
    }
}