SalesforceExportProcess.java 16.7 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  aQute.bnd.annotation.ProviderType
 *  com.adobe.granite.crypto.CryptoException
 *  com.adobe.granite.crypto.CryptoSupport
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  com.day.cq.workflow.WorkflowException
 *  com.day.cq.workflow.WorkflowSession
 *  com.day.cq.workflow.exec.WorkItem
 *  com.day.cq.workflow.exec.Workflow
 *  com.day.cq.workflow.exec.WorkflowData
 *  com.day.cq.workflow.exec.WorkflowProcess
 *  com.day.cq.workflow.metadata.MetaDataMap
 *  javax.jcr.Credentials
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.SimpleCredentials
 *  javax.jcr.Value
 *  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.LoginException
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.mcm.salesforce;

import aQute.bnd.annotation.ProviderType;
import com.adobe.cq.mcm.salesforce.SalesforceClient;
import com.adobe.cq.mcm.salesforce.SalesforceConfiguration;
import com.adobe.cq.mcm.salesforce.SalesforceException;
import com.adobe.cq.mcm.salesforce.SalesforceResponse;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.exec.Workflow;
import com.day.cq.workflow.exec.WorkflowData;
import com.day.cq.workflow.exec.WorkflowProcess;
import com.day.cq.workflow.metadata.MetaDataMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.jcr.Credentials;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Value;
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.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ProviderType
@Component
@Service
@Property(name="process.label", value={"Export Leads to Salesforce"})
public class SalesforceExportProcess
implements WorkflowProcess {
    private static final Logger log = LoggerFactory.getLogger(SalesforceExportProcess.class);
    public static final String INSTANCE_URL = "instanceurl";
    public static final String ACCESS_TOKEN = "accesstoken";
    public static final String CUSTOMER_KEY = "customerkey";
    public static final String CUSTOMER_SECRET = "customersecret";
    public static final String REFRESH_TOKEN = "refreshtoken";
    public static final String JCR_PATH = "JCR_PATH";
    public static final String CQ_CLOUDSERVICECONFIG = "cq:cloudserviceconfig";
    public static final String SF_LEAD_MGMT_RESTFUL_PATH = "/services/data/v20.0/sobjects/Lead/";
    public static final String APPLICATION_JSON = "application/json";
    public static final String HTTP_PATCH = "PATCH";
    public static final String HTTP_POST = "POST";
    public static final int SF_SUCCESS_UPDATE_CODE = 204;
    private static final String SF_ENTITY_DELETED_ERRORCODE = "ENTITY_IS_DELETED";
    private static final String SF_REQUIRED_FIELD_MISSING_ERRORCODE = "REQUIRED_FIELD_MISSING";
    public static final String ERROR_CODE = "errorCode";
    public static final String SF_LEAD_CREATION_SUCCESS = "success";
    public static final String SF_LEAD_ID_FIELDNAME = "leadID";
    @Reference
    private ConfigurationManager configurationManager;
    @Reference
    private ConfigurationManagerFactory configurationManagerFactory;
    @Reference
    private ResourceResolverFactory resourceResolverFactory;
    @Reference
    private SalesforceConfiguration salesforceConfiguration;
    @Reference
    private CryptoSupport cryptoSupport;

    public void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap args) throws WorkflowException {
        WorkflowData workflowData = workItem.getWorkflowData();
        if (workflowData.getPayloadType().equals("JCR_PATH")) {
            ResourceResolver resolver;
            Session impersonateSession;
            block31 : {
                Configuration salesforceConfig;
                String configPath;
                String userId = (String)workItem.getWorkflow().getMetaDataMap().get((Object)"userId");
                if (userId == null) {
                    userId = workItem.getWorkflow().getInitiator();
                }
                impersonateSession = null;
                resolver = null;
                ConfigurationManager configurationManager = null;
                try {
                    impersonateSession = workflowSession.getSession().impersonate((Credentials)new SimpleCredentials(userId, new char[0]));
                    HashMap<String, Session> map = new HashMap<String, Session>();
                    map.put("user.jcr.session", impersonateSession);
                    resolver = this.resourceResolverFactory.getResourceResolver(map);
                    configurationManager = this.configurationManagerFactory.getConfigurationManager(resolver);
                }
                catch (RepositoryException e) {
                    throw new WorkflowException((Throwable)e);
                }
                catch (LoginException e) {
                    throw new WorkflowException((Throwable)e);
                }
                if (configurationManager != null && (configPath = (String)args.get("cq:cloudserviceconfig", String.class)) != null && (salesforceConfig = configurationManager.getConfiguration(configPath)) != null) {
                    Session session = workflowSession.getSession();
                    String workflowPayloadPath = workItem.getWorkflowData().getPayload().toString();
                    try {
                        if (session.itemExists(workflowPayloadPath)) {
                            Node node = session.getNode(workflowPayloadPath);
                            String instanceUrl = (String)salesforceConfig.get("instanceurl", (Object)"");
                            String accessToken = (String)salesforceConfig.get("accesstoken", (Object)"");
                            String clientId = (String)salesforceConfig.get("customerkey", (Object)"");
                            String encryptedCustomerSecret = (String)salesforceConfig.get("customersecret", (Object)"");
                            String encryptedRefereshToken = (String)salesforceConfig.get("refreshtoken", (Object)"");
                            String customerSecret = encryptedCustomerSecret;
                            String refreshToken = encryptedRefereshToken;
                            if (this.cryptoSupport.isProtected(encryptedCustomerSecret)) {
                                customerSecret = this.cryptoSupport.unprotect(encryptedCustomerSecret);
                            }
                            if (this.cryptoSupport.isProtected(encryptedRefereshToken)) {
                                refreshToken = this.cryptoSupport.unprotect(encryptedRefereshToken);
                            }
                            Map<String, String> fieldsMapping = this.salesforceConfiguration.getLeadsMapping();
                            HashMap<String, String> httpData = new HashMap<String, String>();
                            for (Map.Entry<String, String> entry : fieldsMapping.entrySet()) {
                                if (!node.hasProperty(entry.getKey())) continue;
                                String fieldValue = node.getProperty(entry.getKey()).getValue().getString();
                                httpData.put(entry.getValue(), fieldValue);
                            }
                            JSONObject requestData = new JSONObject(httpData);
                            String requestDataString = requestData.toString();
                            SalesforceClient salesforceClient = new SalesforceClient();
                            salesforceClient.setAccessToken(accessToken);
                            salesforceClient.setRefreshToken(refreshToken);
                            salesforceClient.setClientId(clientId);
                            salesforceClient.setClientSecret(customerSecret);
                            salesforceClient.setInstanceURL(instanceUrl);
                            salesforceClient.setContentType("application/json");
                            StringBuilder salesforcePath = new StringBuilder("/services/data/v20.0/sobjects/Lead/");
                            if (node.hasProperty("leadID")) {
                                salesforcePath.append(node.getProperty("leadID").getValue().getString());
                                salesforceClient.setStringMethod("PATCH");
                            } else {
                                salesforceClient.setStringMethod("POST");
                            }
                            salesforceClient.setPath(salesforcePath.toString());
                            salesforceClient.setData(requestDataString);
                            SalesforceResponse salesforceResponse = salesforceClient.executeRequest();
                            if (salesforceResponse.getAccessTokenUpdated().booleanValue()) {
                                Node configNode = session.getNode(configPath).getNode("jcr:content");
                                configNode.setProperty("accesstoken", salesforceClient.getAccessToken());
                                configNode.getSession().save();
                            }
                            try {
                                if (salesforceResponse.getBody() == null && salesforceResponse.getCode() == 204) {
                                    log.info("Salesforce Lead Updated with Success (id: " + node.getProperty("leadID").getValue().getString() + ")");
                                } else {
                                    JSONObject responseJson = salesforceResponse.getBodyAsJSON();
                                    if (responseJson.has("success") && responseJson.getBoolean("success")) {
                                        if (!node.hasProperty("leadID")) {
                                            node.setProperty("leadID", responseJson.getString("id"));
                                            session.save();
                                            log.info("New Salesforce Lead Created with Success (id: " + responseJson.getString("id") + ")");
                                        }
                                    } else if (responseJson.has("errorCode") && responseJson.getString("errorCode") != null) {
                                        String errorCode = responseJson.getString("errorCode");
                                        if ("ENTITY_IS_DELETED".equals(errorCode)) {
                                            Boolean recreateLeadFlag = (Boolean)args.get("recreateLead", Boolean.class);
                                            if (recreateLeadFlag != null && recreateLeadFlag.equals(true)) {
                                                salesforceClient.setPath("/services/data/v20.0/sobjects/Lead/");
                                                salesforceClient.setStringMethod("POST");
                                                salesforceResponse = salesforceClient.executeRequest();
                                                responseJson = salesforceResponse.getBodyAsJSON();
                                                node.setProperty("leadID", responseJson.getString("id"));
                                                session.save();
                                                log.info("Salesforce Lead Created again (after deletion from SF) with Success (id: " + responseJson.getString("id") + ")");
                                            }
                                        } else if ("REQUIRED_FIELD_MISSING".equals(errorCode)) {
                                            log.error("Lead Creation failed. Some required fields missing while creating lead: " + salesforceResponse.getBody());
                                            throw new SalesforceException("Lead Creation failed. Some required fields missing while creating lead: " + salesforceResponse.getBody());
                                        }
                                    }
                                }
                                break block31;
                            }
                            catch (JSONException e) {
                                log.error("JSON Exception while parsing Response from Salesforce in Lead creation/updation workflow. Response: " + salesforceResponse.getBody());
                                break block31;
                            }
                        }
                        log.error("Salesforce node could not be found. path: " + workflowPayloadPath);
                        throw new WorkflowException("Salesforce node could not be found. path: " + workflowPayloadPath);
                    }
                    catch (RepositoryException re) {
                        log.error("Repository Exception in Lead Creation Workflow " + re.getMessage());
                        throw new WorkflowException("Repository Exception in Lead Creation Workflow " + re.getMessage());
                    }
                    catch (CryptoException e) {
                        log.error("Crypto Exception in Lead Creation Workflow: " + e.getMessage());
                        throw new WorkflowException("Crypto Exception in Lead Creation Workflow: " + e.getMessage());
                    }
                    catch (SalesforceException se) {
                        log.error("Exception while Publishing lead to Salesforce: " + se.getMessage());
                        throw new WorkflowException("Exception while Publishing lead to Salesforce: " + se.getMessage());
                    }
                }
            }
            if (impersonateSession != null) {
                impersonateSession.logout();
            }
            if (resolver != null) {
                resolver.close();
            }
        }
    }

    protected void bindConfigurationManager(ConfigurationManager configurationManager) {
        this.configurationManager = configurationManager;
    }

    protected void unbindConfigurationManager(ConfigurationManager configurationManager) {
        if (this.configurationManager == configurationManager) {
            this.configurationManager = null;
        }
    }

    protected void bindConfigurationManagerFactory(ConfigurationManagerFactory configurationManagerFactory) {
        this.configurationManagerFactory = configurationManagerFactory;
    }

    protected void unbindConfigurationManagerFactory(ConfigurationManagerFactory configurationManagerFactory) {
        if (this.configurationManagerFactory == configurationManagerFactory) {
            this.configurationManagerFactory = null;
        }
    }

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

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

    protected void bindSalesforceConfiguration(SalesforceConfiguration salesforceConfiguration) {
        this.salesforceConfiguration = salesforceConfiguration;
    }

    protected void unbindSalesforceConfiguration(SalesforceConfiguration salesforceConfiguration) {
        if (this.salesforceConfiguration == salesforceConfiguration) {
            this.salesforceConfiguration = null;
        }
    }

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

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