Thursday, April 13, 2017

Integration of Adobe Experience Manager(AEM) with Salesforce - Part4

Integration of Adobe Experience Manager(AEM) with Salesforce - Part4

This post will explain the approach to extend the basic Adobe Experience Manager(AEM) Salesforce connector to create/update the Salesforce objects.

Refer the following post for details on integrating Salesforce with Adobe Experience Manager(AEM)
https://www.albinsblog.com/2017/03/integrationofaemcq5withsalesforcepart1.html
https://www.albinsblog.com/2017/04/integrationofaemcq5withsalesforcepart2.html
https://www.albinsblog.com/2017/04/integration-of-aem-with-salesforce-part3.html

Prerequisite  - Configure the Salesforce cloud connection, refer the above mentioned post for more details.
Enable the Salesforce cloud configuration for the Home page of the websites.


Dependency:

Add the below Maven dependency to the project
For 6.0 and 6.1
<dependency>
    <groupId>com.adobe.aem</groupId>
    <artifactId>aem-api</artifactId>
    <version>6.0.0.1</version>
    <scope>provided</scope>
</dependency>

For 6.2
<dependency>
    <groupId>com.adobe.aem</groupId>
    <artifactId>uber-jar</artifactId>
    <version>6.2.0</version>
    <classifier>apis</classifier>
    <scope>provided</scope>
</dependency>


Change the version based on your server

Create a Java Class (SalesforceUpdateProcess.java) that will use the base connector to create/update Salesforce objects - This code provides the support to OPPORTUNITY, change the code accordingly to enable the support for other objects.

import javax.jcr.Node;
import javax.jcr.RepositoryException;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.adobe.cq.mcm.salesforce.SalesforceClient;
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;

@Component
@Service({SalesforceUpdateProcess.class})
public class SalesforceUpdateProcess  
{
  private static final Logger log = LoggerFactory.getLogger(SalesforceUpdateProcess.class);

  @Reference
  private CryptoSupport cryptoSupport;
  
  public void update(Configuration cloudConfig, SalesforceUpdateParameters parameters, ResourceResolver resolver)
   throws Exception
 {
 
   if (cloudConfig != null)
   {
     String instanceUrl = (String)cloudConfig.get("instanceurl", "");
     String accessToken = (String)cloudConfig.get("accesstoken", "");
     String clientId = (String)cloudConfig.get("customerkey", "");
     String encryptedCustomerSecret = (String)cloudConfig.get("customersecret", "");
     String encryptedRefereshToken = (String)cloudConfig.get("refreshtoken", "");
     try
     {
       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);
       }
       
       JSONObject requestData = new JSONObject(parameters.getInputData());
                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");
                String sObjectName="";
                if (SalesforceUpdateParameters.SalesforceObjectType.OPPORTUNITY.equals(parameters.getObjectType())) {
                sObjectName="OPPORTUNITY";
                }
                StringBuilder salesforcePath = new StringBuilder("/services/data/v20.0/sobjects/"+sObjectName+"/");
                if (SalesforceUpdateParameters.SalesforceOperationType.UPDATE.equals(parameters.getOperationType())) 
                {
                salesforcePath=salesforcePath.append(parameters.getSalesforceObjectId());
                salesforceClient.setStringMethod("PATCH");
                }else if (SalesforceUpdateParameters.SalesforceOperationType.CREATE.equals(parameters.getOperationType())) {
                salesforceClient.setStringMethod("POST");
               }     
   
                salesforceClient.setPath(salesforcePath.toString());
                salesforceClient.setData(requestDataString);
                
                SalesforceResponse salesforceResponse = salesforceClient.executeRequest();
       if (salesforceResponse.getAccessTokenUpdated().booleanValue())
       {
         String configPath = cloudConfig.getPath();
         Resource configResource = resolver.getResource(configPath);
         Node configNode = ((Node)configResource.adaptTo(Node.class)).getNode("jcr:content");
         configNode.setProperty("accesstoken", salesforceClient.getAccessToken());
         configNode.getSession().save();
       }   
               
       if (salesforceResponse.getCode()!=204 && salesforceResponse.getCode()!=201)
                {
        throw new Exception("Error in Update"+salesforceResponse.getBody());
                }
     }
     catch (RepositoryException e)
     {
       log.error("Repository Exception in Update " + e.getMessage());
       throw new Exception("Repository Exception in Update " + e.getMessage());
     }
     catch (CryptoException e)
     {
       log.error("Cryto Exception in Update " + e.getMessage());
       throw new Exception("Crypto Exception in Update " + e.getMessage());
     }
     catch (JSONException e)
     {
       log.error("JSON Exception in Update " + e.getMessage());
       throw new Exception("JSON Exception in Update " + e.getMessage());
     }
     catch (Exception e)
     {
       log.error("Exception in Update " + e.getMessage());
       throw new Exception("Exception in Update " + e.getMessage());
     }
   }     
 }  
  
  protected void bindCryptoSupport(CryptoSupport paramCryptoSupport)
  {
    this.cryptoSupport = paramCryptoSupport;
  }
  
  protected void unbindCryptoSupport(CryptoSupport paramCryptoSupport)
  {
    if (this.cryptoSupport == paramCryptoSupport) {
      this.cryptoSupport = null;
    }
  }
}


Create a Java class(SalesforceUpdateParameters.java) that will provide the support for required Salesforce objects -  - This code provides the support to OPPORTUNITY, change the code accordingly to enable the support for other objects.

import java.util.HashMap;

public class SalesforceUpdateParameters
{
  private HashMap<String,String> inputData;
  private SalesforceObjectType objectType;  
  private SalesforceOperationType opeationType;
  private String salesforceObjectId;
  
  public static enum SalesforceOperationType
  {
 UPDATE,CREATE;
    
    private SalesforceOperationType() {}
  }  
  public SalesforceOperationType getOperationType()
  {
    return this.opeationType;
  }  
  public void setOpeationType(SalesforceOperationType opeationType)
  {
    this.opeationType = opeationType;
  }  
  public void setOpeationType(String opeationType)
  {
    if (SalesforceOperationType.UPDATE.name().equalsIgnoreCase(opeationType)) {
      this.opeationType = SalesforceOperationType.UPDATE;
    } else if (SalesforceOperationType.CREATE.name().equalsIgnoreCase(opeationType)) {
        this.opeationType = SalesforceOperationType.CREATE;
      }
  }  
  public static enum SalesforceObjectType
  {
 OPPORTUNITY;    
    private SalesforceObjectType() {}
  }  
  public SalesforceObjectType getObjectType()
  {
    return this.objectType;
  }  
  public void setObjectType(SalesforceObjectType objectType)
  {
    this.objectType = objectType;
  }  
  public void setObjectType(String objectType)
  {
    if (SalesforceObjectType.OPPORTUNITY.name().equalsIgnoreCase(objectType)) {
      this.objectType = SalesforceObjectType.OPPORTUNITY;
    } 
  }  
  public HashMap<String,String> getInputData()
  {
    return this.inputData;
  }  
  public void setInputData(HashMap<String,String> inputData)
  {
    this.inputData = inputData;
  }
public String getSalesforceObjectId() {
return salesforceObjectId;
}
public void setSalesforceObjectId(String salesforceObjectId) {
this.salesforceObjectId = salesforceObjectId;
}
}

Create a components that will invoke SalesforceUpdateProcess.java to create/update the Salesforce objects by providing required parameters.

<% 

           try{

            String[] cloudConfigs = pageProperties.getInherited("cq:cloudserviceconfigs", new String[]{});

            ConfigurationManager configurationManager = resourceResolver.adaptTo(ConfigurationManager.class);



            if(cloudConfigs.length>0){

                Configuration salesforceConfig = configurationManager.getConfiguration("salesforce",cloudConfigs);



SalesforceUpdateProcess updateClient = sling.getService(SalesforceUpdateProcess.class);
                SalesforceUpdateParameters updateParameters = new SalesforceUpdateParameters();
                                                      updateParameters.setObjectType(SalesforceUpdateParameters.SalesforceObjectType.OPPORTUNITY);

                HashMap<String,String> inputData=new HashMap<String,String>();//Send only the required field for update
                inputData.put("Description","Test Description");
                inputData.put("Name","TestOpportunity");
                inputData.put("StageName","Prospecting");   
                inputData.put("CloseDate","2017-04-30");   

                updateParameters.setInputData(inputData);
                updateParameters.setOpeationType(SalesforceUpdateParameters.SalesforceOperationType.CREATE);//Create New Object
                //updateParameters.setOpeationType(SalesforceUpdateParameters.SalesforceOperationType.UPDATE);//Update the existing object by providong the id
                //updateParameters.setSalesforceObjectId("0069000000rjArf");//Object id to update

                updateClient.update(salesforceConfig, updateParameters, resource.getResourceResolver());

                }else
                {%>
 <div id="cloudconfigerror">
                    Salesforce Cloud Service Configuration could not be found for this page.
                </div>
                <%}
                }catch(Exception e)
                {%>
 <div id="error">
     Exception occurred while Create/Update. Please contact Administrator.
            </div>
            <%}

                %>




No comments:

Post a Comment