I18nDictPrepareLanguageCopyProcess.java 13.4 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.translation.api.TranslationException
 *  com.adobe.granite.translation.api.TranslationException$ErrorCode
 *  com.day.cq.workflow.WorkflowException
 *  com.day.cq.workflow.WorkflowSession
 *  com.day.cq.workflow.exec.Route
 *  com.day.cq.workflow.exec.WorkItem
 *  com.day.cq.workflow.exec.WorkflowData
 *  com.day.cq.workflow.exec.WorkflowProcess
 *  com.day.cq.workflow.metadata.MetaDataMap
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.RepositoryException
 *  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.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.wcm.translation.impl.process;

import com.adobe.cq.wcm.translation.impl.I18nDictionary;
import com.adobe.cq.wcm.translation.impl.TranslationUtils;
import com.adobe.granite.translation.api.TranslationException;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.Route;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.exec.WorkflowData;
import com.day.cq.workflow.exec.WorkflowProcess;
import com.day.cq.workflow.metadata.MetaDataMap;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
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.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
@Service(value={WorkflowProcess.class})
@Properties(value={@Property(name="service.description", value={"Create I18N-Dictionary Language Copy"}), @Property(name="service.vendor", value={"Adobe"}), @Property(name="process.label", value={"WCM: Create I18N-Dictionary Language Copy"})})
public class I18nDictPrepareLanguageCopyProcess
implements WorkflowProcess {
    private static final Logger log = LoggerFactory.getLogger(I18nDictPrepareLanguageCopyProcess.class);
    @Reference
    private ResourceResolverFactory resolverFactory = null;
    private Resource srcDictionary = null;
    private Resource destDictionary = null;
    private Resource rootResource = null;
    private String destLanguage = null;
    private String srcBaseName = null;
    private ResourceResolver resourceResolver = null;
    private MetaDataMap metaData = null;
    private static String DEFAULT_I18N_KEY_LANGUAGE = "en";
    private static String CHECK_EXISTING_TRANSLATIONS_FIELD = "checkExistingTranslations";

    public void execute(WorkItem item, WorkflowSession workflowSession, MetaDataMap args) throws WorkflowException {
        log.debug("Creating I18N-Dictionary language copy for workitem {}", (Object)(item != null ? item.getId() : "<null>"));
        try {
            String destinationPath;
            this.resourceResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "translation-job"));
            WorkflowData data = item.getWorkflowData();
            this.validateWorkflowData(data, this.resourceResolver);
            String payloadData = (String)data.getPayload();
            this.metaData = data.getMetaDataMap();
            this.destLanguage = (String)this.metaData.get("destinationLanguage", String.class);
            if (log.isTraceEnabled()) {
                log.trace("Source Path:{}", (Object)payloadData);
                log.trace("Destination language:{}", (Object)this.destLanguage);
            }
            this.srcDictionary = this.resourceResolver.getResource(payloadData);
            if (!I18nDictionary.isI18nDictionary(this.srcDictionary)) {
                this.rootResource = this.srcDictionary;
                String checkExistingTranslations = (String)this.metaData.get(CHECK_EXISTING_TRANSLATIONS_FIELD, String.class);
                this.destDictionary = checkExistingTranslations == null ? this.createI18nDictionaryFromExistingI18nKeys(this.destLanguage, this.metaData, true) : this.createI18nDictionaryFromExistingI18nKeys(this.destLanguage, this.metaData, false);
                if (this.destDictionary != null) {
                    String srcLanguage = DEFAULT_I18N_KEY_LANGUAGE;
                    this.metaData.put((Object)"sourceLanguage", (Object)srcLanguage);
                    destinationPath = this.destDictionary.getPath();
                    this.metaData.put((Object)"targetPath", (Object)destinationPath);
                    this.resourceResolver.commit();
                }
            } else {
                this.rootResource = this.srcDictionary.getParent();
                String srcLanguage = TranslationUtils.getAttribute(this.srcDictionary, "jcr:language", String.class);
                this.srcBaseName = TranslationUtils.getAttribute(this.srcDictionary, "sling:basename", String.class);
                String checkExistingTranslations = (String)this.metaData.get(CHECK_EXISTING_TRANSLATIONS_FIELD, String.class);
                this.metaData.put((Object)"sourceLanguage", (Object)srcLanguage);
                if (checkExistingTranslations == null && this.createLanguageCopy(null) || this.createLanguageCopyIfRequired()) {
                    destinationPath = this.destDictionary.getPath();
                    this.metaData.put((Object)"targetPath", (Object)destinationPath);
                    this.resourceResolver.commit();
                }
            }
            if (!args.containsKey((Object)"PROCESS_AUTO_ADVANCE") || !((Boolean)args.get("PROCESS_AUTO_ADVANCE", Boolean.class)).booleanValue()) {
                boolean advanced = false;
                List routes = workflowSession.getRoutes(item);
                for (Route route : routes) {
                    if (!route.hasDefault()) continue;
                    workflowSession.complete(item, route);
                    advanced = true;
                    break;
                }
                if (!advanced) {
                    workflowSession.complete(item, (Route)routes.get(0));
                }
            }
        }
        catch (Exception e) {
            log.error("Error while creating I18N-Dictionary-Language-Copy", (Throwable)e);
            throw new WorkflowException("Error while creating I18N-Dictionary-Language-Copy.", (Throwable)e);
        }
        finally {
            if (this.resourceResolver != null && this.resourceResolver.isLive()) {
                this.resourceResolver.close();
            }
        }
    }

    private void validateWorkflowData(WorkflowData data, ResourceResolver resourceResolver) throws TranslationException {
        log.trace("In function: validateWorkflowData");
        String payloadData = (String)data.getPayload();
        MetaDataMap metaData = data.getMetaDataMap();
        String destLanguage = (String)metaData.get("destinationLanguage", String.class);
        if (StringUtils.isEmpty((CharSequence)payloadData) || resourceResolver.getResource(payloadData) == null || StringUtils.isEmpty((CharSequence)destLanguage)) {
            throw new TranslationException("Invalid Data", TranslationException.ErrorCode.GENERAL_EXCEPTION);
        }
    }

    private boolean createLanguageCopy(HashMap<String, String> dictionaryEntries) throws PersistenceException {
        if (dictionaryEntries == null) {
            dictionaryEntries = new HashMap();
            I18nDictionary.getAllEntriesFromDict(this.srcDictionary, dictionaryEntries);
            if (dictionaryEntries.size() == 0) {
                this.metaData.put((Object)"translationError", (Object)"NOTHING_TO_TRANSLATE");
                return false;
            }
        }
        this.rootResource = I18nDictionary.getOrCreateLanguageCopyParentResource(this.rootResource);
        this.destDictionary = TranslationUtils.checkFileExtension((Node)this.srcDictionary.adaptTo(Node.class), ".json") ? I18nDictionary.getOrCreateI18nDictionaryResource(this.resourceResolver, this.rootResource.getPath(), this.destLanguage, this.srcBaseName, true) : I18nDictionary.getOrCreateI18nDictionaryResource(this.resourceResolver, this.rootResource.getPath(), this.destLanguage, this.srcBaseName, false);
        if (this.destDictionary != null) {
            I18nDictionary.addEntriesToDict(this.destDictionary, dictionaryEntries);
            return true;
        }
        return false;
    }

    private boolean createLanguageCopyIfRequired() throws PersistenceException, UnsupportedEncodingException, RepositoryException {
        HashSet<String> existingI18nStrings = I18nDictionary.getAllI18nDictKeys(this.resourceResolver, this.destLanguage, this.srcBaseName);
        HashMap<String, String> srcI18nEntries = new HashMap<String, String>();
        I18nDictionary.getAllEntriesFromDict(this.srcDictionary, srcI18nEntries);
        if (srcI18nEntries.size() == 0) {
            this.metaData.put((Object)"translationError", (Object)"NOTHING_TO_TRANSLATE");
            return false;
        }
        I18nDictionary.getAllEntriesFromDict(this.srcDictionary, srcI18nEntries);
        HashMap newI18nDestStrings = srcI18nEntries;
        if (existingI18nStrings != null) {
            newI18nDestStrings = new HashMap();
            for (Map.Entry<String, String> entry : srcI18nEntries.entrySet()) {
                if (existingI18nStrings.contains(entry.getKey())) continue;
                newI18nDestStrings.put(entry.getKey(), entry.getValue());
            }
        }
        if (newI18nDestStrings.size() > 0) {
            return this.createLanguageCopy(newI18nDestStrings);
        }
        this.metaData.put((Object)"translationError", (Object)"LANGUAGE_COPY_EXISTS");
        return false;
    }

    Resource createI18nDictionaryFromExistingI18nKeys(String language, MetaDataMap metaData, boolean ignoreExistingTranslations) throws PersistenceException {
        log.trace("In function: createI18nDictionaryFromExistingI18nKeys");
        Resource i18nDictionary = null;
        String parentPath = this.rootResource.getPath();
        NodeIterator nodes = I18nDictionary.getAllI18nDictsAtPath(this.resourceResolver, parentPath, null);
        if (nodes != null && nodes.getSize() > 0) {
            HashSet<String> dictKeySet = new HashSet<String>();
            this.rootResource = I18nDictionary.getOrCreateLanguageCopyParentResource(this.rootResource);
            String destParentPath = this.rootResource.getPath();
            try {
                while (nodes.hasNext()) {
                    Node node = nodes.nextNode();
                    I18nDictionary.getAllKeysFromDict(this.resourceResolver.getResource(node.getPath()), dictKeySet);
                }
                if (dictKeySet.size() > 0) {
                    HashSet<String> existingI18nStrings = null;
                    if (!ignoreExistingTranslations) {
                        existingI18nStrings = I18nDictionary.getAllI18nDictKeys(this.resourceResolver, language, null);
                    }
                    if (existingI18nStrings != null) {
                        HashSet<String> newI18nDestStringSet = new HashSet<String>();
                        for (String dictKey : dictKeySet) {
                            if (existingI18nStrings.contains(dictKey)) continue;
                            newI18nDestStringSet.add(dictKey);
                        }
                        if (newI18nDestStringSet.size() > 0) {
                            i18nDictionary = I18nDictionary.getOrCreateI18nDictionaryResource(this.resourceResolver, destParentPath, language, null, true);
                            I18nDictionary.addEntriesToDict(i18nDictionary, newI18nDestStringSet);
                        } else {
                            metaData.put((Object)"translationError", (Object)"LANGUAGE_COPY_EXISTS");
                        }
                    } else {
                        i18nDictionary = I18nDictionary.getOrCreateI18nDictionaryResource(this.resourceResolver, destParentPath, language, null, true);
                        I18nDictionary.addEntriesToDict(i18nDictionary, dictKeySet);
                    }
                } else {
                    metaData.put((Object)"translationError", (Object)"NOTHING_TO_TRANSLATE");
                }
            }
            catch (Exception e) {
                return null;
            }
        }
        return i18nDictionary;
    }

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

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