DTMConfigurationUtil.java 11.4 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.crypto.CryptoException
 *  com.adobe.granite.crypto.CryptoSupport
 *  com.day.cq.commons.Externalizer
 *  com.day.cq.i18n.I18n
 *  com.day.cq.workflow.WorkflowException
 *  com.day.cq.workflow.WorkflowService
 *  com.day.cq.workflow.WorkflowSession
 *  com.day.cq.workflow.exec.Workflow
 *  com.day.cq.workflow.exec.WorkflowData
 *  com.day.cq.workflow.metadata.MetaDataMap
 *  com.day.cq.workflow.model.WorkflowModel
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.Session
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.http.HttpEntity
 *  org.apache.http.StatusLine
 *  org.apache.http.client.methods.CloseableHttpResponse
 *  org.apache.http.client.methods.HttpGet
 *  org.apache.http.client.methods.HttpUriRequest
 *  org.apache.http.impl.client.CloseableHttpClient
 *  org.apache.http.impl.client.HttpClientBuilder
 *  org.apache.http.osgi.services.HttpClientBuilderFactory
 *  org.apache.http.util.EntityUtils
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.apache.sling.commons.scheduler.ScheduleOptions
 *  org.apache.sling.commons.scheduler.Scheduler
 *  org.osgi.service.event.Event
 *  org.osgi.service.event.EventAdmin
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.dtm.impl.util;

import com.adobe.cq.dtm.impl.DTMWorkflowTriggerJob;
import com.adobe.cq.dtm.impl.constants.DTMServerType;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import com.day.cq.commons.Externalizer;
import com.day.cq.i18n.I18n;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowService;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.Workflow;
import com.day.cq.workflow.exec.WorkflowData;
import com.day.cq.workflow.metadata.MetaDataMap;
import com.day.cq.workflow.model.WorkflowModel;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.jcr.PathNotFoundException;
import javax.jcr.Session;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.http.util.EntityUtils;
import org.apache.sling.api.SlingHttpServletResponse;
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.resource.ValueMap;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.scheduler.ScheduleOptions;
import org.apache.sling.commons.scheduler.Scheduler;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DTMConfigurationUtil {
    private static final Logger LOG = LoggerFactory.getLogger(DTMConfigurationUtil.class);
    private static boolean isWaitingForExecution = false;

    public static void triggerDTMWorkflow(WorkflowService workflowService, Resource dtmConfig, DTMServerType dtmServerType) throws WorkflowException, PathNotFoundException {
        if (isWaitingForExecution) {
            return;
        }
        if (workflowService == null) {
            throw new IllegalArgumentException("Workflow service is null.");
        }
        if (dtmConfig == null) {
            throw new IllegalArgumentException("DTM configuration is null.");
        }
        if (dtmServerType == null) {
            throw new IllegalArgumentException("DTM server type is null.");
        }
        ValueMap dtmConfigProps = (ValueMap)dtmConfig.adaptTo(ValueMap.class);
        String modelPath = (String)dtmConfigProps.get((Object)((Object)((Object)dtmServerType) + "DownloadWorkflow"));
        WorkflowSession workflowSession = workflowService.getWorkflowSession((Session)dtmConfig.getResourceResolver().adaptTo(Session.class));
        WorkflowModel model = workflowSession.getModel(modelPath);
        if (model == null) {
            throw new PathNotFoundException("DTM workflow path not found.");
        }
        boolean delayExecution = false;
        String[] statuses = new String[]{"RUNNING"};
        for (Workflow workflow : workflowSession.getWorkflows(statuses)) {
            if (!modelPath.equals(workflow.getWorkflowModel().getId())) continue;
            delayExecution = true;
            isWaitingForExecution = true;
            workflowSession.terminateWorkflow(workflow);
        }
        if (delayExecution) {
            try {
                Thread.sleep(3000);
            }
            catch (InterruptedException e) {
                LOG.error("Another thread has interrupted the current thread.", (Throwable)e);
            }
            isWaitingForExecution = false;
        }
        WorkflowData wfData = workflowSession.newWorkflowData("JCR_PATH", (Object)dtmConfig.getPath());
        wfData.getMetaDataMap().put((Object)"dtmServerType", (Object)dtmServerType.toString());
        workflowSession.startWorkflow(model, wfData);
    }

    public static String getDTMJobName(String dtmConfigPath, DTMServerType dtmServerType) {
        String jobName = null;
        if (dtmConfigPath != null) {
            String dtmConfigName = DTMConfigurationUtil.getConfigNameFromContentPath(dtmConfigPath);
            jobName = (Object)((Object)dtmServerType) + "_" + dtmConfigName;
        }
        return jobName;
    }

    public static String getConfigNameFromContentPath(String path) {
        String[] pathTokens;
        String configName = null;
        if (path != null && (pathTokens = path.split("/")).length >= 2) {
            configName = pathTokens[pathTokens.length - 2];
        }
        return configName;
    }

    public static void scheduleOrUnscheduleDTMJob(ResourceResolverFactory rrf, WorkflowService workflowService, Scheduler scheduler, Resource dtmConfig, DTMServerType dtmServerType) {
        ValueMap dtmConfigProps = (ValueMap)dtmConfig.adaptTo(ValueMap.class);
        String dtmJobName = DTMConfigurationUtil.getDTMJobName(dtmConfig.getParent().getPath(), dtmServerType);
        String pollingEnablerS = (String)dtmConfigProps.get((Object)((Object)((Object)dtmServerType) + "PollingEnabler"));
        boolean pollingEnabler = Boolean.parseBoolean(pollingEnablerS);
        if (pollingEnabler) {
            String cronExpression = (String)dtmConfigProps.get((Object)((Object)((Object)dtmServerType) + "Schedule"));
            ScheduleOptions scheduleOptions = scheduler.EXPR(cronExpression);
            scheduleOptions = scheduleOptions.name(dtmJobName).onSingleInstanceOnly(true);
            if (!scheduler.schedule((Object)new DTMWorkflowTriggerJob(rrf, workflowService, dtmConfig.getPath(), dtmServerType), scheduleOptions)) {
                throw new RuntimeException("DTM " + (Object)((Object)dtmServerType) + " bundle download job could not be scheduled.");
            }
        } else {
            scheduler.unschedule(dtmJobName);
        }
    }

    public static void sendTriggerWorkflowOSGIEvent(EventAdmin eventAdmin, String dtmConfigPath, DTMServerType dtmServerType) {
        Hashtable<String, String> eventProperties = new Hashtable<String, String>();
        eventProperties.put("path", dtmConfigPath);
        eventProperties.put("dtmServerType", dtmServerType.name());
        eventAdmin.postEvent(new Event("com/adobe/cq/dtm/workflow/TRIGGER", eventProperties));
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static JSONObject callDTMApi(HttpClientBuilderFactory clientBuilderFactory, String dtmApiUrl, String token) throws JSONException {
        JSONObject jsonResponse;
        jsonResponse = null;
        CloseableHttpClient client = clientBuilderFactory.newBuilder().build();
        try {
            HttpEntity entity;
            StatusLine responseStatusLine;
            HttpGet apiRequest = new HttpGet(dtmApiUrl);
            apiRequest.addHeader("Authorization", "Token token=\"" + token + "\"");
            CloseableHttpResponse response = client.execute((HttpUriRequest)apiRequest);
            StatusLine statusLine = responseStatusLine = response != null ? response.getStatusLine() : null;
            if (responseStatusLine != null && responseStatusLine.getStatusCode() == 200 && (entity = response.getEntity()) != null) {
                String responseBody = EntityUtils.toString((HttpEntity)entity);
                jsonResponse = new JSONObject(responseBody);
            }
        }
        catch (IOException e) {
            LOG.error("Failed to obtain a response from the DTM API Server.", (Throwable)e);
        }
        finally {
            try {
                if (client != null) {
                    client.close();
                }
            }
            catch (IOException e) {
                LOG.error("Failed to close HTTP connection with the DTM API Server.", (Throwable)e);
            }
        }
        return jsonResponse;
    }

    public static void setErrorResponse(SlingHttpServletResponse response, JSONObject jsonResponse, int statusCode, I18n i18n, String errorMessage, Throwable e) throws JSONException {
        response.setStatus(statusCode);
        jsonResponse.put("error", (Object)i18n.get(errorMessage));
        if (e != null) {
            LOG.error(errorMessage, e);
        } else {
            LOG.error(errorMessage);
        }
    }

    public static String getDTMApiUrl(ResourceResolver resourceResolver) {
        Resource dtmConfigsRoot = resourceResolver.getResource("/etc/cloudservices/dynamictagmanagement/jcr:content");
        ValueMap dtmConfigRootProps = (ValueMap)dtmConfigsRoot.adaptTo(ValueMap.class);
        return (String)dtmConfigRootProps.get((Object)"apiUrl");
    }

    public static String getExternalizedURL(ResourceResolver resourceResolver, String domainHint, String path) {
        String url = null;
        if (path == null) {
            throw new IllegalArgumentException("path argument is null.");
        }
        if (StringUtils.isBlank((CharSequence)domainHint)) {
            Externalizer externalizer;
            if (resourceResolver != null && (externalizer = (Externalizer)resourceResolver.adaptTo(Externalizer.class)) != null) {
                url = externalizer.externalLink(resourceResolver, "local", path);
            }
        } else {
            url = domainHint + path;
        }
        return url;
    }

    public static String getValueIfEncrypted(CryptoSupport cryptoSupport, String text) {
        String decryptedValue = text;
        if (cryptoSupport.isProtected(text)) {
            try {
                decryptedValue = cryptoSupport.unprotect(text);
            }
            catch (CryptoException e) {
                LOG.error("Unable to decrypt text: " + text, (Throwable)e);
            }
        }
        return decryptedValue;
    }
}