PublishToCampaignProcess.java 11.1 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.crypto.CryptoSupport
 *  com.day.cq.mcm.api.newsletter.NewsLetter
 *  com.day.cq.mcm.api.newsletter.NewsletterService
 *  com.day.cq.mcm.emailprovider.types.Email
 *  com.day.cq.mcm.emailprovider.util.EmailHelper
 *  com.day.cq.replication.Agent
 *  com.day.cq.replication.AgentConfig
 *  com.day.cq.replication.AgentManager
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.workflow.WorkflowException
 *  com.day.cq.workflow.WorkflowSession
 *  com.day.cq.workflow.exec.WorkItem
 *  com.day.cq.workflow.metadata.MetaDataMap
 *  javax.jcr.RepositoryException
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.ModifiableValueMap
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.commons.json.JSONObject
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.mcm.campaign.impl;

import com.adobe.granite.crypto.CryptoSupport;
import com.day.cq.mcm.api.newsletter.NewsLetter;
import com.day.cq.mcm.api.newsletter.NewsletterService;
import com.day.cq.mcm.campaign.ACConnectorException;
import com.day.cq.mcm.campaign.CallResults;
import com.day.cq.mcm.campaign.CampaignConnector;
import com.day.cq.mcm.campaign.CampaignCredentials;
import com.day.cq.mcm.campaign.impl.AbstractCampaignProcess;
import com.day.cq.mcm.campaign.impl.IntegrationConfig;
import com.day.cq.mcm.emailprovider.types.Email;
import com.day.cq.mcm.emailprovider.util.EmailHelper;
import com.day.cq.replication.Agent;
import com.day.cq.replication.AgentConfig;
import com.day.cq.replication.AgentManager;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.metadata.MetaDataMap;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.jcr.RepositoryException;
import org.apache.felix.scr.annotations.Component;
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.ModifiableValueMap;
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.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=0)
@Service
@Property(name="process.label", value={"Adobe Campaign: Forward page to Campaign"})
public class PublishToCampaignProcess
extends AbstractCampaignProcess {
    private static final String PRM_CONTENT = "htmlContent";
    private static final long TIMEOUT = 60000;
    private final Logger log;
    @Reference
    private ResourceResolverFactory resolverFactory;
    @Reference
    private CryptoSupport cryptoSupport;
    @Reference
    private NewsletterService newsletterService;
    @Reference
    private AgentManager agentManager;
    @Reference
    private CampaignConnector connector;
    @Reference
    private IntegrationConfig integConfig;

    public PublishToCampaignProcess() {
        this.log = LoggerFactory.getLogger(this.getClass());
    }

    private Agent getPublishAgent() {
        Agent theAgent = null;
        Map agents = this.agentManager.getAgents();
        for (String agentId : agents.keySet()) {
            AgentConfig agentConfig;
            Agent toCheck = (Agent)agents.get(agentId);
            if (!toCheck.isValid() || !toCheck.isEnabled() || toCheck.isCacheInvalidator() || (agentConfig = toCheck.getConfiguration()).usedForReverseReplication() || agentConfig.isSpecific() || agentConfig.isTriggeredOnDistribute() || agentConfig.isTriggeredOnModification() || agentConfig.isTriggeredOnOffTime()) continue;
            theAgent = toCheck;
            break;
        }
        return theAgent;
    }

    private String getTargetURL() throws WorkflowException {
        String publicUrl = this.integConfig.getPublicUrl();
        if (publicUrl != null) {
            return publicUrl;
        }
        Agent publishAgent = this.getPublishAgent();
        if (publishAgent == null) {
            throw new WorkflowException("Could not determine publish agent ...");
        }
        String targetURL = publishAgent.getConfiguration().getTransportURI();
        int protocolEnd = targetURL.indexOf("://");
        if (protocolEnd < 0) {
            throw new WorkflowException("Missing publish protocol: " + targetURL);
        }
        int slashPos = targetURL.indexOf("/", protocolEnd += 3);
        if (slashPos > protocolEnd) {
            targetURL = targetURL.substring(0, slashPos);
        }
        return targetURL;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void execute(WorkItem item, WorkflowSession session, MetaDataMap args) throws WorkflowException {
        block19 : {
            ResourceResolver resolver = this.getResourceResolver(this.resolverFactory, session);
            if (resolver == null) {
                throw new WorkflowException("Could not create ResourceResolver.");
            }
            if ("failed".equals(this.getStatus(resolver, item))) {
                return;
            }
            try {
                String templateId;
                CampaignCredentials credentials;
                NewsLetter newsletter;
                Page page = this.getPage(resolver, item);
                try {
                    Configuration config = this.getWebserviceConfig(page, this.connector);
                    credentials = this.getCredentials(config, this.connector);
                    templateId = this.getTemplate(page);
                }
                catch (ACConnectorException e) {
                    throw new WorkflowException("Invalid webservice configuration", (Throwable)e);
                }
                String targetURL = this.getTargetURL();
                try {
                    Resource pageResource = resolver.getResource(page.getPath());
                    targetURL = targetURL + pageResource.getPath() + ".publish.html";
                    newsletter = this.newsletterService.buildNewsletter(pageResource, new URI(targetURL));
                }
                catch (RepositoryException re) {
                    throw new WorkflowException("Could not create NewsLetter object from Page", (Throwable)re);
                }
                catch (Exception e) {
                    throw new WorkflowException("Internal error creating NewsLetter object", (Throwable)e);
                }
                Email mail = EmailHelper.getEmail((String)null, (NewsLetter)newsletter);
                if (mail == null) {
                    throw new WorkflowException("Could not create 'Email' for 'NewsLetter'");
                }
                LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
                parameters.put("template", templateId);
                parameters.put("htmlContent", mail.getContent());
                CallResults callResults = null;
                try {
                    callResults = this.connector.postFunction("amcCreateDelivery.jssp", parameters, credentials);
                    int status = callResults.getStatus();
                    if (status != 200) {
                        throw new WorkflowException("Unexpected status code; expected: 200; is: " + status + "; template: " + templateId + "; response: " + callResults.bodyAsString());
                    }
                    String json = callResults.bodyAsString();
                    JSONObject parsedJson = new JSONObject(json);
                    String publishedId = parsedJson.getString("deliveryName");
                    if (publishedId != null) {
                        this.log.info("Newsletter published successfully to Adobe Campaign; delivery id is '{}'", (Object)publishedId);
                        Resource pageContent = page.getContentResource();
                        ModifiableValueMap props = (ModifiableValueMap)pageContent.adaptTo(ModifiableValueMap.class);
                        props.put((Object)"acDelivery", (Object)publishedId);
                        props.put((Object)"acPublishState", (Object)"published");
                        pageContent.getResourceResolver().commit();
                        break block19;
                    }
                    throw new WorkflowException("Missing delivery ID from return; response: " + json);
                }
                finally {
                    if (callResults != null) {
                        callResults.destroy();
                    }
                }
            }
            catch (Exception e) {
                this.log.error("Newsletter publication failed", (Throwable)e);
                this.setStatus(resolver, item, "failed");
            }
            finally {
                resolver.close();
            }
        }
    }

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

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

    protected void bindCryptoSupport(CryptoSupport cryptoSupport) {
        this.cryptoSupport = cryptoSupport;
    }

    protected void unbindCryptoSupport(CryptoSupport cryptoSupport) {
        if (this.cryptoSupport == cryptoSupport) {
            this.cryptoSupport = null;
        }
    }

    protected void bindNewsletterService(NewsletterService newsletterService) {
        this.newsletterService = newsletterService;
    }

    protected void unbindNewsletterService(NewsletterService newsletterService) {
        if (this.newsletterService == newsletterService) {
            this.newsletterService = null;
        }
    }

    protected void bindAgentManager(AgentManager agentManager) {
        this.agentManager = agentManager;
    }

    protected void unbindAgentManager(AgentManager agentManager) {
        if (this.agentManager == agentManager) {
            this.agentManager = null;
        }
    }

    protected void bindConnector(CampaignConnector campaignConnector) {
        this.connector = campaignConnector;
    }

    protected void unbindConnector(CampaignConnector campaignConnector) {
        if (this.connector == campaignConnector) {
            this.connector = null;
        }
    }

    protected void bindIntegConfig(IntegrationConfig integrationConfig) {
        this.integConfig = integrationConfig;
    }

    protected void unbindIntegConfig(IntegrationConfig integrationConfig) {
        if (this.integConfig == integrationConfig) {
            this.integConfig = null;
        }
    }
}