EchoSignServiceImpl.java 30.4 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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.aem.adobesign.handler.AdobeSignStatusHandler
 *  com.adobe.aem.adobesign.recipient.RecipientAuthenticationMethod
 *  com.adobe.aem.adobesign.recipient.RecipientInfo
 *  com.adobe.aem.adobesign.recipient.RecipientPhoneInfo
 *  com.adobe.aem.adobesign.recipient.RecipientSecurityOption
 *  com.adobe.aem.adobesign.recipient.RecipientSetInfo
 *  com.adobe.aem.adobesign.recipient.RecipientSetInfo$RecipientRole
 *  com.adobe.aem.adobesign.recipient.SigningUrl
 *  com.adobe.aem.adobesign.recipient.SigningUrlSetInfo
 *  com.adobe.aem.adobesign.service.AdobeSignService
 *  com.adobe.aem.adobesign.service.AdobeSignServiceException
 *  com.adobe.aem.adobesign.service.AgreementCancellationOptions
 *  com.adobe.aem.adobesign.service.AgreementCreationOptions
 *  com.adobe.aem.adobesign.service.AgreementCreationOptions$SignatureFlow
 *  com.adobe.aem.adobesign.service.AgreementCreationResponse
 *  com.adobe.aem.adobesign.service.AgreementStatusOptions
 *  com.adobe.aem.adobesign.service.AgreementStatusResponse
 *  com.adobe.aem.adobesign.service.AgreementStatusResponse$AgreementStatus
 *  com.adobe.aem.adobesign.service.Attachment
 *  com.adobe.aem.adobesign.service.WidgetCreationOptions
 *  com.adobe.aemds.guide.addon.signing.DocumentSigningService
 *  com.adobe.aemds.guide.addon.signing.SigningUtils
 *  com.adobe.aemds.guide.addon.signing.echosign.EchoSignConfiguration
 *  com.adobe.aemds.guide.addon.signing.echosign.EchoSignConstants
 *  com.adobe.aemds.guide.addon.signing.echosign.EchoSignConstants$ERROR_CODE
 *  com.adobe.aemds.guide.addon.signing.echosign.EchoSignUtils
 *  com.adobe.aemds.guide.model.FormSubmitInfo
 *  com.adobe.aemds.guide.model.SignAgreementInfo
 *  com.adobe.aemds.guide.model.SignerInfo
 *  com.adobe.aemds.guide.model.SignerInfoSource
 *  com.adobe.aemds.guide.model.SignerResource
 *  com.adobe.aemds.guide.service.GuideException
 *  com.adobe.aemds.guide.service.SignAgreementService
 *  com.adobe.aemds.guide.utils.GuideSubmitUtils
 *  com.adobe.aemds.guide.utils.XMLUtils
 *  com.adobe.fd.core.security.CurrentUserService
 *  com.adobe.forms.common.service.FileAttachmentWrapper
 *  com.adobe.forms.service.LCFormsService
 *  com.adobe.granite.resourceresolverhelper.ResourceResolverHelper
 *  com.day.cq.i18n.I18n
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  javax.jcr.AccessDeniedException
 *  javax.jcr.ItemNotFoundException
 *  javax.jcr.RepositoryException
 *  org.apache.commons.io.IOUtils
 *  org.apache.commons.lang.StringUtils
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.aemds.guide.addon.signing.echosign.impl;

import com.adobe.aem.adobesign.handler.AdobeSignStatusHandler;
import com.adobe.aem.adobesign.recipient.RecipientAuthenticationMethod;
import com.adobe.aem.adobesign.recipient.RecipientInfo;
import com.adobe.aem.adobesign.recipient.RecipientPhoneInfo;
import com.adobe.aem.adobesign.recipient.RecipientSecurityOption;
import com.adobe.aem.adobesign.recipient.RecipientSetInfo;
import com.adobe.aem.adobesign.recipient.SigningUrl;
import com.adobe.aem.adobesign.recipient.SigningUrlSetInfo;
import com.adobe.aem.adobesign.service.AdobeSignService;
import com.adobe.aem.adobesign.service.AdobeSignServiceException;
import com.adobe.aem.adobesign.service.AgreementCancellationOptions;
import com.adobe.aem.adobesign.service.AgreementCreationOptions;
import com.adobe.aem.adobesign.service.AgreementCreationResponse;
import com.adobe.aem.adobesign.service.AgreementStatusOptions;
import com.adobe.aem.adobesign.service.AgreementStatusResponse;
import com.adobe.aem.adobesign.service.Attachment;
import com.adobe.aem.adobesign.service.WidgetCreationOptions;
import com.adobe.aemds.guide.addon.signing.DocumentSigningService;
import com.adobe.aemds.guide.addon.signing.SigningUtils;
import com.adobe.aemds.guide.addon.signing.echosign.EchoSignConfiguration;
import com.adobe.aemds.guide.addon.signing.echosign.EchoSignConstants;
import com.adobe.aemds.guide.addon.signing.echosign.EchoSignUtils;
import com.adobe.aemds.guide.model.FormSubmitInfo;
import com.adobe.aemds.guide.model.SignAgreementInfo;
import com.adobe.aemds.guide.model.SignerInfo;
import com.adobe.aemds.guide.model.SignerInfoSource;
import com.adobe.aemds.guide.model.SignerResource;
import com.adobe.aemds.guide.service.GuideException;
import com.adobe.aemds.guide.service.SignAgreementService;
import com.adobe.aemds.guide.utils.GuideSubmitUtils;
import com.adobe.aemds.guide.utils.XMLUtils;
import com.adobe.fd.core.security.CurrentUserService;
import com.adobe.forms.common.service.FileAttachmentWrapper;
import com.adobe.forms.service.LCFormsService;
import com.adobe.granite.resourceresolverhelper.ResourceResolverHelper;
import com.day.cq.i18n.I18n;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.jcr.AccessDeniedException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.RepositoryException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferencePolicy;
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.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Component(metatype=1, immediate=1, label="AdobeSignService")
@Service(value={DocumentSigningService.class, SignAgreementService.class})
public class EchoSignServiceImpl
implements DocumentSigningService {
    protected static final Logger log = LoggerFactory.getLogger(EchoSignServiceImpl.class);
    @Reference(policy=ReferencePolicy.DYNAMIC)
    private LCFormsService lcFormsService;
    @Reference(policy=ReferencePolicy.DYNAMIC)
    private ResourceResolverHelper resourceResolverHelper;
    @Reference
    private ResourceResolverFactory resourceResolverFactory;
    @Reference(target="(handler=formsportal)")
    private AdobeSignStatusHandler adobeSignSatusHandler;
    @Reference
    private ConfigurationManagerFactory configurationManagerFactory;
    @Reference
    private AdobeSignService adobeSignService;
    @Reference
    private CurrentUserService currentUserService;

    public boolean storeSignedDocument(String documentId, Map<String, String> configMap) {
        throw new UnsupportedOperationException("Stored Signed document not supported for Adobe Sign service.");
    }

    public byte[] getSignedDocument(String documentKey, Map<String, String> configMap) {
        byte[] signedDocBytes = null;
        EchoSignConfiguration config = EchoSignConfiguration.getConfig(configMap);
        try {
            AgreementStatusOptions statusOptions = new AgreementStatusOptions();
            statusOptions.setFetchSignedDocument(true);
            AgreementStatusResponse asr = this.adobeSignService.getAgreementStatus(documentKey, config.getConfigPath(), statusOptions);
            signedDocBytes = asr.getSignedDocument();
        }
        catch (AdobeSignServiceException e) {
            log.error("Error while calling getSignedDocument API", (Throwable)e);
        }
        return signedDocBytes;
    }

    public JSONObject getSignatureDocument(String formData, String templatePath, Map<String, String> configMap, I18n i18n) {
        EchoSignConfiguration config = EchoSignConfiguration.getConfig(configMap);
        String email = this.getCurrentUserEmail();
        JSONObject resultObject = new JSONObject();
        try {
            if (config != null) {
                if (StringUtils.isNotEmpty((String)email)) {
                    config.setRecipientEmail(email);
                    byte[] outputPdfContent = SigningUtils.getPDFContent((LCFormsService)this.lcFormsService, (String)formData, (String)templatePath);
                    if (outputPdfContent != null) {
                        try {
                            AgreementCreationResponse response = this.adobeSignService.createPersonalizedWidget(outputPdfContent, config.getConfigPath(), EchoSignUtils.createWidgetOptions((EchoSignConfiguration)config, (ResourceResolver)this.resourceResolverHelper.getResourceResolver()));
                            resultObject.put("serviceResultStatus", EchoSignConstants.ERROR_CODE.OK.getCode());
                            resultObject.put("resultURL", (Object)response.getUrl());
                            resultObject.put("resultJavascript", (Object)response.getEmbeddedCode());
                            resultObject.put("documentKey", (Object)response.getAgreementId());
                        }
                        catch (AdobeSignServiceException asse) {
                            this.processAdobeSignException(resultObject, asse.getMessage(), i18n);
                            log.error("Error while calling createPersonalEmbeddedWidget API", (Throwable)asse);
                        }
                    } else {
                        resultObject.put("serviceResultStatus", EchoSignConstants.ERROR_CODE.PDF_GENERATION.getCode());
                        resultObject.put("serviceFailureReason", (Object)EchoSignConstants.ERROR_CODE.PDF_GENERATION.getLocalizedMessage(i18n));
                        log.error("Failed to generate the PDF from formData");
                    }
                } else {
                    resultObject.put("serviceResultStatus", EchoSignConstants.ERROR_CODE.EMAIL_NOT_DEFINED.getCode());
                    resultObject.put("serviceFailureReason", (Object)EchoSignConstants.ERROR_CODE.EMAIL_NOT_DEFINED.getLocalizedMessage(i18n));
                }
            } else {
                resultObject.put("serviceResultStatus", EchoSignConstants.ERROR_CODE.NO_SIGNING_SERVICE.getCode());
                resultObject.put("serviceFailureReason", (Object)EchoSignConstants.ERROR_CODE.NO_SIGNING_SERVICE.getLocalizedMessage(i18n));
            }
        }
        catch (JSONException jsonException) {
            log.error("Error while creating result object", (Throwable)jsonException);
        }
        return resultObject;
    }

    public JSONObject getSignatureURL(String formData, String templatePath, Map<String, String> configMap, I18n i18n) {
        return this.getSignatureDocument(formData, templatePath, configMap, i18n);
    }

    private void processAdobeSignException(JSONObject resultObject, String errorMessage, I18n i18n) {
        try {
            if (errorMessage.startsWith("AEM-AS-100")) {
                resultObject.put("serviceResultStatus", EchoSignConstants.ERROR_CODE.ADOBE_SIGN_EXCEPTION.getCode());
                resultObject.put("serviceFailureReason", (Object)EchoSignConstants.ERROR_CODE.ADOBE_SIGN_EXCEPTION.getLocalizedMessage(i18n));
            } else {
                resultObject.put("serviceResultStatus", EchoSignConstants.ERROR_CODE.SIGN_SERVICE_EXCEPTION.getCode());
                resultObject.put("serviceFailureReason", (Object)(EchoSignConstants.ERROR_CODE.SIGN_SERVICE_EXCEPTION.getLocalizedMessage(i18n) + errorMessage));
            }
        }
        catch (JSONException jsonException) {
            log.error("Error while parsing EchoSign exception", (Throwable)jsonException);
        }
    }

    private ResourceResolver getServiceResourceResolver() {
        try {
            return this.resourceResolverFactory.getServiceResourceResolver(null);
        }
        catch (Exception e) {
            log.error("Cannot provide  serviceResourceResolver", (Throwable)e);
            return null;
        }
    }

    public ConfigurationManager getConfigurationManager() {
        ResourceResolver serviceResourceResolver = this.getServiceResourceResolver();
        return this.configurationManagerFactory.getConfigurationManager(serviceResourceResolver);
    }

    private String getCurrentUserEmail() {
        return (String)this.currentUserService.getCurrentUserAsMap().get("email");
    }

    public Map<String, Object> submitAgreement(String systemId, String agreementId, String signConfigPath) throws GuideException {
        Map result = null;
        try {
            AgreementStatusOptions statusOptions = new AgreementStatusOptions();
            statusOptions.setFetchAttachments(true);
            statusOptions.setFetchFormData(true);
            statusOptions.setFetchSignedDocument(true);
            AgreementStatusResponse agreementStatusResponse = this.adobeSignService.getAgreementStatus(agreementId, signConfigPath, statusOptions);
            result = this.adobeSignSatusHandler.updateAgreementStatus(systemId, agreementStatusResponse);
        }
        catch (AdobeSignServiceException signException) {
            throw new GuideException((Exception)signException);
        }
        return result;
    }

    public SignAgreementInfo createAgreement(FormSubmitInfo formSubmitInfo, String postSigningURL, Boolean fetchFirstSignerUrl) {
        SignAgreementInfo signAgreementInfo = new SignAgreementInfo();
        Resource formContainerResource = formSubmitInfo.getFormContainerResource();
        try {
            SignerResource signerResource = (SignerResource)formContainerResource.getChild("signerInfo").adaptTo(SignerResource.class);
            String signConfigPath = signerResource.getSignConfigPath();
            FileAttachmentWrapper pdf = formSubmitInfo.getDocumentOfRecord();
            AgreementCreationOptions agreementCreationOptions = this.createAgreementOptions(signerResource, formSubmitInfo, postSigningURL);
            AgreementCreationResponse agreementCreationResponse = this.adobeSignService.createAgreement(pdf.getValue(), signConfigPath, agreementCreationOptions);
            String agreementId = agreementCreationResponse.getAgreementId();
            signAgreementInfo.setAgreementId(agreementId);
            AgreementStatusOptions statusOptions = new AgreementStatusOptions();
            AgreementStatusResponse agreementStatusResponse = this.adobeSignService.getAgreementStatus(agreementId, signConfigPath, statusOptions);
            signAgreementInfo.setNextSigners(EchoSignUtils.getNextSigners((List)agreementStatusResponse.getNextParticipantSets()));
            signAgreementInfo.setAgreementStatus(agreementStatusResponse.getAgreementStatus().toString());
            if (fetchFirstSignerUrl.booleanValue() || signerResource.isFirstSignerFormFiller().booleanValue()) {
                List signingUrlsSet = this.adobeSignService.getSigningUrls(agreementId, signConfigPath);
                signAgreementInfo.setSigningURL(((SigningUrl)((SigningUrlSetInfo)signingUrlsSet.get(0)).getSigningUrls().get(0)).geteSignUrl());
            }
        }
        catch (AdobeSignServiceException | IOException | RepositoryException | JSONException e) {
            log.error("Unable to create agreement", (Throwable)e);
            signAgreementInfo.setAgreementId(null);
        }
        return signAgreementInfo;
    }

    private AgreementCreationOptions createAgreementOptions(SignerResource signerResource, FormSubmitInfo formSubmitInfo, String postSigningURL) throws JSONException, AccessDeniedException, ItemNotFoundException, RepositoryException, IOException {
        AgreementCreationOptions agreementOptions = new AgreementCreationOptions();
        if (formSubmitInfo.getContentType().equals("application/xml")) {
            agreementOptions.setRecipientSetInfos(this.getSignerSetsFromDataXML(formSubmitInfo.getData(), signerResource));
        } else {
            agreementOptions.setRecipientSetInfos(this.getSignerSetsFromDataJson(formSubmitInfo.getData(), signerResource));
        }
        agreementOptions.setLocale(formSubmitInfo.getLocale());
        Resource contentResource = GuideSubmitUtils.getParentResource((Resource)formSubmitInfo.getFormContainerResource(), (String)"cq:PageContent");
        String agreementName = (String)contentResource.getValueMap().get("jcr:title", String.class);
        if (StringUtils.isEmpty((String)agreementName)) {
            agreementName = contentResource.getParent().getName();
        }
        agreementOptions.setName(agreementName);
        agreementOptions.setSignatureFlow(AgreementCreationOptions.SignatureFlow.valueOf((String)signerResource.getWorkflowType()));
        if (StringUtils.isNotEmpty((String)postSigningURL)) {
            agreementOptions.setPostSigningUrl(postSigningURL);
        }
        agreementOptions.setRedirectDelay(1);
        List attachmentWrappers = formSubmitInfo.getFileAttachments();
        if (attachmentWrappers != null && !attachmentWrappers.isEmpty()) {
            ArrayList<Attachment> attachments = new ArrayList<Attachment>();
            for (FileAttachmentWrapper wrapper : attachmentWrappers) {
                Attachment attachment = new Attachment(wrapper.getFileName(), IOUtils.toByteArray((InputStream)wrapper.getInputStream()));
                attachments.add(attachment);
            }
            agreementOptions.setAttachments(attachments);
        }
        return agreementOptions;
    }

    private List<RecipientSetInfo> getSignerSetsFromDataXML(String data, SignerResource signersInfo) {
        ArrayList<RecipientSetInfo> signerSets = new ArrayList<RecipientSetInfo>();
        if (!StringUtils.isEmpty((String)data) && signersInfo != null) {
            Element signersNode = XMLUtils.getSignersDataXmlElement((Document)XMLUtils.strToDoc((String)data));
            NodeList children = signersNode.getChildNodes();
            int childCount = 0;
            for (int i = 0; i < children.getLength(); ++i) {
                Node child = children.item(i);
                if (child.getNodeType() != 1) continue;
                if (++childCount == 1) {
                    signerSets.add(this.createSignersSetFromDomNode((Element)children.item(i), (SignerInfo)signersInfo.getAllSignerInfo().get(childCount - 1), true));
                    continue;
                }
                signerSets.add(this.createSignersSetFromDomNode((Element)children.item(i), (SignerInfo)signersInfo.getAllSignerInfo().get(childCount - 1), false));
            }
        } else {
            log.error("Either data XML is null or empty or signers info is null\t");
        }
        return signerSets;
    }

    private RecipientSetInfo createSignersSetFromDomNode(Element signerNode, SignerInfo signerInfo, boolean firstSigner) {
        RecipientSetInfo recipientSet = new RecipientSetInfo();
        recipientSet.setRole(RecipientSetInfo.RecipientRole.SIGNER);
        ArrayList<RecipientInfo> recipients = new ArrayList<RecipientInfo>();
        if (signerInfo != null && signerNode != null) {
            RecipientInfo recipient = new RecipientInfo();
            String email = null;
            switch (signerInfo.getEmailSource()) {
                case FORM: {
                    email = signerNode.getElementsByTagName("email").item(0).getTextContent();
                    break;
                }
                case TYPED: {
                    email = signerInfo.getEmail();
                    break;
                }
                case USER_PROFILE: {
                    if (firstSigner) {
                        email = (String)this.currentUserService.getCurrentUserAsMap().get("email");
                        if (!StringUtils.isEmpty((String)email)) break;
                        log.error("Email retrieved from profile is empty or null");
                        break;
                    }
                    log.error("Pick from user profile option can only be used for first signer");
                    throw new GuideException("Pick from user profile option can only be used for first signer");
                }
            }
            recipient.setEmail(email);
            RecipientAuthenticationMethod recipientAuthenticationMethod = RecipientAuthenticationMethod.get((String)signerInfo.getSecurityOption());
            if (recipientAuthenticationMethod != null) {
                RecipientSecurityOption rso = new RecipientSecurityOption();
                rso.setAuthenticationMethod(recipientAuthenticationMethod);
                if (RecipientAuthenticationMethod.PHONE == recipientAuthenticationMethod) {
                    RecipientPhoneInfo[] phoneInfos = new RecipientPhoneInfo[]{new RecipientPhoneInfo()};
                    String countryCode = null;
                    String number = null;
                    NodeList phones = signerNode.getElementsByTagName("phone");
                    Element phoneNode = (Element)phones.item(0);
                    switch (signerInfo.getCountryCodeSource()) {
                        case FORM: {
                            countryCode = phoneNode.getElementsByTagName("countryCode").item(0).getTextContent();
                            break;
                        }
                        case TYPED: {
                            countryCode = signerInfo.getCountryCode();
                        }
                    }
                    switch (signerInfo.getPhoneSource()) {
                        case FORM: {
                            number = phoneNode.getElementsByTagName("number").item(0).getTextContent();
                            break;
                        }
                        case TYPED: {
                            number = signerInfo.getPhone();
                        }
                    }
                    phoneInfos[0].setCountryCode(countryCode);
                    phoneInfos[0].setPhoneNumber(number);
                    rso.setPhoneInfos(phoneInfos);
                }
                recipient.setSecurityOptions(rso);
            }
            recipients.add(recipient);
        }
        recipientSet.setMemberInfos(recipients);
        return recipientSet;
    }

    private List<RecipientSetInfo> getSignerSetsFromDataJson(String data, SignerResource signersInfo) throws JSONException {
        ArrayList<RecipientSetInfo> signerSets = new ArrayList<RecipientSetInfo>();
        if (!StringUtils.isEmpty((String)data) && signersInfo != null) {
            JSONObject dataJson = new JSONObject(data);
            JSONObject signersJson = dataJson.getJSONObject("afData").getJSONObject("afSubmissionInfo").getJSONObject("signers");
            Iterator childItr = signersJson.keys();
            int childCount = 0;
            while (childItr.hasNext()) {
                JSONObject child = signersJson.getJSONObject((String)childItr.next());
                if (++childCount == 1) {
                    signerSets.add(this.createSignersSetFromJson(child, (SignerInfo)signersInfo.getAllSignerInfo().get(childCount - 1), true));
                    continue;
                }
                signerSets.add(this.createSignersSetFromJson(child, (SignerInfo)signersInfo.getAllSignerInfo().get(childCount - 1), false));
            }
        } else {
            log.error("Either data Json is null or empty or signers info is null\t");
        }
        return signerSets;
    }

    private RecipientSetInfo createSignersSetFromJson(JSONObject signerJson, SignerInfo signerInfo, boolean firstSigner) throws JSONException {
        RecipientSetInfo recipientSet = new RecipientSetInfo();
        recipientSet.setRole(RecipientSetInfo.RecipientRole.SIGNER);
        ArrayList<RecipientInfo> recipients = new ArrayList<RecipientInfo>();
        if (signerInfo != null && signerJson != null) {
            RecipientInfo recipient = new RecipientInfo();
            String email = null;
            switch (signerInfo.getEmailSource()) {
                case FORM: {
                    email = signerJson.getString("email");
                    break;
                }
                case TYPED: {
                    email = signerInfo.getEmail();
                    break;
                }
                case USER_PROFILE: {
                    if (firstSigner) {
                        email = (String)this.currentUserService.getCurrentUserAsMap().get("email");
                        if (!StringUtils.isEmpty((String)email)) break;
                        log.error("Email retrieved from profile is empty or null");
                        break;
                    }
                    log.error("Pick from user profile option can only be used for first signer");
                    throw new GuideException("Pick from user profile option can only be used for first signer");
                }
            }
            recipient.setEmail(email);
            RecipientAuthenticationMethod recipientAuthenticationMethod = RecipientAuthenticationMethod.get((String)signerInfo.getSecurityOption());
            if (recipientAuthenticationMethod != null) {
                RecipientSecurityOption rso = new RecipientSecurityOption();
                rso.setAuthenticationMethod(recipientAuthenticationMethod);
                if (RecipientAuthenticationMethod.PHONE == recipientAuthenticationMethod) {
                    RecipientPhoneInfo[] phoneInfos = new RecipientPhoneInfo[]{new RecipientPhoneInfo()};
                    String countryCode = null;
                    String number = null;
                    JSONObject phoneJson = signerJson.getJSONObject("phone");
                    switch (signerInfo.getCountryCodeSource()) {
                        case FORM: {
                            countryCode = phoneJson.getString("countryCode");
                            break;
                        }
                        case TYPED: {
                            countryCode = signerInfo.getCountryCode();
                        }
                    }
                    switch (signerInfo.getPhoneSource()) {
                        case FORM: {
                            number = phoneJson.getString("number");
                            break;
                        }
                        case TYPED: {
                            number = signerInfo.getPhone();
                        }
                    }
                    phoneInfos[0].setCountryCode(countryCode);
                    phoneInfos[0].setPhoneNumber(number);
                    rso.setPhoneInfos(phoneInfos);
                }
                recipient.setSecurityOptions(rso);
            }
            recipients.add(recipient);
        }
        recipientSet.setMemberInfos(recipients);
        return recipientSet;
    }

    public boolean cancelAgreement(String agreementId, Resource guideContainerResource) throws GuideException {
        boolean deleted = false;
        if (StringUtils.isNotEmpty((String)agreementId) && guideContainerResource != null) {
            SignerResource signerResource = (SignerResource)guideContainerResource.getChild("signerInfo").adaptTo(SignerResource.class);
            String signConfigPath = signerResource.getSignConfigPath();
            AgreementCancellationOptions options = new AgreementCancellationOptions();
            options.setNotifySigner(true);
            try {
                String status = this.adobeSignService.cancelAgreement(agreementId, signConfigPath, options);
                if (status.equals("CANCELLED")) {
                    deleted = true;
                }
            }
            catch (AdobeSignServiceException e) {
                throw new GuideException((Exception)e);
            }
        }
        return deleted;
    }

    protected void bindLcFormsService(LCFormsService lCFormsService) {
        this.lcFormsService = lCFormsService;
    }

    protected void unbindLcFormsService(LCFormsService lCFormsService) {
        if (this.lcFormsService == lCFormsService) {
            this.lcFormsService = null;
        }
    }

    protected void bindResourceResolverHelper(ResourceResolverHelper resourceResolverHelper) {
        this.resourceResolverHelper = resourceResolverHelper;
    }

    protected void unbindResourceResolverHelper(ResourceResolverHelper resourceResolverHelper) {
        if (this.resourceResolverHelper == resourceResolverHelper) {
            this.resourceResolverHelper = null;
        }
    }

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

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

    protected void bindAdobeSignSatusHandler(AdobeSignStatusHandler adobeSignStatusHandler) {
        this.adobeSignSatusHandler = adobeSignStatusHandler;
    }

    protected void unbindAdobeSignSatusHandler(AdobeSignStatusHandler adobeSignStatusHandler) {
        if (this.adobeSignSatusHandler == adobeSignStatusHandler) {
            this.adobeSignSatusHandler = null;
        }
    }

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

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

    protected void bindAdobeSignService(AdobeSignService adobeSignService) {
        this.adobeSignService = adobeSignService;
    }

    protected void unbindAdobeSignService(AdobeSignService adobeSignService) {
        if (this.adobeSignService == adobeSignService) {
            this.adobeSignService = null;
        }
    }

    protected void bindCurrentUserService(CurrentUserService currentUserService) {
        this.currentUserService = currentUserService;
    }

    protected void unbindCurrentUserService(CurrentUserService currentUserService) {
        if (this.currentUserService == currentUserService) {
            this.currentUserService = null;
        }
    }

}