SalesforceExportProcess.java
16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/*
* 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;
}
}
}