PublishServiceImpl.java 15.2 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.replication.ReplicationActionType
 *  com.day.cq.replication.ReplicationStatus
 *  com.day.cq.replication.Replicator
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Workspace
 *  javax.jcr.nodetype.NodeType
 *  javax.jcr.security.AccessControlManager
 *  javax.jcr.security.Privilege
 *  javax.jcr.version.Version
 *  javax.jcr.version.VersionManager
 *  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.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.aem.formsndocuments.publish.impl;

import com.adobe.aem.formsndocuments.publish.DeactivatePreprocessor;
import com.adobe.aem.formsndocuments.publish.PublishPreprocessor;
import com.adobe.aem.formsndocuments.publish.PublishService;
import com.adobe.aem.formsndocuments.service.FormsRelationService;
import com.adobe.aem.formsndocuments.transferobjects.AssetInfo;
import com.adobe.aem.formsndocuments.util.FMUtils;
import com.adobe.aemforms.fm.exception.FormsMgrException;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationStatus;
import com.day.cq.replication.Replicator;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeType;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
import javax.jcr.version.Version;
import javax.jcr.version.VersionManager;
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.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate=1)
@Service(value={PublishService.class})
public class PublishServiceImpl
implements PublishService {
    private final Logger log = LoggerFactory.getLogger(PublishServiceImpl.class);
    @Reference(referenceInterface=Replicator.class)
    private Replicator replicator;
    @Reference(referenceInterface=PublishPreprocessor.class, cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)
    private final List<PublishPreprocessor> publishPreprocessors = new CopyOnWriteArrayList<PublishPreprocessor>();
    @Reference(referenceInterface=DeactivatePreprocessor.class, cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)
    private final List<DeactivatePreprocessor> deactivatePreprocessors = new CopyOnWriteArrayList<DeactivatePreprocessor>();
    @Reference(referenceInterface=FormsRelationService.class)
    private FormsRelationService formsRelationService;

    @Override
    public Set<AssetInfo> getRelatedAssetsToPublish(ResourceResolver resolver, String path) throws FormsMgrException {
        try {
            Session session = (Session)resolver.adaptTo(Session.class);
            LinkedHashSet<AssetInfo> allRelatedChildAssets = new LinkedHashSet<AssetInfo>();
            this.formsRelationService.getAllRelatedChildAssets(resolver, path, allRelatedChildAssets);
            LinkedHashSet<AssetInfo> toBePublishedAssets = new LinkedHashSet<AssetInfo>();
            for (AssetInfo formInfo : allRelatedChildAssets) {
                Resource resource = formInfo.getResource();
                ReplicationStatus replStatus = (ReplicationStatus)resource.adaptTo(ReplicationStatus.class);
                long lastModifiedTime = FMUtils.getLastModifiedOrCreated(session, resource.getPath());
                if ((replStatus.isDelivered() || replStatus.isActivated()) && replStatus.getLastPublished().getTimeInMillis() >= lastModifiedTime && lastModifiedTime != -1 && !formInfo.getPublishAssetType().equals("AF CQ Page")) continue;
                toBePublishedAssets.add(formInfo);
            }
            this.formsRelationService.getAssociatedTags(resolver, toBePublishedAssets);
            return toBePublishedAssets;
        }
        catch (Exception e) {
            throw new FormsMgrException(e);
        }
    }

    @Override
    public void publish(Session session, List<String> assetPaths) throws FormsMgrException {
        try {
            if (assetPaths == null) {
                return;
            }
            HashMap preprocessParams = new HashMap();
            String fmRoot = "/content/dam/formsanddocuments";
            for (String assetPath : assetPaths) {
                this.log.info("Publishing asset: " + assetPath);
                boolean fmAsset = assetPath.startsWith(fmRoot);
                if (!session.nodeExists(assetPath)) {
                    this.log.warn("Unable to publish asset with invalid path: " + assetPath);
                    continue;
                }
                Node assetNode = session.getNode(assetPath);
                if (fmAsset && assetNode.getPrimaryNodeType().getName().equals("dam:Asset")) {
                    for (PublishPreprocessor preprocessor : this.publishPreprocessors) {
                        this.log.info("Invoking preprocessor:" + preprocessor.getClass().getName());
                        try {
                            preprocessor.preprocess(session, assetPath, preprocessParams);
                        }
                        catch (Exception e) {
                            this.log.warn("Exception in publish preprocess. Cause: " + e.getMessage(), (Throwable)e);
                        }
                    }
                }
                if (!fmAsset) {
                    if (assetPath.startsWith("/content/apps/cm")) {
                        this.createVersion(session, assetPath);
                        this.replicate(session, assetPath, ReplicationActionType.ACTIVATE);
                        if (assetNode.hasNode("renditions")) {
                            this.replicateNodeTree(session, assetNode.getNode("renditions"), ReplicationActionType.ACTIVATE);
                        }
                        session.getNode(assetPath).setProperty("lastPublishDate", Calendar.getInstance());
                        session.save();
                    } else if (assetNode.isNodeType("cq:ClientLibraryFolder") || assetNode.isNodeType("cq:Template")) {
                        this.replicateNodeTree(session, assetNode, ReplicationActionType.ACTIVATE);
                    } else {
                        this.replicate(session, assetPath, ReplicationActionType.ACTIVATE);
                    }
                } else {
                    this.replicate(session, assetPath, ReplicationActionType.ACTIVATE);
                }
                this.log.info("Asset published successfully: " + assetPath);
            }
        }
        catch (FormsMgrException e) {
            throw e;
        }
        catch (Exception e) {
            throw new FormsMgrException(e);
        }
    }

    @Override
    public void deactivate(Session session, List<String> assetPaths) throws FormsMgrException {
        try {
            if (assetPaths == null) {
                return;
            }
            HashMap preprocessParams = new HashMap();
            for (String assetPath : assetPaths) {
                boolean fmAsset;
                this.log.info("Deactivating asset: " + assetPath);
                boolean bl = fmAsset = assetPath.startsWith("/content/dam/formsanddocuments") || assetPath.startsWith("/content/dam/formsanddocuments-themes");
                if (!session.nodeExists(assetPath)) {
                    this.log.warn("Unable to deactivate asset with invalid path: " + assetPath);
                    continue;
                }
                Node assetNode = session.getNode(assetPath);
                String guidePagePath = null;
                String clientlibPath = null;
                if (fmAsset) {
                    if (FMUtils.isGuide(session, assetPath) || FMUtils.isAdaptiveDocument(session, assetPath) || FMUtils.isAFFragment(session, assetPath)) {
                        guidePagePath = FMUtils.getPagePathFromAsset(assetPath);
                        if (!session.nodeExists(guidePagePath)) {
                            throw new FormsMgrException("Page corresponding to guide node does not exists.");
                        }
                    } else if (FMUtils.isTheme(session, assetPath) && !session.nodeExists(clientlibPath = FMUtils.getClientlibPath(assetNode))) {
                        this.log.error("Clientlib corresponding to " + assetNode.getPath() + " node does not exists.");
                        throw new FormsMgrException("Clientlib corresponding to theme node does not exists.");
                    }
                }
                if (!PublishServiceImpl.canReplicate(assetPath, session)) {
                    throw new FormsMgrException("AEM-FMG-800-004", new String[]{FMUtils.getNameFromPath(assetPath)});
                }
                if (guidePagePath != null && !PublishServiceImpl.canReplicate(guidePagePath, session)) {
                    throw new FormsMgrException("AEM-FMG-800-004", new String[]{FMUtils.getNameFromPath(guidePagePath)});
                }
                if (clientlibPath != null && !PublishServiceImpl.canReplicate(clientlibPath, session)) {
                    throw new FormsMgrException("AEM-FMG-800-004", new String[]{FMUtils.getNameFromPath(clientlibPath)});
                }
                if (fmAsset && assetNode.getPrimaryNodeType().getName().equals("dam:Asset")) {
                    for (DeactivatePreprocessor preprocessor : this.deactivatePreprocessors) {
                        this.log.info("Invoking preprocessor:" + preprocessor.getClass().getName());
                        try {
                            preprocessor.preprocess(assetPath, preprocessParams);
                        }
                        catch (Exception e) {
                            this.log.warn("Exception in deactivate preprocess. Cause: " + e.getMessage(), (Throwable)e);
                        }
                    }
                }
                this.replicate(session, assetPath, ReplicationActionType.DEACTIVATE);
                if (guidePagePath != null) {
                    this.replicate(session, guidePagePath, ReplicationActionType.DEACTIVATE);
                } else if (clientlibPath != null) {
                    this.replicate(session, clientlibPath, ReplicationActionType.DEACTIVATE);
                }
                Node contentNode = FMUtils.getContentNode(assetNode, false);
                if (contentNode != null) {
                    contentNode.setProperty("jcr:lastModified", Calendar.getInstance());
                    session.save();
                }
                this.log.info("Asset deactivated successfully: " + assetPath);
            }
        }
        catch (FormsMgrException e) {
            throw e;
        }
        catch (Exception e) {
            throw new FormsMgrException(e);
        }
    }

    private String createVersion(Session session, String nodePath) throws FormsMgrException {
        try {
            VersionManager versionMgr;
            this.log.info("Creating version for asset:" + nodePath);
            Node node = session.getNode(nodePath);
            if (!node.isNodeType("mix:versionable") && node.canAddMixin("mix:versionable")) {
                this.log.debug("Adding MIX_VERSIONABLE mixin to asset:" + nodePath);
                node.addMixin("mix:versionable");
            }
            if (session.hasPendingChanges()) {
                session.save();
            }
            if (!(versionMgr = session.getWorkspace().getVersionManager()).isCheckedOut(nodePath)) {
                versionMgr.checkout(nodePath);
                this.log.debug("First time checkout for asset:" + nodePath);
            }
            Version version = versionMgr.checkpoint(nodePath);
            String versionName = version.getName();
            this.log.info("Created version " + versionName + " for asset " + nodePath);
            return versionName;
        }
        catch (Exception e) {
            throw new FormsMgrException(e);
        }
    }

    private void replicateNodeTree(Session session, Node assetNode, ReplicationActionType replicateActionType) throws FormsMgrException {
        try {
            this.replicator.replicate(session, replicateActionType, assetNode.getPath());
            if (assetNode.isNodeType("dam:Asset") || assetNode.isNodeType("cq:Page")) {
                return;
            }
            NodeIterator nItr = assetNode.getNodes();
            while (nItr.hasNext()) {
                Node childNode = nItr.nextNode();
                this.replicateNodeTree(session, childNode, replicateActionType);
            }
        }
        catch (Exception e) {
            throw new FormsMgrException(e);
        }
    }

    private void replicate(Session session, String nodePath, ReplicationActionType replicateActionType) throws FormsMgrException {
        try {
            this.replicator.replicate(session, replicateActionType, nodePath);
        }
        catch (Exception e) {
            throw new FormsMgrException(e);
        }
    }

    private static boolean canReplicate(String path, Session session) throws RepositoryException {
        AccessControlManager acMgr = session.getAccessControlManager();
        return session.getAccessControlManager().hasPrivileges(path, new Privilege[]{acMgr.privilegeFromName("{http://www.day.com/crx/1.0}replicate")});
    }

    protected void bindPublishPreprocessors(PublishPreprocessor publishPreprocessor) {
        this.publishPreprocessors.add(publishPreprocessor);
    }

    protected void unbindPublishPreprocessors(PublishPreprocessor publishPreprocessor) {
        this.publishPreprocessors.remove(publishPreprocessor);
    }

    protected void bindDeactivatePreprocessors(DeactivatePreprocessor deactivatePreprocessor) {
        this.deactivatePreprocessors.add(deactivatePreprocessor);
    }

    protected void unbindDeactivatePreprocessors(DeactivatePreprocessor deactivatePreprocessor) {
        this.deactivatePreprocessors.remove(deactivatePreprocessor);
    }

    protected void bindReplicator(Replicator replicator) {
        this.replicator = replicator;
    }

    protected void unbindReplicator(Replicator replicator) {
        if (this.replicator == replicator) {
            this.replicator = null;
        }
    }

    protected void bindFormsRelationService(FormsRelationService formsRelationService) {
        this.formsRelationService = formsRelationService;
    }

    protected void unbindFormsRelationService(FormsRelationService formsRelationService) {
        if (this.formsRelationService == formsRelationService) {
            this.formsRelationService = null;
        }
    }
}