Utils.java 13.3 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.wcm.api.WCMException
 *  com.day.cq.wcm.msm.api.LiveRelationship
 *  com.day.cq.wcm.msm.api.LiveRelationshipManager
 *  com.day.cq.wcm.msm.api.LiveStatus
 *  com.day.text.Text
 *  javax.jcr.Item
 *  javax.jcr.ItemNotFoundException
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.PropertyIterator
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.nodetype.NodeType
 *  org.apache.commons.lang.StringUtils
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.msm.impl;

import com.day.cq.wcm.api.WCMException;
import com.day.cq.wcm.msm.api.LiveRelationship;
import com.day.cq.wcm.msm.api.LiveRelationshipManager;
import com.day.cq.wcm.msm.api.LiveStatus;
import com.day.cq.wcm.msm.impl.LiveCopyManagerImpl;
import com.day.cq.wcm.msm.impl.LiveRelationshipManagerImpl;
import com.day.cq.wcm.msm.impl.RolloutManagerImpl;
import com.day.text.Text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.jcr.Item;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.nodetype.NodeType;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Utils {
    private static final Logger log = LoggerFactory.getLogger(Utils.class);
    private static final String SLASH = "/";
    private static final String PATH_CONTENT = "/jcr:content";
    private static final String PE_CONTENT = "/jcr:content/";

    public static boolean isGhost(Node node) throws RepositoryException {
        return node.hasProperty("sling:resourceType") && node.getProperty("sling:resourceType").getString().equals("wcm/msm/components/ghost");
    }

    public static Node getNode(ResourceResolver resolver, String path) {
        Resource r;
        if (path != null && (r = resolver.getResource(path)) != null) {
            try {
                return Utils.getWorkingNode((Node)r.adaptTo(Node.class));
            }
            catch (RepositoryException e) {
                log.debug("Failed to access primary item of {}: {}", (Object)r.getPath(), (Object)e);
            }
        }
        return null;
    }

    public static String appendPath(String root, String relative) {
        if (StringUtils.isEmpty((String)root) || StringUtils.isEmpty((String)relative) || relative.startsWith("/") || !root.startsWith("/")) {
            throw new IllegalArgumentException();
        }
        if (root.endsWith("/")) {
            return String.format("%s%s", root, relative);
        }
        return String.format("%s/%s", root, relative);
    }

    public static String relativePath(String parent, String child) {
        if (StringUtils.isEmpty((String)parent) || StringUtils.isEmpty((String)child) || !parent.startsWith("/") || !child.startsWith("/") || !Text.isDescendant((String)parent, (String)child)) {
            throw new IllegalArgumentException();
        }
        return child.substring(parent.length() + 1);
    }

    public static Node getWorkingNode(Node node) throws ItemNotFoundException, RepositoryException {
        String name;
        if (node != null && node.isNodeType("nt:hierarchyNode") && (name = Utils.getPrimaryItemName(node)) != null) {
            Item item = node.getPrimaryItem();
            if (item.isNode()) {
                return (Node)item;
            }
            return item.getParent();
        }
        return node;
    }

    public static Node getHierarchyNode(Node node) throws RepositoryException {
        try {
            Node parent;
            String name;
            if (node != null && !node.isNodeType("nt:hierarchyNode") && node.getParent().isNodeType("nt:hierarchyNode") && (name = Utils.getPrimaryItemName(parent = node.getParent())) != null && node.getName().equals(name)) {
                return parent;
            }
        }
        catch (ItemNotFoundException ignore) {
            // empty catch block
        }
        return node;
    }

    public static boolean resourceHasNode(Resource resource) {
        return resource != null && resource.adaptTo(Node.class) != null;
    }

    public static String getContainingPagePath(String absPath) {
        if (!absPath.startsWith("/")) {
            throw new IllegalArgumentException("Only absolute Paths accepted");
        }
        if (absPath.contains("/jcr:content/")) {
            return absPath.substring(0, absPath.indexOf("/jcr:content/"));
        }
        if (absPath.endsWith("/jcr:content")) {
            return absPath.substring(0, absPath.length() - "/jcr:content".length());
        }
        return absPath;
    }

    public static void writeRelationship(ResourceResolver resolver, String targetPath, String sourcePath, boolean isDeep, String[] rolloutConfigs, boolean autoSave) throws WCMException {
        try {
            Node slaveNode = Utils.getNode(resolver, targetPath);
            if (slaveNode != null) {
                if (!slaveNode.isNodeType("cq:LiveSync")) {
                    slaveNode.addMixin("cq:LiveSync");
                }
                Node configNode = !slaveNode.hasNode("cq:LiveSyncConfig") ? slaveNode.addNode("cq:LiveSyncConfig", "cq:LiveSyncConfig") : slaveNode.getNode("cq:LiveSyncConfig");
                if (sourcePath.endsWith("jcr:content")) {
                    sourcePath = sourcePath.substring(0, sourcePath.indexOf("jcr:content") - 1);
                }
                configNode.setProperty("cq:master", sourcePath);
                configNode.setProperty("cq:isDeep", isDeep);
                if (rolloutConfigs != null && rolloutConfigs.length == 1 && "".equals(rolloutConfigs[0])) {
                    rolloutConfigs = null;
                }
                if (rolloutConfigs != null) {
                    configNode.setProperty("cq:rolloutConfigs", rolloutConfigs);
                }
                if (autoSave) {
                    slaveNode.getSession().save();
                }
            }
        }
        catch (Exception re) {
            throw new WCMException("Unable to write relationship", (Throwable)re);
        }
    }

    public static void detachLiveCopy(Node targetNode, boolean deep, boolean autoSave) throws WCMException {
        try {
            if (targetNode != null) {
                Utils.detachLiveCopy(targetNode, deep);
                if (autoSave) {
                    targetNode.getSession().save();
                }
            }
        }
        catch (Exception re) {
            throw new WCMException("Unable to remove Live Copy markers", (Throwable)re);
        }
    }

    public static boolean cleanupGhost(Resource target) throws WCMException, RepositoryException {
        Node targetNode;
        if (target != null && (targetNode = (Node)target.adaptTo(Node.class)) != null && Utils.isGhost(targetNode)) {
            String initialSlingResourceSuperType;
            String initialSlingResourceType = targetNode.hasProperty("initialSlingResourceType") ? targetNode.getProperty("initialSlingResourceType").getString() : "";
            String string = initialSlingResourceSuperType = targetNode.hasProperty("initialSlingResourceSuperType") ? targetNode.getProperty("initialSlingResourceSuperType").getString() : "";
            if (!"".equals(initialSlingResourceType)) {
                targetNode.setProperty("sling:resourceType", initialSlingResourceType);
                targetNode.setProperty("sling:resourceSuperType", initialSlingResourceSuperType);
                Utils.detachLiveCopy(targetNode, true, false);
                targetNode.getSession().save();
                return true;
            }
            targetNode.remove();
            targetNode.getSession().save();
            return false;
        }
        throw new WCMException("Trying to clean up a resource which is not a ghost");
    }

    public static void removeOrphanGhosts(LiveRelationshipManager liveRelationshipManager, Resource resource, boolean deep, boolean autoSave) throws WCMException {
        try {
            if (autoSave) {
                Session session = (Session)resource.getResourceResolver().adaptTo(Session.class);
                Utils.removeOrphanGhosts(liveRelationshipManager, resource, deep);
                session.save();
            } else {
                Utils.removeOrphanGhosts(liveRelationshipManager, resource, deep);
            }
        }
        catch (Exception re) {
            throw new WCMException("Unable to remove orphan ghosts", (Throwable)re);
        }
    }

    public static String findFollowingSibling(Node sourceNode, Node targetParent) throws RepositoryException {
        String followingSibling = null;
        if (targetParent != null && sourceNode != null) {
            Node masterParent = sourceNode.getParent();
            String sourceName = sourceNode.getName();
            NodeIterator ni = masterParent.getNodes();
            boolean foundMasterChild = false;
            while (ni.hasNext()) {
                Node masterChild = ni.nextNode();
                if (masterChild.getName().equals(sourceName)) {
                    foundMasterChild = true;
                    continue;
                }
                if (!foundMasterChild || !targetParent.hasNode(masterChild.getName())) continue;
                followingSibling = masterChild.getName();
                break;
            }
        }
        return followingSibling;
    }

    public static String getPagePath(String pagePath) {
        if ("jcr:content".equals(Text.getName((String)pagePath))) {
            return Text.getRelativeParent((String)pagePath, (int)1);
        }
        return pagePath;
    }

    @Deprecated
    public static Map<String, String> nodeToMap(Node node) throws RepositoryException {
        HashMap<String, String> res = new HashMap<String, String>();
        if (node != null) {
            PropertyIterator iter = node.getProperties();
            while (iter.hasNext()) {
                Property prop = iter.nextProperty();
                res.put(prop.getName(), prop.getString());
            }
        }
        return res;
    }

    private static void removeOrphanGhosts(LiveRelationshipManager liveRelationshipManager, Resource resource, boolean deep) throws WCMException {
        try {
            LiveRelationship lr;
            if (Utils.isGhost((Node)resource.adaptTo(Node.class)) && !(lr = liveRelationshipManager.getLiveRelationship(resource, false)).getStatus().isSourceExisting()) {
                Node targetNode = (Node)resource.adaptTo(Node.class);
                targetNode.remove();
                return;
            }
            if (deep) {
                Iterator ni = resource.getResourceResolver().listChildren(resource);
                while (ni.hasNext()) {
                    Resource child = (Resource)ni.next();
                    Utils.removeOrphanGhosts(liveRelationshipManager, child, deep);
                }
            }
        }
        catch (Exception re) {
            throw new WCMException("Unable to remove orphan ghosts", (Throwable)re);
        }
    }

    private static void detachLiveCopy(Node targetNode, boolean deep) throws WCMException {
        try {
            if (Utils.isGhost(targetNode)) {
                targetNode.remove();
                return;
            }
            LiveRelationshipManagerImpl.removeMarker(targetNode);
            if (targetNode.hasNode("cq:LiveSyncAction")) {
                Node actions = targetNode.getNode("cq:LiveSyncAction");
                actions.remove();
            }
            LiveCopyManagerImpl.removeMarker(targetNode);
            RolloutManagerImpl.removeMarker(targetNode);
            if (deep) {
                NodeIterator ni = targetNode.getNodes();
                while (ni.hasNext()) {
                    Node child = ni.nextNode();
                    Utils.detachLiveCopy(child, deep);
                }
            }
        }
        catch (Exception re) {
            throw new WCMException("Unable to remove Live Copy markers", (Throwable)re);
        }
    }

    private static String getPrimaryItemName(Node node) throws RepositoryException {
        NodeType[] mixins;
        String name = node.getPrimaryNodeType().getPrimaryItemName();
        if (name != null) {
            return name;
        }
        for (NodeType mixin : mixins = node.getMixinNodeTypes()) {
            name = mixin.getPrimaryItemName();
            if (name == null) continue;
            return name;
        }
        return null;
    }

    public static List<String> propertyMVToList(Node node, String name) {
        ArrayList<String> ret = new ArrayList<String>();
        try {
            if (node != null && node.hasProperty(name)) {
                Value[] values;
                for (Value v : values = node.getProperty(name).getValues()) {
                    ret.add(v.getString());
                }
            }
        }
        catch (RepositoryException ignore) {
            // empty catch block
        }
        return ret;
    }
}