SalesforceClient.java 15.5 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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  org.apache.http.HttpEntity
 *  org.apache.http.HttpResponse
 *  org.apache.http.StatusLine
 *  org.apache.http.client.HttpClient
 *  org.apache.http.client.methods.HttpGet
 *  org.apache.http.client.methods.HttpPatch
 *  org.apache.http.client.methods.HttpPost
 *  org.apache.http.client.methods.HttpUriRequest
 *  org.apache.http.client.utils.HttpClientUtils
 *  org.apache.http.entity.ContentType
 *  org.apache.http.entity.StringEntity
 *  org.apache.http.impl.client.CloseableHttpClient
 *  org.apache.http.impl.client.HttpClients
 *  org.apache.http.util.EntityUtils
 *  org.apache.sling.commons.json.JSONArray
 *  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 com.adobe.cq.mcm.salesforce.SalesforceException;
import com.adobe.cq.mcm.salesforce.SalesforceResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SalesforceClient {
    public static final String INVALID_CLIENT_ID = "invalid_client_id";
    public static final String INVALID_CLIENT = "invalid_client";
    public static final String CLIENT_ID = "client_id";
    public static final String CLIENT_SECRET = "client_secret";
    public static final String REFRESH_ACCESS_TOKEN_ENDPOINT = "/services/oauth2/token";
    public static final String APPLICATION_FORMURL_ENCODED = "application/x-www-form-urlencoded";
    public static final String GRANT_TYPE = "grant_type";
    public static final String REFRESH_TOKEN = "refresh_token";
    protected final int HTTP_CODE_REFRESH_TOKEN_SUCCESS = 200;
    protected String clientId = "";
    protected String clientSecret = "";
    protected String instanceURL = "";
    protected String path = "";
    protected String accessToken = "";
    protected String refreshToken = "";
    protected String contentType = "";
    protected String data = "";
    protected AvailableMethods method;
    protected HashMap<String, String> parameters = new HashMap();
    private final Logger logger = LoggerFactory.getLogger(SalesforceClient.class);

    public String getClientId() {
        return this.clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
        if (!this.data.contains("client_id")) {
            this.addData("client_id", clientId);
        }
    }

    public String getClientSecret() {
        return this.clientSecret;
    }

    public void setClientSecret(String clientSecret) {
        this.clientSecret = clientSecret;
        if (!this.data.contains("client_secret")) {
            this.addData("client_secret", clientSecret);
        }
    }

    public String getData() {
        return this.data;
    }

    public void addData(String key, String value) {
        this.addData(key, value, true);
    }

    public void addData(String key, String value, boolean encode) {
        if (!this.data.equals("")) {
            this.data = this.data + "&";
        }
        try {
            this.data = this.data + key + "=" + (encode ? URLEncoder.encode(value, "UTF-8") : value);
        }
        catch (UnsupportedEncodingException e) {
            this.logger.error("Exception in adding data to Salesforce Client: " + e.getMessage());
        }
    }

    public void setData(Map<String, String> data) {
        this.data = "";
        Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pairs = it.next();
            try {
                this.data = this.data + pairs.getKey() + "=" + URLEncoder.encode(pairs.getValue(), "UTF-8");
            }
            catch (UnsupportedEncodingException e) {
                this.logger.error("Exception in adding data to Salesforce Client: " + e.getMessage());
            }
            if (!it.hasNext()) continue;
            this.data = this.data + "&";
        }
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getInstanceURL() {
        return this.instanceURL;
    }

    public void setInstanceURL(String instanceURL) {
        this.instanceURL = instanceURL;
    }

    public String getPath() {
        return this.path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getAccessToken() {
        return this.accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getRefreshToken() {
        return this.refreshToken;
    }

    public void setRefreshToken(String refreshToken) {
        this.refreshToken = refreshToken;
    }

    public String getContentType() {
        return this.contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public AvailableMethods getMethod() {
        return this.method;
    }

    public void setMethod(AvailableMethods method) {
        this.method = method;
    }

    public void setStringMethod(String method) {
        if (method.equals("GET")) {
            this.setMethod(AvailableMethods.GET);
        } else if (method.equals("POST")) {
            this.setMethod(AvailableMethods.POST);
        } else if (method.equals("PATCH")) {
            this.setMethod(AvailableMethods.PATCH);
        }
    }

    public void addParameter(String key, String value) {
        this.parameters.put(key, value);
    }

    public HashMap<String, String> getParameters() {
        return this.parameters;
    }

    public void setParameters(HashMap<String, String> parameters) {
        this.parameters = parameters;
    }

    public SalesforceResponse executeRequest() throws SalesforceException {
        if (this.method == AvailableMethods.GET) {
            return this.executeGetRequest();
        }
        if (this.method == AvailableMethods.POST || this.method == AvailableMethods.PATCH) {
            return this.executeDataRequest();
        }
        throw new SalesforceException("Unavailable HTTP Method");
    }

    public SalesforceResponse executeGetRequest() throws SalesforceException {
        SalesforceResponse response = new SalesforceResponse();
        try {
            response = this.doExecuteGetRequest();
            if (this.isAccessTokenExpired(response)) {
                SalesforceResponse refreshResponse = this.refreshAccessToken();
                response = this.doExecuteGetRequest();
                response.setAccessTokenUpdated(refreshResponse.getAccessTokenUpdated());
            }
        }
        catch (IOException e) {
            this.logger.error("Transport Error while executing a GET Request ", (Throwable)e);
            throw new SalesforceException("Transport Error while executing a GET Request ", e);
        }
        return response;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public SalesforceResponse doExecuteGetRequest() throws IOException, SalesforceException {
        SalesforceResponse response;
        CloseableHttpClient client = HttpClients.createDefault();
        response = new SalesforceResponse();
        try {
            String uri = this.instanceURL + this.path + "?";
            for (Map.Entry<String, String> pairs : this.parameters.entrySet()) {
                uri = uri + pairs.getKey() + "=" + URLEncoder.encode(pairs.getValue(), "UTF-8");
            }
            HttpGet method = new HttpGet(uri);
            if (!this.contentType.isEmpty()) {
                method.setHeader("Content-Type", this.contentType);
            }
            if (!this.accessToken.isEmpty()) {
                method.removeHeaders("Authorization");
                method.setHeader("Authorization", "OAuth " + this.accessToken);
            }
            HttpResponse httpResponse = client.execute((HttpUriRequest)method);
            try {
                response.setCode(httpResponse.getStatusLine().getStatusCode());
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    String body = EntityUtils.toString((HttpEntity)httpResponse.getEntity());
                    response.setBody(body);
                }
            }
            finally {
                HttpClientUtils.closeQuietly((HttpResponse)httpResponse);
            }
        }
        catch (Exception e) {
            this.logger.error("Error while Executing GET Request to Salesforce.com: ", (Throwable)e);
            throw new SalesforceException("Error while Executing GET Request to Salesforce.com: ", e);
        }
        finally {
            HttpClientUtils.closeQuietly((HttpClient)client);
        }
        return response;
    }

    public SalesforceResponse executeDataRequest() throws SalesforceException {
        SalesforceResponse response = new SalesforceResponse();
        try {
            response = this.doExecuteDataRequest();
            if (this.isAccessTokenExpired(response)) {
                SalesforceResponse refreshResponse = this.refreshAccessToken();
                response = this.doExecuteDataRequest();
                response.setAccessTokenUpdated(refreshResponse.getAccessTokenUpdated());
            }
        }
        catch (IOException e) {
            this.logger.error("Transport Error while executing a GET Request ", (Throwable)e);
            throw new SalesforceException("Transport Error while executing a GET Request ", e);
        }
        return response;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public SalesforceResponse doExecuteDataRequest() throws IOException, SalesforceException {
        SalesforceResponse response;
        HttpPost method = null;
        if (this.method == AvailableMethods.POST) {
            method = new HttpPost(this.instanceURL + this.path);
        } else if (this.method == AvailableMethods.PATCH) {
            method = new HttpPatch(this.instanceURL + this.path);
        }
        response = new SalesforceResponse();
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            if (!this.contentType.isEmpty()) {
                method.setHeader("Content-Type", this.contentType);
            }
            if (!this.accessToken.isEmpty()) {
                method.removeHeaders("Authorization");
                method.setHeader("Authorization", "OAuth " + this.accessToken);
            }
            method.setEntity((HttpEntity)new StringEntity(this.data, ContentType.create((String)this.contentType, (String)"UTF-8")));
            HttpResponse httpResponse = client.execute((HttpUriRequest)method);
            try {
                response.setCode(httpResponse.getStatusLine().getStatusCode());
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    String body = EntityUtils.toString((HttpEntity)httpResponse.getEntity());
                    response.setBody(body);
                }
            }
            finally {
                HttpClientUtils.closeQuietly((HttpResponse)httpResponse);
            }
        }
        catch (Exception e) {
            this.logger.error("Error while Executing POST/PUT Request to Salesforce.com: ", (Throwable)e);
            throw new SalesforceException("Error while Executing POST/PUT Request to Salesforce.com: ", e);
        }
        finally {
            method.releaseConnection();
        }
        return response;
    }

    public SalesforceResponse refreshAccessToken() throws SalesforceException {
        SalesforceClient salesforceRefreshClient = new SalesforceClient();
        salesforceRefreshClient.setRefreshToken(this.refreshToken);
        salesforceRefreshClient.setPath("/services/oauth2/token");
        salesforceRefreshClient.setInstanceURL(this.instanceURL);
        salesforceRefreshClient.setContentType("application/x-www-form-urlencoded");
        salesforceRefreshClient.addData("grant_type", "refresh_token");
        salesforceRefreshClient.addData("client_id", this.clientId);
        salesforceRefreshClient.addData("client_secret", this.clientSecret);
        salesforceRefreshClient.addData("refresh_token", this.refreshToken);
        salesforceRefreshClient.setMethod(AvailableMethods.POST);
        SalesforceResponse response = salesforceRefreshClient.executeRequest();
        try {
            if (response.getCode() != 200) {
                String errorMessage = "";
                JSONObject errorJSON = response.getBodyAsJSON();
                errorMessage = errorJSON.get("error").equals("invalid_client_id") ? "Can't refresh access token due to Invalid Customer Key " : (errorJSON.get("error").equals("invalid_client") ? "Can't refresh access token due to Invalid Customer Secret " : "Can't refresh access token due to some unknown error. Please contact Administrator ");
                this.logger.error("Can't refresh access token. Response: " + response.getBody());
                throw new SalesforceException(errorMessage);
            }
            JSONObject responseJson = new JSONObject(response.getBody());
            this.setInstanceURL(responseJson.getString("instance_url"));
            this.setAccessToken(responseJson.getString("access_token"));
            response.setAccessTokenUpdated(true);
        }
        catch (JSONException e) {
            this.logger.error("JSON Exception while refreshing the Access Token. Response: " + response.getBody() + " Exception: " + e.getMessage());
            throw new SalesforceException("JSON Exception while refreshing the Access Token. Response: " + response.getBody() + " Exception: " + e.getMessage());
        }
        return response;
    }

    public boolean isAccessTokenExpired(SalesforceResponse salesforceResponse) throws SalesforceException {
        if (salesforceResponse.getBody() != null && !"".equals(salesforceResponse.getBody())) {
            try {
                String responseBody = salesforceResponse.getBody();
                if (responseBody.charAt(0) != '[' && responseBody.charAt(responseBody.length() - 1) != ']') {
                    responseBody = "" + '[' + responseBody + ']';
                }
                JSONArray salesforceResponseJson = new JSONArray(responseBody);
                return salesforceResponseJson.getJSONObject(0).getString("errorCode").equals("INVALID_SESSION_ID");
            }
            catch (JSONException e) {
                this.logger.info("ErrorCode not found meaning success hence ignoring exception ");
            }
        }
        return false;
    }

    public static enum AvailableMethods {
        GET,
        POST,
        PATCH;
        

        private AvailableMethods() {
        }
    }

}