FMCRUDServiceImpl.java 44.9 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 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.aemds.guide.utils.GuideThemeUtils
 *  com.adobe.granite.asset.api.Asset
 *  com.adobe.granite.asset.api.AssetManager
 *  com.adobe.granite.asset.api.AssetRelation
 *  com.day.cq.replication.ReplicationStatus
 *  com.day.cq.tagging.Tag
 *  com.day.cq.tagging.TagManager
 *  javax.jcr.Binary
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.ValueFactory
 *  org.apache.commons.lang.StringUtils
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferenceCardinality
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.ModifiableValueMap
 *  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.JSONArray
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.aem.formsndocuments.service.impl;

import com.adobe.aem.formsndocuments.preprocess.DeletePreprocessor;
import com.adobe.aem.formsndocuments.publish.PublishService;
import com.adobe.aem.formsndocuments.service.FMCRUDService;
import com.adobe.aem.formsndocuments.util.FMConstants;
import com.adobe.aem.formsndocuments.util.FMUtils;
import com.adobe.aem.formsndocuments.util.ThumbnailUtil;
import com.adobe.aemds.guide.utils.GuideThemeUtils;
import com.adobe.aemforms.fm.exception.FormsMgrException;
import com.adobe.granite.asset.api.Asset;
import com.adobe.granite.asset.api.AssetManager;
import com.adobe.granite.asset.api.AssetRelation;
import com.day.cq.replication.ReplicationStatus;
import com.day.cq.tagging.Tag;
import com.day.cq.tagging.TagManager;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
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.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.ModifiableValueMap;
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.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate=1)
@Service(value={FMCRUDService.class})
public class FMCRUDServiceImpl
implements FMCRUDService {
    private final Logger log = LoggerFactory.getLogger(FMCRUDServiceImpl.class);
    @Reference(referenceInterface=DeletePreprocessor.class, cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)
    private final List<DeletePreprocessor> deletePreprocessors = new CopyOnWriteArrayList<DeletePreprocessor>();
    @Reference(referenceInterface=PublishService.class)
    private PublishService publishService;
    @Reference(referenceInterface=ResourceResolverFactory.class)
    ResourceResolverFactory resourceResolverFactory;

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void preprocessDelete(Session session, String assetPath) throws FormsMgrException {
        HashMap preprocessParams = new HashMap();
        this.log.info("Invoking delete preprocessors for asset:" + assetPath);
        for (DeletePreprocessor preprocessor : this.deletePreprocessors) {
            this.log.debug("Invoking preprocessor:" + preprocessor.getClass().getName());
            try {
                preprocessor.preprocess(session, assetPath, preprocessParams);
            }
            catch (Exception e) {
                this.log.warn("Exception in delete preprocess. Cause: " + e.getMessage(), (Throwable)e);
            }
        }
        ResourceResolver resourceResolver = null;
        try {
            ReplicationStatus replicationStatus;
            resourceResolver = FMUtils.getResourceResolver(this.resourceResolverFactory, session);
            Resource resource = resourceResolver.getResource(assetPath);
            if (resource != null && ((replicationStatus = (ReplicationStatus)resource.adaptTo(ReplicationStatus.class)).isActivated() || replicationStatus.isDelivered())) {
                this.log.info("Deactivating asset: " + assetPath);
                this.publishService.deactivate(session, Arrays.asList(assetPath));
            }
        }
        finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
    }

    @Override
    public void deleteCRXResource(Session session, String resourcePath) throws FormsMgrException {
        try {
            if (session == null) {
                Object[] args = new Object[]{"session", session};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            if (!session.nodeExists(resourcePath)) {
                Object[] args = new Object[]{resourcePath};
                throw new FormsMgrException("AEM-FMG-700-002", args);
            }
            FMConstants.CoreAssetType assetType = FMUtils.getAssetType(session, resourcePath);
            if (FMUtils.isForm(assetType) || assetType == FMConstants.CoreAssetType.GUIDE || assetType == FMConstants.CoreAssetType.AFFRAGMENT || assetType == FMConstants.CoreAssetType.FORMSET || assetType == FMConstants.CoreAssetType.RESOURCE || assetType == FMConstants.CoreAssetType.ADAPTIVEDOCUMENT || assetType == FMConstants.CoreAssetType.THEME) {
                this.preprocessDelete(session, resourcePath);
                this.deleteAsset(session, resourcePath, assetType);
            } else if (assetType == FMConstants.CoreAssetType.FOLDER) {
                List<String> childAssets = this.getAllAssets(session, resourcePath);
                for (String childAssetPath : childAssets) {
                    if (FMUtils.isFolder(session, childAssetPath) || FMUtils.isApplication(session, childAssetPath)) continue;
                    this.preprocessDelete(session, childAssetPath);
                }
                this.deleteAsset(session, resourcePath, assetType);
            }
        }
        catch (Exception e) {
            throw FMUtils.getFormsMgrException(e);
        }
    }

    private void deleteAsset(Session session, String resourcePath, FMConstants.CoreAssetType assetType) throws FormsMgrException {
        try {
            String clientlibPath;
            Node resourceNode = session.getNode(resourcePath);
            if (assetType == FMConstants.CoreAssetType.GUIDE || assetType == FMConstants.CoreAssetType.FOLDER || assetType == FMConstants.CoreAssetType.AFFRAGMENT || assetType == FMConstants.CoreAssetType.ADAPTIVEDOCUMENT) {
                String cqPagePath = FMUtils.getPagePathFromAsset(resourcePath);
                if (session.nodeExists(cqPagePath)) {
                    session.getNode(cqPagePath).remove();
                }
            } else if (assetType == FMConstants.CoreAssetType.THEME && session.nodeExists(clientlibPath = FMUtils.getClientlibPath(resourceNode))) {
                session.getNode(clientlibPath).remove();
            }
            resourceNode.remove();
            this.log.info((Object)((Object)assetType) + " removed successfully from path : " + resourcePath);
            session.save();
        }
        catch (Exception e) {
            throw FMUtils.getFormsMgrException(e);
        }
    }

    public List<String> getAllAssets(Session session, String folderPath) throws FormsMgrException {
        ArrayList<String> assetList = new ArrayList<String>();
        this.populateAllAssets(session, assetList, folderPath);
        return assetList;
    }

    private void populateAllAssets(Session session, List<String> assetList, String folderPath) throws FormsMgrException {
        block8 : {
            try {
                if (folderPath != null && !folderPath.isEmpty()) {
                    NodeIterator iter;
                    Node rootNode;
                    if (session.nodeExists(folderPath) && (iter = (rootNode = session.getNode(folderPath)).getNodes()) != null) {
                        int i = 0;
                        while ((long)i < iter.getSize()) {
                            Node node = iter.nextNode();
                            String nodePath = node.getPath();
                            FMConstants.CoreAssetType assetType = FMUtils.getAssetType(session, nodePath);
                            if (assetType == FMConstants.CoreAssetType.FOLDER) {
                                assetList.add(nodePath);
                                this.populateAllAssets(session, assetList, nodePath);
                            } else if (assetType == FMConstants.CoreAssetType.GUIDE || assetType == FMConstants.CoreAssetType.FORM || assetType == FMConstants.CoreAssetType.PDFFORM || assetType == FMConstants.CoreAssetType.PRINTFORM || assetType == FMConstants.CoreAssetType.RESOURCE) {
                                assetList.add(nodePath);
                            }
                            ++i;
                        }
                    }
                    break block8;
                }
                throw new FormsMgrException("Invalid Asset path:" + folderPath);
            }
            catch (Exception e) {
                throw FMUtils.getFormsMgrException(e);
            }
        }
    }

    protected void bindDeletePreprocessors(DeletePreprocessor deletePreprocessor) {
        this.deletePreprocessors.add(deletePreprocessor);
    }

    protected void unbindDeletePreprocessors(DeletePreprocessor deletePreprocessor) {
        this.deletePreprocessors.remove(deletePreprocessor);
    }

    @Override
    public Asset createAsset(ResourceResolver resolver, JSONObject assetJSON) throws FormsMgrException {
        try {
            Iterator jsonIter;
            String propertyName;
            String propertyValue;
            AssetManager assetManager = (AssetManager)resolver.adaptTo(AssetManager.class);
            Asset asset = assetManager.createAsset(assetJSON.getString("path"));
            String type = assetJSON.getString("assetType");
            ValueMap vm = (ValueMap)asset.adaptTo(ValueMap.class);
            if (assetJSON.has("assetJcrProperties")) {
                JSONObject jcrPropertyJSON = assetJSON.getJSONObject("assetJcrProperties");
                jsonIter = jcrPropertyJSON.keys();
                while (jsonIter.hasNext()) {
                    propertyName = (String)jsonIter.next();
                    propertyValue = jcrPropertyJSON.getString(propertyName);
                    vm.put((Object)propertyName, (Object)propertyValue);
                }
            }
            vm.put((Object)type, (Object)"1");
            JSONObject metadataPropertyJSON = assetJSON.getJSONObject("metadataProperties");
            Resource metadataResource = resolver.getResource((Resource)asset, "jcr:content/metadata");
            ModifiableValueMap mvm = (ModifiableValueMap)metadataResource.adaptTo(ModifiableValueMap.class);
            jsonIter = metadataPropertyJSON.keys();
            while (jsonIter.hasNext()) {
                propertyName = (String)jsonIter.next();
                propertyValue = metadataPropertyJSON.getString(propertyName);
                if (propertyName.equals("cq:tags")) {
                    if (JSONArray.class.isAssignableFrom(metadataPropertyJSON.get("cq:tags").getClass())) {
                        JSONArray jsonArray = metadataPropertyJSON.getJSONArray("cq:tags");
                        if (jsonArray == null) continue;
                        int arrLen = jsonArray.length();
                        String[] tags = new String[arrLen];
                        for (int i = 0; i < arrLen; ++i) {
                            tags[i] = jsonArray.optString(i);
                        }
                        TagManager tagManager = (TagManager)resolver.adaptTo(TagManager.class);
                        if (tagManager == null || tags == null) continue;
                        ArrayList<Tag> processedTags = new ArrayList<Tag>();
                        for (String tagId : tags) {
                            Tag tag = tagManager.resolve(tagId);
                            if (tag == null) {
                                tag = tagManager.createTagByTitle(tagId, Locale.ENGLISH);
                            }
                            processedTags.add(tag);
                        }
                        tagManager.setTags(metadataResource, processedTags.toArray((T[])new Tag[tags.length]), false);
                        continue;
                    }
                    mvm.put((Object)propertyName, (Object)propertyValue.split(","));
                    continue;
                }
                mvm.put((Object)propertyName, (Object)propertyValue.toString());
            }
            if (!"formset".equals(type)) {
                ((Session)resolver.adaptTo(Session.class)).getNode(asset.getPath() + "/" + "jcr:content" + "/" + "related").remove();
            }
            return asset;
        }
        catch (JSONException e) {
            throw new FormsMgrException("AEM-FMG-800-005");
        }
        catch (Exception e) {
            throw new FormsMgrException(e);
        }
    }

    @Override
    public void createFormset(ResourceResolver resolver, JSONObject formsetJSON) throws FormsMgrException, IOException {
        Asset asset = this.createUpdateFormset(resolver, formsetJSON);
        this.generateFormsetThumbnail(resolver, asset.getPath());
    }

    @Override
    public void updateFormset(ResourceResolver resolver, JSONObject formsetJSON) throws FormsMgrException {
        this.createUpdateFormset(resolver, formsetJSON);
    }

    @Override
    public void generateFormsetThumbnail(ResourceResolver resolver, String formsetPath) throws FormsMgrException, IOException {
        if (formsetPath != null && !formsetPath.isEmpty()) {
            Asset asset = (Asset)resolver.getResource(formsetPath).adaptTo(Asset.class);
            ThumbnailUtil.addThumbnail(resolver.getResource(formsetPath), this.getMembers(asset, "forms"));
            resolver.commit();
        }
    }

    @Override
    public String createFragmentFromPanel(ResourceResolver resolver, JSONObject params) throws FormsMgrException {
        try {
            String inputFormCQPagePath;
            String inputFormAssetsNodePath;
            Node metadataNode;
            String errorMsg = new String();
            if (!this.isValidFragmentInputParams(params, errorMsg)) {
                this.log.error(errorMsg);
                throw new FormsMgrException("AEM-FMG-700-001");
            }
            Session session = (Session)resolver.adaptTo(Session.class);
            JSONObject assetJson = new JSONObject();
            JSONObject metadataProperties = new JSONObject(params.getString("metadataProperties"));
            assetJson.put("metadataProperties", (Object)metadataProperties);
            String panelPath = params.getString("panelPath");
            String fragName = params.getString("name");
            String inputTargetPath = params.has("targetPath") ? params.getString("targetPath") : null;
            String targetFragPath = this.getTargetFragmentPath(resolver, panelPath, inputTargetPath, fragName);
            if (metadataProperties.has("cq:tags")) {
                String tags = metadataProperties.getString("cq:tags");
                if (tags != null && !tags.isEmpty()) {
                    metadataProperties.put("cq:tags", (Object)StringUtils.split((String)tags, (String)","));
                } else {
                    metadataProperties.remove("cq:tags");
                }
            }
            FMConstants.FORM_MODEL formModel = FMConstants.FORM_MODEL.NONE;
            String inputFormModelStr = metadataProperties.getString("formmodel");
            if ("formtemplates".equals(inputFormModelStr)) {
                formModel = FMConstants.FORM_MODEL.FORM_TEMPLATE;
            } else if ("xmlschema".equals(inputFormModelStr)) {
                formModel = FMConstants.FORM_MODEL.XML_SCHEMA;
            } else if ("none".equals(inputFormModelStr)) {
                metadataProperties.remove("fragmentModelRoot");
            }
            FMUtils.prepareJsonToCreateDAMAsset(resolver, assetJson, FMConstants.CoreAssetType.AFFRAGMENT, targetFragPath, fragName);
            this.createAsset(resolver, assetJson);
            String createdFragmentAssetPath = assetJson.getString("path");
            Node cqPageNode = FMUtils.createCQPageNode(resolver, assetJson, FMConstants.CoreAssetType.AFFRAGMENT, formModel, null);
            String fragmentCQPagePath = cqPageNode.getPath();
            JSONObject panelJson = new JSONObject(params.getString("panelJson"));
            String fragmentRootPanelPath = fragmentCQPagePath + "/" + "jcr:content/guideContainer" + "/" + "rootPanel";
            FMUtils.JsonToJcrNode(session.getNode(fragmentRootPanelPath + "/" + "items"), panelJson.getJSONObject("items"));
            AssetManager assetManager = (AssetManager)resolver.adaptTo(AssetManager.class);
            Resource resource = FMUtils.getClosestNodeUpInHierarchy(resolver, panelPath, "jcr:primaryType", "cq:Page", false);
            String string = inputFormCQPagePath = resource == null ? null : resource.getPath();
            if (inputFormCQPagePath != null && session.nodeExists(inputFormAssetsNodePath = inputFormCQPagePath + "/" + "jcr:content/guideContainer/assets")) {
                String fragmentAssetNodePath = fragmentCQPagePath + "/" + "jcr:content/guideContainer/assets";
                assetManager.copyAsset(inputFormAssetsNodePath, fragmentAssetNodePath);
                String fragmentDictionaryPath = fragmentAssetNodePath + "/" + "dictionary";
                if (session.nodeExists(fragmentDictionaryPath)) {
                    Node dictionaryNode = session.getNode(fragmentDictionaryPath);
                    NodeIterator iter = dictionaryNode.getNodes();
                    long iteratorsize = iter.getSize();
                    for (long i = 0; i < iteratorsize; ++i) {
                        iter.nextNode().setProperty("sling:basename", fragmentDictionaryPath);
                    }
                }
            }
            this.addImagesInCreatedFragment(assetManager, panelJson, panelPath, fragmentRootPanelPath);
            if (formModel == FMConstants.FORM_MODEL.XML_SCHEMA && "/assets/xsdRef.xsd".equals(metadataProperties.getString("xsdRef")) && (metadataNode = FMUtils.getMetadataNode(session, inputFormCQPagePath, false)) != null && metadataNode.hasProperty("xsdRef")) {
                String xsdRefVal = metadataNode.getProperty("xsdRef").getString();
                Node fragMetadataNode = FMUtils.getMetadataNode(session, createdFragmentAssetPath, false);
                fragMetadataNode.setProperty("xsdRef", xsdRefVal);
            }
            resolver.commit();
            return createdFragmentAssetPath;
        }
        catch (FormsMgrException e) {
            throw e;
        }
        catch (Exception e) {
            this.log.error("Adaptive Form Fragment creation failed ", (Throwable)e);
            throw new FormsMgrException("AEM-FMG-800-007");
        }
    }

    private void addImagesInCreatedFragment(AssetManager assetManager, JSONObject panelJson, String srcPanelPath, String targetFragmentPath) throws FormsMgrException {
        Iterator keys = panelJson.keys();
        try {
            while (keys.hasNext()) {
                String key = (String)keys.next();
                Object property = panelJson.get(key);
                if (!JSONObject.class.isAssignableFrom(property.getClass())) continue;
                JSONObject jsonData = (JSONObject)property;
                if (jsonData.has("jcr:primaryType") && jsonData.getString("jcr:primaryType").equals("nt:file")) {
                    assetManager.copyAsset(srcPanelPath + "/" + key, targetFragmentPath + "/" + key);
                    continue;
                }
                this.addImagesInCreatedFragment(assetManager, jsonData, srcPanelPath + "/" + key, targetFragmentPath + "/" + key);
            }
        }
        catch (JSONException e) {
            this.log.error("JSON Exception while parsing panelJson in updatePanelJsonToCreateFragment() ", (Throwable)e);
            throw new FormsMgrException("AEM-FMG-800-007");
        }
    }

    private boolean isValidFragmentInputParams(JSONObject params, String errorMsg) throws FormsMgrException {
        boolean returnVal = false;
        errorMsg = "Invalid Parameter : ";
        try {
            if (!params.has("metadataProperties")) {
                errorMsg = errorMsg.concat("fragment metadata properties missing");
            } else if (!params.has("panelPath") || params.getString("panelPath").isEmpty()) {
                errorMsg = errorMsg.concat("panel path missing");
            } else if (!params.has("panelJson")) {
                errorMsg = errorMsg.concat("panel json missing");
            } else if (!params.has("name") || params.getString("name").isEmpty()) {
                errorMsg = errorMsg.concat("fragment name missing");
            } else {
                JSONObject metadataProperties = new JSONObject(params.getString("metadataProperties"));
                if (!metadataProperties.has("formmodel") || metadataProperties.getString("formmodel").isEmpty()) {
                    errorMsg = errorMsg.concat("fragment FORM MODEL missing");
                } else {
                    returnVal = true;
                }
            }
        }
        catch (JSONException e) {
            this.log.error("JSON Exception in isValidFragmentInputParams() while validating input params for Fragment creation from existing panel ", (Throwable)e);
            throw new FormsMgrException("AEM-FMG-800-007");
        }
        return returnVal;
    }

    @Override
    public void cleanUpForm(Session session, String formPath) throws FormsMgrException {
        block9 : {
            try {
                if (session == null) {
                    Object[] args = new Object[]{"session", session};
                    throw new FormsMgrException("AEM-FMG-700-001", args);
                }
                if (session.nodeExists(formPath)) {
                    Node formNode = session.getNode(formPath);
                    Node metaDataNode = FMUtils.getMetadataNode(formNode, false);
                    if (metaDataNode != null) {
                        if (metaDataNode.hasProperty("underReview")) {
                            this.cleanUpReviewInfo(session, formPath);
                        }
                        if (metaDataNode.hasProperty("targetEnabled")) {
                            this.cleanUpABTestingInfo(session, formPath);
                        }
                        if (metaDataNode.hasProperty("analyticsEnabled")) {
                            this.cleanUpAnalyticsInfo(session, formPath);
                        }
                    }
                    break block9;
                }
                throw new FormsMgrException("AEM-FMG-700-002", new String[]{formPath});
            }
            catch (FormsMgrException e) {
                throw e;
            }
            catch (RepositoryException e) {
                throw new FormsMgrException((Throwable)e);
            }
        }
    }

    @Override
    public void cleanUpReviewInfo(Session session, String formPath) throws FormsMgrException {
        try {
            if (session == null) {
                Object[] args = new Object[]{"session", session};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            Node formNode = session.getNode(formPath);
            Node metaDataNode = FMUtils.getMetadataNode(formNode, false);
            if (metaDataNode != null && metaDataNode.hasProperty("reviewId")) {
                metaDataNode.setProperty("reviewId", (Value)null);
                metaDataNode.setProperty("reviewInitiator", (Value)null);
                metaDataNode.setProperty("underReview", (Value)null);
                String reviewContainerPath = formNode.getPath() + "/" + "jcr:content" + "/" + "reviewcontainer";
                Node reviewContainerNode = session.getNode(reviewContainerPath);
                reviewContainerNode.remove();
            }
        }
        catch (Exception e) {
            Object[] args = new Object[]{"Review", formPath};
            throw new FormsMgrException("AEM-FMG-700-025", args);
        }
    }

    @Override
    public void cleanUpABTestingInfo(Session session, String formPath) throws FormsMgrException {
        this.cleanUpFormABTestingInfo(session, formPath);
        this.cleanUpFormPageABTestingInfo(session, FMUtils.getPagePathFromAsset(formPath));
    }

    @Override
    public void cleanUpFormABTestingInfo(Session session, String formPath) throws FormsMgrException {
        try {
            if (session == null) {
                Object[] args = new Object[]{"session", session};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            if (session.nodeExists(formPath)) {
                Node formNode = session.getNode(formPath);
                Node metaDataNode = FMUtils.getMetadataNode(formNode, false);
                if (metaDataNode != null) {
                    metaDataNode.setProperty("targetEnabled", (Value)null);
                    metaDataNode.setProperty("targetCampaignName", (Value)null);
                    metaDataNode.setProperty("targetCampaignObj", (Value)null);
                    metaDataNode.setProperty("targetAudience", (Value)null);
                    metaDataNode.setProperty("targetPercentage", (Value)null);
                    metaDataNode.setProperty("targetUrlDomains", (Value)null);
                    metaDataNode.setProperty("targetProfile", (Value)null);
                    metaDataNode.setProperty("targetStartDate", (Value)null);
                    metaDataNode.setProperty("targetLastModified", (Value)null);
                } else {
                    this.log.error("Unable to retrieve metadata node for the form : " + formPath);
                }
            } else {
                this.log.error("Unable to retrieve node at path : " + formPath);
            }
        }
        catch (Exception e) {
            Object[] args = new Object[]{"A/B Testing", formPath};
            throw new FormsMgrException("AEM-FMG-700-025", args);
        }
    }

    @Override
    public void cleanUpFormPageABTestingInfo(Session session, String pagePath) throws FormsMgrException {
        try {
            if (session == null) {
                Object[] args = new Object[]{"session", session};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            if (session.nodeExists(pagePath)) {
                Node pageNode = session.getNode(pagePath);
                Node contentNode = FMUtils.getContentNode(pageNode, false);
                if (contentNode != null && contentNode.hasProperty("targetEnabled")) {
                    contentNode.setProperty("targetEnabled", (Value)null);
                    if (contentNode.hasNode("guideContainer2")) {
                        Node guideContainerNode2 = contentNode.getNode("guideContainer2");
                        guideContainerNode2.remove();
                    }
                } else {
                    this.log.error("Unable to retrieve JCR content node for page path : " + pagePath);
                }
            } else {
                this.log.error("Unable to retrieve node at path : " + pagePath);
            }
        }
        catch (Exception e) {
            Object[] args = new Object[]{"A/B Testing", FMUtils.getAssetPathFromPage(pagePath)};
            throw new FormsMgrException("AEM-FMG-700-025", args);
        }
    }

    @Override
    public void cleanUpAnalyticsInfo(Session session, String formPath) throws FormsMgrException {
        try {
            if (session == null) {
                Object[] args = new Object[]{"session", session};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            if (session.nodeExists(formPath)) {
                Node metaDataNode;
                Node formNode = session.getNode(formPath);
                Node analyticsDataNode = FMUtils.getAnalyticsDataNode(formNode, false);
                if (analyticsDataNode != null) {
                    analyticsDataNode.remove();
                }
                if ((metaDataNode = FMUtils.getMetadataNode(formNode, false)) != null) {
                    metaDataNode.setProperty("analyticsEnabled", (Value)null);
                } else {
                    this.log.error("Unable to retrieve metadata node for the form : " + formPath);
                }
            } else {
                this.log.error("Unable to retrieve node at path : " + formPath);
            }
        }
        catch (Exception e) {
            Object[] args = new Object[]{"Analytics", formPath};
            throw new FormsMgrException("AEM-FMG-700-025", args);
        }
    }

    private Iterator<Asset> getMembers(Asset asset, String relationName) {
        final Iterator members = asset.listRelated(relationName);
        return new Iterator<Asset>(){

            @Override
            public boolean hasNext() {
                return members.hasNext();
            }

            @Override
            public Asset next() {
                return (Asset)((Asset)members.next()).adaptTo(Asset.class);
            }

            @Override
            public void remove() {
                members.remove();
            }
        };
    }

    private Asset createUpdateFormset(ResourceResolver resolver, JSONObject formsetJSON) throws FormsMgrException {
        try {
            Asset asset;
            if (resolver == null) {
                this.log.error("resolver parameter in createUpdateFormset() function is null");
                Object[] args = new Object[]{"resolver", resolver};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            if (formsetJSON == null) {
                this.log.error("formsetJSON parameter in createUpdateFormset() function is null");
                Object[] args = new Object[]{"formsetJSON", formsetJSON};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            String errorMsg = new String();
            Session session = (Session)resolver.adaptTo(Session.class);
            if (!this.isValidFormsetInputParams(session, formsetJSON, errorMsg)) {
                this.log.error(errorMsg);
                Object[] args = new Object[]{"errorMsg", errorMsg};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            formsetJSON.put("assetType", (Object)"formset");
            JSONObject jcrContentPropertyJSON = new JSONObject();
            jcrContentPropertyJSON.put("sling:resourceType", (Object)"fd/fm/formset/render");
            formsetJSON.put("assetJcrProperties", (Object)jcrContentPropertyJSON);
            if (formsetJSON.has("metadataProperties")) {
                asset = this.createAsset(resolver, formsetJSON);
            } else {
                AssetManager assetManager = (AssetManager)resolver.adaptTo(AssetManager.class);
                asset = assetManager.getAsset(formsetJSON.getString("path"));
                asset.removeRelation("forms");
            }
            ValueMap vm = (ValueMap)asset.adaptTo(ValueMap.class);
            vm.put((Object)"jcr:lastModified", (Object)Calendar.getInstance());
            if (formsetJSON.has("formsetForms")) {
                JSONArray formReferenceJSONArray = formsetJSON.getJSONArray("formsetForms");
                for (int i = 0; i < formReferenceJSONArray.length(); ++i) {
                    String formPath = null;
                    JSONObject formReferenceJSON = formReferenceJSONArray.getJSONObject(i);
                    HashMap<String, String> props = new HashMap<String, String>();
                    Iterator jsonIterator = formReferenceJSON.keys();
                    while (jsonIterator.hasNext()) {
                        String propertyName = (String)jsonIterator.next();
                        String propertyValue = formReferenceJSON.getString(propertyName);
                        if (propertyName.equals("formPath")) {
                            formPath = formReferenceJSON.getString("formPath");
                            continue;
                        }
                        props.put(propertyName, propertyValue);
                    }
                    asset.addRelation("forms", formPath, props);
                }
                resolver.commit();
                return asset;
            }
            throw new FormsMgrException("AEM-FMG-800-005");
        }
        catch (Exception e) {
            throw new FormsMgrException("AEM-FMG-800-006");
        }
    }

    private boolean isValidFormsetInputParams(Session session, JSONObject params, String errorMsg) throws FormsMgrException, RepositoryException {
        boolean returnVal = false;
        errorMsg = "Invalid Parameter : ";
        try {
            if (session == null) {
                this.log.error("session parameter in isValidThemeInputParams() function is null");
                Object[] args = new Object[]{"session", session};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            if (!params.has("path") || params.getString("path").isEmpty()) {
                errorMsg = errorMsg.concat("Formset path is missing");
            } else if (params.has("metadataProperties")) {
                String formsetPath = params.getString("path");
                int index = formsetPath.lastIndexOf("/");
                String nodeName = formsetPath.substring(index + 1);
                if (session.nodeExists(formsetPath)) {
                    this.log.error("Error as resource " + nodeName + " already exist at destination" + formsetPath);
                    Object[] args = new Object[]{nodeName, formsetPath};
                    throw new FormsMgrException("AEM-FMG-900-002", args);
                }
            }
            returnVal = true;
        }
        catch (JSONException e) {
            this.log.error("JSON Exception in isValidThemeInputParams() while validating input params for theme creation ", (Throwable)e);
            throw new FormsMgrException("AEM-FMG-800-009");
        }
        return returnVal;
    }

    private String getTargetFragmentPath(ResourceResolver resolver, String panelPath, String targetPath, String fragName) throws FormsMgrException {
        try {
            Session session;
            if (targetPath == null || targetPath.isEmpty()) {
                Resource resource = FMUtils.getClosestNodeUpInHierarchy(resolver, panelPath, "jcr:primaryType", "cq:Page", false);
                if (resource == null) {
                    throw new FormsMgrException("AEM-FMG-700-001");
                }
                targetPath = resource.getPath();
                String assetPath = FMUtils.getAssetPathFromPage(targetPath);
                targetPath = assetPath.substring(0, assetPath.lastIndexOf("/"));
            }
            if ((session = (Session)resolver.adaptTo(Session.class)).nodeExists(targetPath + "/" + fragName)) {
                Object[] args = new Object[]{fragName, targetPath};
                throw new FormsMgrException("AEM-FMG-900-002", args);
            }
            return targetPath;
        }
        catch (RepositoryException e) {
            this.log.error("error while deducing target path to save Fragment ", (Throwable)e);
            throw new FormsMgrException("AEM-FMG-800-007");
        }
    }

    @Override
    public void createTheme(ResourceResolver resolver, JSONObject themeJson) throws FormsMgrException {
        try {
            if (resolver == null) {
                this.log.error("resolver parameter in createTheme() function is null");
                Object[] args = new Object[]{"resolver", resolver};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            if (themeJson == null) {
                this.log.error("themeJson parameter in createTheme() function is null");
                Object[] args = new Object[]{"themeJson", themeJson};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            String errorMsg = new String();
            Session session = (Session)resolver.adaptTo(Session.class);
            if (!this.isValidThemeInputParams(session, themeJson, errorMsg)) {
                this.log.error(errorMsg);
                Object[] args = new Object[]{"errorMsg", errorMsg};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            themeJson.put("assetType", (Object)"theme");
            JSONObject jcrContentPropertyJSON = new JSONObject();
            jcrContentPropertyJSON.put("sling:resourceType", (Object)"fd/fm/theme/render");
            themeJson.put("assetJcrProperties", (Object)jcrContentPropertyJSON);
            Asset themeAsset = this.createAsset(resolver, themeJson);
            AssetManager assetManager = (AssetManager)resolver.adaptTo(AssetManager.class);
            String defaultAFPath = GuideThemeUtils.getConfiguredFormPagePath((ResourceResolver)resolver, (String)themeAsset.getChild("jcr:content").getPath());
            String afRenditionNodePath = defaultAFPath + "/" + "jcr:content/renditions";
            if (session.nodeExists(afRenditionNodePath)) {
                assetManager.copyAsset(afRenditionNodePath, themeAsset.getPath() + "/" + "jcr:content/renditions");
            }
            Node themeNode = session.getNode(themeAsset.getPath());
            Node renditionNode = FMUtils.getRenditionNode(themeNode, true);
            if (session.nodeExists("/libs/fd/af/themes/initialJSON")) {
                String destPath = renditionNode.getPath() + "/" + "original";
                assetManager.copyAsset("/libs/fd/af/themes/initialJSON", destPath);
                Node contentNode = session.getNode(destPath + "/" + "jcr:content");
                contentNode.setProperty("jcr:lastModified", Calendar.getInstance());
                contentNode.setProperty("jcr:lastModifiedBy", session.getUserID());
            }
            this.createClientLibFolderForTheme(session, assetManager, themeJson, themeAsset.getName());
            resolver.commit();
        }
        catch (FormsMgrException e) {
            throw e;
        }
        catch (Exception e) {
            this.log.error("Exception in createTheme while theme creation", (Throwable)e);
            throw new FormsMgrException("AEM-FMG-800-009");
        }
    }

    private boolean isValidThemeInputParams(Session session, JSONObject params, String errorMsg) throws FormsMgrException, RepositoryException {
        boolean returnVal = false;
        errorMsg = "Invalid Parameter : ";
        try {
            if (session == null) {
                this.log.error("session parameter in isValidThemeInputParams() function is null");
                Object[] args = new Object[]{"session", session};
                throw new FormsMgrException("AEM-FMG-700-001", args);
            }
            if (!params.has("path") || params.getString("path").isEmpty()) {
                errorMsg = errorMsg.concat("Theme path is missing");
            } else if (!params.has("metadataProperties")) {
                errorMsg = errorMsg.concat("Theme metadata properties is missing");
            } else {
                JSONObject metadataProperties = new JSONObject(params.getString("metadataProperties"));
                if (!metadataProperties.has("clientlibRef") || metadataProperties.getString("clientlibRef").isEmpty()) {
                    errorMsg = errorMsg.concat("Theme clientlib location is missing");
                } else if (!metadataProperties.has("clientlibCategory") || metadataProperties.getString("clientlibCategory").isEmpty()) {
                    errorMsg = errorMsg.concat("Theme clientlib category name is missing");
                } else {
                    String themePath = params.getString("path");
                    int index = themePath.lastIndexOf("/");
                    String nodeName = themePath.substring(index + 1);
                    if (session.nodeExists(themePath)) {
                        this.log.error("Exception in isValidThemeInputParams() as resource" + nodeName + "already exist at destination" + themePath);
                        Object[] args = new Object[]{nodeName, themePath};
                        throw new FormsMgrException("AEM-FMG-900-002", args);
                    }
                    String clientLibLocation = params.getJSONObject("metadataProperties").getString("clientlibRef");
                    if (session.nodeExists(clientLibLocation + "/" + nodeName)) {
                        this.log.error("Exception in isValidThemeInputParams() as CQ Client Library folder" + nodeName + "already exists at " + clientLibLocation + " location");
                        Object[] args = new Object[]{nodeName, clientLibLocation};
                        throw new FormsMgrException("AEM-FMG-900-002", args);
                    }
                    returnVal = true;
                }
            }
        }
        catch (JSONException e) {
            this.log.error("JSON Exception in isValidThemeInputParams() while validating input params for theme creation ", (Throwable)e);
            throw new FormsMgrException("AEM-FMG-800-009");
        }
        return returnVal;
    }

    private void createClientLibFolderForTheme(Session session, AssetManager assetManager, JSONObject params, String themeName) throws FormsMgrException {
        String clientLibLocation = "";
        try {
            JSONObject metadataPropertyJSON = params.getJSONObject("metadataProperties");
            clientLibLocation = metadataPropertyJSON.getString("clientlibRef");
            String clientLibCategoryName = metadataPropertyJSON.getString("clientlibCategory");
            Node rootNode = FMUtils.getFolderNode(session, clientLibLocation, true, "nt:folder");
            Node clientLibNode = rootNode.addNode(themeName, "cq:ClientLibraryFolder");
            clientLibNode.setProperty("categories", new String[]{clientLibCategoryName});
            clientLibNode.setProperty("guideComponentType", "fd/af/components/guideThemeClientLib");
            String cssFileName = "theme.css";
            Node cssFolderNode = clientLibNode.addNode("css", "nt:folder");
            assetManager.copyAsset("/etc/clientlibs/fd/af/guidetheme2/default/css/default.css", cssFolderNode.getPath() + "/" + cssFileName);
            Node cssTextFileNode = clientLibNode.addNode("css.txt", "nt:file");
            Node cssTextFileContentNode = cssTextFileNode.addNode("jcr:content", "nt:resource");
            cssTextFileContentNode.setProperty("jcr:mimeType", "text/css");
            String cssTextFileContent = "css/" + cssFileName;
            Binary binary = session.getValueFactory().createBinary((InputStream)new ByteArrayInputStream(cssTextFileContent.getBytes()));
            cssTextFileContentNode.setProperty("jcr:data", binary);
        }
        catch (Exception e) {
            this.log.error("Error while creating client library folder structure at location " + clientLibLocation, (Throwable)e);
            throw new FormsMgrException(e);
        }
    }

    @Override
    public boolean checkNodeExist(ResourceResolver resolver, String nodePath) throws FormsMgrException {
        Session session = (Session)resolver.adaptTo(Session.class);
        try {
            return session.nodeExists(nodePath);
        }
        catch (Exception e) {
            this.log.error("Exception in checkNodeExist() while checking Node Existence", (Throwable)e);
            throw new FormsMgrException(e);
        }
    }

    protected void bindPublishService(PublishService publishService) {
        this.publishService = publishService;
    }

    protected void unbindPublishService(PublishService publishService) {
        if (this.publishService == publishService) {
            this.publishService = null;
        }
    }

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

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

}