PageTranslationServlet.java 17.4 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.aemds.guide.service.GuideLocalizationService
 *  com.adobe.cq.launches.api.LaunchManagerFactory
 *  com.adobe.granite.translation.api.TranslationConstants
 *  com.adobe.granite.translation.api.TranslationConstants$ContentType
 *  com.adobe.granite.translation.api.TranslationConstants$TranslationMethod
 *  com.adobe.granite.translation.api.TranslationException
 *  com.adobe.granite.translation.api.TranslationManager
 *  com.adobe.granite.translation.api.TranslationResult
 *  com.adobe.granite.translation.api.TranslationService
 *  com.adobe.granite.translation.api.TranslationService$TranslationServiceInfo
 *  com.adobe.granite.translation.core.TranslationCloudConfigUtil
 *  com.adobe.granite.ui.clientlibs.HtmlLibraryManager
 *  com.day.cq.wcm.api.LanguageManager
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageManagerFactory
 *  com.day.cq.wcm.contentsync.PageExporter
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Value
 *  javax.servlet.RequestDispatcher
 *  javax.servlet.Servlet
 *  javax.servlet.ServletRequest
 *  javax.servlet.ServletResponse
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.request.RequestDispatcherOptions
 *  org.apache.sling.api.request.RequestPathInfo
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.servlets.SlingSafeMethodsServlet
 *  org.apache.sling.commons.html.HtmlParser
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.wcm.translation.impl.servlet;

import com.adobe.aemds.guide.service.GuideLocalizationService;
import com.adobe.cq.launches.api.LaunchManagerFactory;
import com.adobe.cq.wcm.translation.impl.TranslationRuleConfigurationFile;
import com.adobe.cq.wcm.translation.impl.TranslationUtils;
import com.adobe.cq.wcm.translation.impl.process.TranslateSitePrepareProcess;
import com.adobe.granite.translation.api.TranslationConstants;
import com.adobe.granite.translation.api.TranslationException;
import com.adobe.granite.translation.api.TranslationManager;
import com.adobe.granite.translation.api.TranslationResult;
import com.adobe.granite.translation.api.TranslationService;
import com.adobe.granite.translation.core.TranslationCloudConfigUtil;
import com.adobe.granite.ui.clientlibs.HtmlLibraryManager;
import com.day.cq.wcm.api.LanguageManager;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManagerFactory;
import com.day.cq.wcm.contentsync.PageExporter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestDispatcherOptions;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.commons.html.HtmlParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1)
@Service(value={Servlet.class})
@Properties(value={@org.apache.felix.scr.annotations.Property(name="sling.servlet.resourceTypes", value={"sling/servlet/default"}), @org.apache.felix.scr.annotations.Property(name="sling.servlet.selectors", value={"translate"}), @org.apache.felix.scr.annotations.Property(name="sling.servlet.extensions", value={"html"}), @org.apache.felix.scr.annotations.Property(name="sling.servlet.methods", value={"GET"})})
public class PageTranslationServlet
extends SlingSafeMethodsServlet {
    private static final String LANGUAGE_PREFIX = "language_";
    private static final long serialVersionUID = 2421863758278649256L;
    private static final Logger log = LoggerFactory.getLogger(PageTranslationServlet.class);
    @Reference
    private TranslationManager translationManager = null;
    @Reference
    private PageManagerFactory pageManagerFactory = null;
    @Reference
    private TranslationCloudConfigUtil translationCloudConfigUtil = null;
    @Reference
    private HtmlLibraryManager htmlLibraryManager = null;
    @Reference
    private ResourceResolverFactory resolverFactory;
    @Reference
    private LanguageManager languageManager;
    @Reference
    private PageExporter pageExporter = null;
    @Reference
    private HtmlParser htmlParser = null;

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
        response.setContentType("text/html");
        String[] selectors = request.getRequestPathInfo().getSelectors();
        ResourceResolver resourceResolver = null;
        try {
            Page page;
            Resource contentResource;
            resourceResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "translation-job"));
            Resource resource = request.getResource();
            String path = resource.getPath();
            log.debug("Path is {}", (Object)path);
            String targetLanguage = this.getTargetLanguage(selectors);
            if (StringUtils.isEmpty((CharSequence)targetLanguage)) {
                targetLanguage = TranslationUtils.getResourceLanguageRoot(resource);
            }
            if ((page = (Page)resource.adaptTo(Page.class)) != null && !StringUtils.isEmpty((CharSequence)targetLanguage) && (contentResource = page.getContentResource()) != null) {
                TranslationService tsvc = null;
                try {
                    tsvc = this.translationManager.createTranslationService(resource);
                }
                catch (Exception e) {
                    log.error("Error while creating translation service {}", (Throwable)e);
                }
                if (tsvc != null && tsvc.getTranslationServiceInfo().getSupportedTranslationMethod() == TranslationConstants.TranslationMethod.MACHINE_TRANSLATION) {
                    ArrayList<TranslationCache> cacheList = new ArrayList<TranslationCache>();
                    this.collectCacheForTranslation(contentResource, resourceResolver, cacheList);
                    this.translateCacheNow(cacheList, targetLanguage, tsvc);
                }
            }
            RequestDispatcherOptions rdo = new RequestDispatcherOptions();
            rdo.setReplaceSelectors("");
            request.getRequestDispatcher(resource, rdo).include((ServletRequest)request, (ServletResponse)response);
        }
        catch (Exception e) {
            log.error("Error in translation {}", (Throwable)e);
        }
        finally {
            if (resourceResolver != null && resourceResolver.isLive()) {
                resourceResolver.close();
            }
        }
    }

    private void translateCacheNow(ArrayList<TranslationCache> cacheList, String targetLanguage, TranslationService tSvc) {
        String[] sourceStringArray = new String[cacheList.size()];
        int index = 0;
        for (TranslationCache cache : cacheList) {
            sourceStringArray[index] = cache.strStringToTranslate;
            ++index;
        }
        String contentCategory = tSvc.getDefaultCategory();
        String strSrcLang = null;
        TranslationConstants.ContentType contentType = TranslationConstants.ContentType.HTML;
        try {
            TranslationResult[] translationResultArray = tSvc.translateArray(sourceStringArray, strSrcLang, targetLanguage, contentType, contentCategory);
            if (translationResultArray != null && translationResultArray.length == cacheList.size()) {
                for (index = 0; index < translationResultArray.length; ++index) {
                    TranslationResult result = translationResultArray[index];
                    TranslationCache cache2 = cacheList.get(index);
                    if (!result.getSourceString().equals(cache2.strStringToTranslate)) continue;
                    if (cache2.indexInMultiValue == -1) {
                        try {
                            cache2.property.setValue(result.getTranslation());
                        }
                        catch (RepositoryException e) {
                            log.error("Error in setValue single {}", (Throwable)e);
                        }
                        continue;
                    }
                    this.setPropertyMultipleValue(cache2.property, result.getTranslation(), cache2.indexInMultiValue);
                }
            } else {
                log.error("Mismatch in translate String and Result");
            }
        }
        catch (TranslationException e) {
            log.error("Error in translateCacheNow {}", (Throwable)e);
        }
    }

    private void setPropertyMultipleValue(Property prop, String translation, int indexInMultiValue) {
        try {
            Value[] val_array;
            if (prop.isMultiple() && (val_array = prop.getValues()) != null && val_array.length > 0 && indexInMultiValue < val_array.length) {
                String[] newVals = new String[val_array.length];
                for (int index = 0; index < val_array.length; ++index) {
                    Value value = val_array[index];
                    newVals[index] = value.getString();
                }
                newVals[indexInMultiValue] = translation;
                prop.setValue(newVals);
            }
        }
        catch (RepositoryException ex) {
            log.error("Error in setPropertyMultipleValue {}", (Throwable)ex);
        }
    }

    private String getTargetLanguage(String[] selectors) {
        String strRetVal = null;
        if (selectors != null) {
            for (String strSelector : selectors) {
                if (strSelector == null || strSelector.indexOf("language_") == -1) continue;
                strRetVal = strSelector.substring("language_".length());
                break;
            }
        }
        return strRetVal;
    }

    private ArrayList<String> getTranslatablePropertyList(Resource resource, ResourceResolver resourceResolver) {
        String strSourceLanguage = "";
        String strDestinationLanguage = "";
        ArrayList<String> arrayList = new ArrayList<String>();
        TranslationRuleConfigurationFile ruleFile = new TranslationRuleConfigurationFile(resourceResolver, TranslateSitePrepareProcess.getRulesFilePath(), strSourceLanguage, strDestinationLanguage, this.translationManager, this.translationCloudConfigUtil, this.pageManagerFactory, this.htmlLibraryManager, null, this.languageManager, null, this.pageExporter, this.htmlParser);
        try {
            arrayList = ruleFile.getTranslatablePropertyListForNode((Node)resource.adaptTo(Node.class));
        }
        catch (RepositoryException e) {
            arrayList.add("Error while calculating getTranslatablePropertyList");
        }
        catch (IOException e) {
            arrayList.add("Error while calculating getTranslatablePropertyList");
        }
        return arrayList;
    }

    private void collectCacheForTranslation(Resource resource, ResourceResolver resourceResolver, ArrayList<TranslationCache> cacheList) {
        ArrayList<String> translatablePropertiesList;
        Iterable childList;
        if (resource != null && (translatablePropertiesList = this.getTranslatablePropertyList(resource, resourceResolver)) != null) {
            Node node = (Node)resource.adaptTo(Node.class);
            for (String strPropertyName : translatablePropertiesList) {
                this.cacheProperty(node, strPropertyName, cacheList);
            }
        }
        if ((childList = resource.getChildren()) != null) {
            for (Resource child : childList) {
                this.collectCacheForTranslation(child, resourceResolver, cacheList);
            }
        }
    }

    private void cacheProperty(Node node, String strPropertyName, ArrayList<TranslationCache> cacheList) {
        try {
            Property prop;
            if (node.hasProperty(strPropertyName) && (prop = node.getProperty(strPropertyName)) != null) {
                if (prop.isMultiple()) {
                    Value[] val_array = prop.getValues();
                    if (val_array != null && val_array.length > 0) {
                        for (int index = 0; index < val_array.length; ++index) {
                            this.appendValueToCache(prop, cacheList, val_array[index], index);
                        }
                    }
                } else {
                    Value value = prop.getValue();
                    this.appendValueToCache(prop, cacheList, value, -1);
                }
            }
        }
        catch (Exception ex) {
            log.error("Error while translating property {}", (Throwable)ex);
        }
    }

    private void appendValueToCache(Property prop, ArrayList<TranslationCache> cacheList, Value value, int indexToMultiValue) throws RepositoryException {
        if (value != null && value.getType() == 1) {
            String strStringToTranslate = value.getString();
            String strTrimmedString = strStringToTranslate;
            if (strTrimmedString != null) {
                strTrimmedString = strTrimmedString.trim();
            }
            if (strTrimmedString != null && !strTrimmedString.isEmpty()) {
                TranslationCache cache = new TranslationCache(prop, value, strTrimmedString, indexToMultiValue);
                cacheList.add(cache);
            }
        }
    }

    protected void bindTranslationManager(TranslationManager translationManager) {
        this.translationManager = translationManager;
    }

    protected void unbindTranslationManager(TranslationManager translationManager) {
        if (this.translationManager == translationManager) {
            this.translationManager = null;
        }
    }

    protected void bindPageManagerFactory(PageManagerFactory pageManagerFactory) {
        this.pageManagerFactory = pageManagerFactory;
    }

    protected void unbindPageManagerFactory(PageManagerFactory pageManagerFactory) {
        if (this.pageManagerFactory == pageManagerFactory) {
            this.pageManagerFactory = null;
        }
    }

    protected void bindTranslationCloudConfigUtil(TranslationCloudConfigUtil translationCloudConfigUtil) {
        this.translationCloudConfigUtil = translationCloudConfigUtil;
    }

    protected void unbindTranslationCloudConfigUtil(TranslationCloudConfigUtil translationCloudConfigUtil) {
        if (this.translationCloudConfigUtil == translationCloudConfigUtil) {
            this.translationCloudConfigUtil = null;
        }
    }

    protected void bindHtmlLibraryManager(HtmlLibraryManager htmlLibraryManager) {
        this.htmlLibraryManager = htmlLibraryManager;
    }

    protected void unbindHtmlLibraryManager(HtmlLibraryManager htmlLibraryManager) {
        if (this.htmlLibraryManager == htmlLibraryManager) {
            this.htmlLibraryManager = null;
        }
    }

    protected void bindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        this.resolverFactory = resourceResolverFactory;
    }

    protected void unbindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        if (this.resolverFactory == resourceResolverFactory) {
            this.resolverFactory = null;
        }
    }

    protected void bindLanguageManager(LanguageManager languageManager) {
        this.languageManager = languageManager;
    }

    protected void unbindLanguageManager(LanguageManager languageManager) {
        if (this.languageManager == languageManager) {
            this.languageManager = null;
        }
    }

    protected void bindPageExporter(PageExporter pageExporter) {
        this.pageExporter = pageExporter;
    }

    protected void unbindPageExporter(PageExporter pageExporter) {
        if (this.pageExporter == pageExporter) {
            this.pageExporter = null;
        }
    }

    protected void bindHtmlParser(HtmlParser htmlParser) {
        this.htmlParser = htmlParser;
    }

    protected void unbindHtmlParser(HtmlParser htmlParser) {
        if (this.htmlParser == htmlParser) {
            this.htmlParser = null;
        }
    }

    class TranslationCache {
        public Property property;
        public Value value;
        public String strStringToTranslate;
        public int indexInMultiValue;

        TranslationCache(Property property, Value value, String strStringToTranslate, int indexInMultiValue) {
            this.property = property;
            this.value = value;
            this.strStringToTranslate = strStringToTranslate;
            this.indexInMultiValue = indexInMultiValue;
        }
    }

}