ContentFragmentMachineTranslator.java 12 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.translation.api.TranslationConstants
 *  com.adobe.granite.translation.api.TranslationConstants$ContentType
 *  com.adobe.granite.translation.api.TranslationException
 *  com.adobe.granite.translation.api.TranslationResult
 *  com.adobe.granite.translation.api.TranslationService
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Value
 *  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.ContentFragmentTranslator;
import com.adobe.cq.wcm.translation.impl.TranslationRuleConfigurationFile;
import com.adobe.cq.wcm.translation.impl.TranslationUtils;
import com.adobe.granite.translation.api.TranslationConstants;
import com.adobe.granite.translation.api.TranslationException;
import com.adobe.granite.translation.api.TranslationResult;
import com.adobe.granite.translation.api.TranslationService;
import java.io.IOException;
import java.util.ArrayList;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
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;

public class ContentFragmentMachineTranslator
extends ContentFragmentTranslator {
    private ArrayList<PropertyNodeCache> cacheList = null;
    private ArrayList<Node> variationList = null;
    private ValueFactory valueFactory = null;
    private static final Logger log = LoggerFactory.getLogger(ContentFragmentMachineTranslator.class);

    public ContentFragmentMachineTranslator(TranslationRuleConfigurationFile ruleFile, TranslationService tSvc, ValueFactory valueFactory) {
        super(ruleFile, tSvc);
        this.valueFactory = valueFactory;
        this.cacheList = new ArrayList();
        this.variationList = new ArrayList();
    }

    @Override
    protected boolean processNodeProperty(Node node, Property prop, String strPropertyName) {
        log.debug("FUNCTION: translateNodeProperty ", (Object)strPropertyName);
        this.addToCacheQueue(node, strPropertyName);
        return true;
    }

    private void addToCacheQueue(Node node, String strPropertyName) {
        try {
            PropertyNodeCache propertyNode = new PropertyNodeCache();
            propertyNode.strNodePath = node.getPath();
            propertyNode.strPropertyName = strPropertyName;
            this.cacheList.add(propertyNode);
        }
        catch (RepositoryException e) {
            log.error("Error while adding node to cache list " + strPropertyName);
        }
    }

    public boolean translateResourceList(ResourceResolver resourceResolver, ArrayList<Resource> resourceList) throws RepositoryException, TranslationException, IOException {
        boolean bSaveRequired = false;
        for (Resource childResource : resourceList) {
            if (this.processTranslationOrTemporaryUpdateNode((Node)childResource.adaptTo(Node.class))) {
                bSaveRequired = true;
            }
            if (!this.processVariations((Node)childResource.adaptTo(Node.class))) continue;
            bSaveRequired = true;
        }
        if (this.saveCacheQueue(resourceResolver)) {
            bSaveRequired = true;
        }
        if (this.saveVariationQueue()) {
            bSaveRequired = true;
        }
        return bSaveRequired;
    }

    private boolean saveCacheQueue(ResourceResolver resourceResolver) {
        if (this.cacheList != null && this.cacheList.size() > 0) {
            ArrayList<Property> propList = new ArrayList<Property>();
            for (int index = 0; index < this.cacheList.size(); ++index) {
                try {
                    Node node;
                    PropertyNodeCache cacheObj = this.cacheList.get(index);
                    Resource resource = resourceResolver.resolve(cacheObj.strNodePath);
                    if (resource == null || (node = (Node)resource.adaptTo(Node.class)) == null) continue;
                    Property prop = node.getProperty(cacheObj.strPropertyName);
                    if (prop != null) {
                        propList.add(prop);
                        continue;
                    }
                    log.trace("Property is null for " + cacheObj.strPropertyName);
                    continue;
                }
                catch (Exception ex) {
                    log.error("Error while getting property ", (Throwable)ex);
                }
            }
            try {
                this.translatePropertyList(propList);
            }
            catch (Exception ex) {
                log.error("Error while translating property ", (Throwable)ex);
            }
        }
        this.cacheList.clear();
        return true;
    }

    private boolean saveVariationQueue() {
        try {
            if (this.variationList != null && this.variationList.size() > 0) {
                this.translateVariationList(this.variationList);
            }
        }
        catch (Exception ex) {
            log.error("Error while translating property ", (Throwable)ex);
        }
        this.variationList.clear();
        return true;
    }

    private void translatePropertyList(ArrayList<Property> propList) throws TranslationException, RepositoryException {
        String contentCategory = this.tSvc.getDefaultCategory();
        String strSrcLang = this.ruleFile.getSourceLanguage();
        String strDstLang = this.ruleFile.getDestinationLanguage();
        TranslationConstants.ContentType contentType = TranslationConstants.ContentType.HTML;
        String[] strStringArrayToTranslate = this.getTranslatableStringArray(propList);
        TranslationResult[] tResultArray = this.tSvc.translateArray(strStringArrayToTranslate, strSrcLang, strDstLang, contentType, contentCategory);
        this.saveTranslatedProperties(propList, tResultArray);
    }

    private void translateVariationList(ArrayList<Node> variationList) throws TranslationException, RepositoryException {
        String contentCategory = this.tSvc.getDefaultCategory();
        String strSrcLang = this.ruleFile.getSourceLanguage();
        String strDstLang = this.ruleFile.getDestinationLanguage();
        for (Node variation : variationList) {
            String[] lines = this.getTranslatableStringArrayFromVariation(variation);
            TranslationConstants.ContentType contentType = this.getContentType(variation);
            if (lines == null || lines.length <= 0) continue;
            TranslationResult[] tResultArray = this.tSvc.translateArray(lines, strSrcLang, strDstLang, contentType, contentCategory);
            this.saveTranslatedVariation(variation, tResultArray);
        }
    }

    private void saveTranslatedProperties(ArrayList<Property> propList, TranslationResult[] tResultArray) throws RepositoryException {
        int currentCount = 0;
        for (Property prop : propList) {
            if (prop.isMultiple()) {
                Value[] val_array = prop.getValues();
                if (val_array == null || val_array.length <= 0) continue;
                ArrayList<String> strOutputArray = new ArrayList<String>();
                for (int index = 0; index < val_array.length; ++index) {
                    Value value = val_array[index];
                    String strTranslationText = this.getTranslatableString(value);
                    if (StringUtils.isEmpty((CharSequence)strTranslationText)) continue;
                    String strNewTranslationText = this.getTranslatedText(strTranslationText, tResultArray[currentCount]);
                    if (!StringUtils.isEmpty((CharSequence)strNewTranslationText)) {
                        strOutputArray.add(strNewTranslationText);
                    }
                    ++currentCount;
                }
                String[] newVals = TranslationUtils.getStringArray(strOutputArray);
                prop.setValue(newVals);
                continue;
            }
            Value value = prop.getValue();
            String strTranslationText = this.getTranslatableString(value);
            if (StringUtils.isEmpty((CharSequence)strTranslationText)) continue;
            String strNewTranslationText = this.getTranslatedText(strTranslationText, tResultArray[currentCount]);
            if (!StringUtils.isEmpty((CharSequence)strNewTranslationText)) {
                prop.setValue(strNewTranslationText);
            }
            ++currentCount;
        }
    }

    private void saveTranslatedVariation(Node variationNode, TranslationResult[] tLinesArray) throws RepositoryException {
        StringBuilder builder = new StringBuilder();
        String lineSeparator = System.getProperty("line.separator");
        for (int i = 0; i < tLinesArray.length; ++i) {
            builder.append(tLinesArray[i].getTranslation());
            if (i + 1 >= tLinesArray.length) continue;
            builder.append(lineSeparator);
        }
        Value variationValue = this.valueFactory.createValue(builder.toString(), 2);
        variationNode.getProperty("jcr:content/jcr:data").setValue(variationValue);
    }

    private String getTranslatedText(String strTranslationText, TranslationResult translationResult) {
        String strRetVal = "";
        String strOriginalTranslationText = translationResult.getSourceString();
        if (strTranslationText.equals(strOriginalTranslationText)) {
            strRetVal = translationResult.getTranslation();
        } else {
            log.warn("Translated Text is not same as what we sent, please check");
        }
        return strRetVal;
    }

    private String[] getTranslatableStringArray(ArrayList<Property> propList) throws RepositoryException {
        ArrayList<String> strOutput = new ArrayList<String>();
        for (Property prop : propList) {
            if (prop.isMultiple()) {
                Value[] val_array = prop.getValues();
                if (val_array == null || val_array.length <= 0) continue;
                for (int index = 0; index < val_array.length; ++index) {
                    Value value = val_array[index];
                    String strTranslationText = this.getTranslatableString(value);
                    if (StringUtils.isEmpty((CharSequence)strTranslationText)) continue;
                    strOutput.add(strTranslationText);
                }
                continue;
            }
            Value value = prop.getValue();
            String strTranslationText = this.getTranslatableString(value);
            if (StringUtils.isEmpty((CharSequence)strTranslationText)) continue;
            strOutput.add(strTranslationText);
        }
        return TranslationUtils.getStringArray(strOutput);
    }

    private String[] getTranslatableStringArrayFromVariation(Node variationNode) throws RepositoryException {
        Value value = variationNode.getProperty("jcr:content/jcr:data").getValue();
        String valueString = value.toString();
        if (!StringUtils.isEmpty((CharSequence)valueString)) {
            return valueString.split("\\r?\\n|\\r");
        }
        return null;
    }

    private String getTranslatableString(Value value) throws IllegalStateException, RepositoryException {
        if (value != null && value.getType() == 1) {
            return value.getString();
        }
        return null;
    }

    @Override
    protected boolean processVariation(Node variationNode) throws RepositoryException {
        log.debug("FUNCTION: translate Variation ");
        String mimeType = this.getMimeType(variationNode);
        if (mimeType.equals(MIME_TYPE_HTML) || mimeType.equals(MIME_TYPE_PLAIN) || mimeType.equals(MIME_TYPE_MARKDOWN)) {
            this.variationList.add(variationNode);
            return true;
        }
        return false;
    }

    class PropertyNodeCache {
        String strNodePath;
        String strPropertyName;

        PropertyNodeCache() {
        }
    }

}