Cq62TargetCampaignsContentUpgrade.java 13 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.Workspace
 *  javax.jcr.nodetype.NodeType
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  org.apache.commons.lang.StringUtils
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.compat.codeupgrade.impl.cq62;

import com.day.cq.compat.codeupgrade.internal.api.ProgressInfoProvider;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeType;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Cq62TargetCampaignsContentUpgrade
implements ProgressInfoProvider {
    static final String QUERY_OFFERPROXY_RESOURCES = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([/content/campaigns]) AND s.[sling:resourceType] = 'cq/personalization/components/offerproxy'AND s.[offerPath] IS NOT NULL";
    private static final String OFFER_LIBRARY_NAME = "offer-library";
    private static final String DEFAULT_AMBIT = "master";
    private static final String PN_OFFERPATH = "offerPath";
    private static final String TEMPLATE_AMBIT = "/libs/cq/personalization/templates/ambit";
    private static final String TITLE_AMBIT = "Master Ambit";
    private static final String RT_BRANDPAGE = "mcm/components/brandpage";
    private static final String RT_AMBITPAGE = "cq/personalization/components/ambitpage";
    private static final String RT_OFFERFOLDERPAGE = "cq/personalization/components/offerfolderpage";
    private static final String RT_OFFERPROXY = "cq/personalization/components/offerproxy";
    private static final String CAMPAIGNS_ROOT_PATH = "/content/campaigns";
    private final Logger log;
    private String progressInfo;

    public Cq62TargetCampaignsContentUpgrade() {
        this.log = LoggerFactory.getLogger(this.getClass());
    }

    @Override
    public String getProgressInfo() {
        return this.progressInfo;
    }

    void setProgressInfo(String info) {
        this.progressInfo = info;
        this.log.info(this.progressInfo);
    }

    void doUpgrade(Session session) {
        this.setProgressInfo(String.format("Migrating resources of type %s.", "cq/personalization/components/offerproxy"));
        int num = this.upgradeOfferProxyResources(session);
        this.setProgressInfo(String.format("%s resources of type %s migrated.", num, "cq/personalization/components/offerproxy"));
        this.setProgressInfo("Migrating brands to master ambit.");
        num = this.migrateBrands(session);
        this.setProgressInfo(String.format("%s brands migrated.", num));
        this.setProgressInfo("Migrating offer-libraries");
        num = this.migrateOfferLibraries(session);
        this.setProgressInfo(String.format("%s offer-libraries migrated.", num));
    }

    private int upgradeOfferProxyResources(Session session) {
        int i = 0;
        try {
            QueryManager qm = session.getWorkspace().getQueryManager();
            Query q = qm.createQuery("SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([/content/campaigns]) AND s.[sling:resourceType] = 'cq/personalization/components/offerproxy'AND s.[offerPath] IS NOT NULL", "JCR-SQL2");
            NodeIterator targetNodes = q.execute().getNodes();
            while (targetNodes.hasNext()) {
                Node targetNode = targetNodes.nextNode();
                try {
                    this.upgradeNode(targetNode);
                    this.save(session);
                    ++i;
                }
                catch (Exception e) {
                    this.log.error(String.format("Cannot update node of type %s at %s.", "cq/personalization/components/offerproxy", targetNode.getPath()), (Throwable)e);
                }
            }
        }
        catch (Exception e) {
            this.log.error(String.format("Cannot query repository for resources of type %s", "cq/personalization/components/offerproxy"), (Throwable)e);
        }
        return i;
    }

    private void upgradeNode(Node node) throws RepositoryException {
        String offerPathValue = null;
        if (node.hasProperty("offerPath")) {
            Property offerPath = node.getProperty("offerPath");
            offerPathValue = !offerPath.isMultiple() ? offerPath.getString() : offerPath.getValues()[0].getString();
            offerPathValue = this.appendAmbitPathSegment(offerPathValue);
            offerPathValue = this.adaptOfferLibraryPathSegment(offerPathValue);
        }
        if (!StringUtils.isEmpty((String)offerPathValue)) {
            this.log.info(String.format("Setting property %s/%s='%s'.", node.getPath(), "offerPath", offerPathValue));
            node.setProperty("offerPath", offerPathValue);
        } else {
            this.log.warn("Unable to set property {} to {} for {}.", new Object[]{"offerPath", offerPathValue, node.getPath()});
        }
    }

    protected String appendAmbitPathSegment(String path) {
        if (path != null && path.indexOf("/master/") == -1) {
            return path.replaceAll("(\\/content\\/campaigns\\/.*?)\\/(.*)", "$1/master/$2");
        }
        return path;
    }

    protected String adaptOfferLibraryPathSegment(String path) {
        if (path != null) {
            return path.replaceAll("(.*)\\/.*\\-offer-library\\/(.*)", "$1/offer-library/$2");
        }
        return path;
    }

    private int migrateBrands(Session session) {
        int i = 0;
        try {
            Node campaignsRoot = session.getNode("/content/campaigns");
            NodeIterator brands = campaignsRoot.getNodes();
            while (brands.hasNext()) {
                Node brand = brands.nextNode();
                if (this.excludeBrand(brand)) {
                    this.log.info("Skipping node at " + brand.getPath());
                    continue;
                }
                try {
                    this.log.info("Migrating brand at {}", (Object)brand.getPath());
                    Node ambit = this.getOrCreateMasterAmbitPage(brand);
                    this.migrateBrand(brand, ambit);
                    ++i;
                }
                catch (RepositoryException e) {
                    this.log.error(String.format("Unable to migrate brand %s.", brand.getName()), (Throwable)e);
                }
            }
        }
        catch (RepositoryException e) {
            this.log.error(String.format("Unable to migrate brands, root not found at %s.", "/content/campaigns"), (Throwable)e);
        }
        return i;
    }

    private boolean excludeBrand(Node brand) throws RepositoryException {
        boolean invalidName = brand.getName().matches("(jcr:content|rep:policy|geometrixx|geometrixx-outdoors)");
        if (invalidName) {
            return true;
        }
        boolean invalidResourceType = true;
        try {
            Node brandContent = brand.getNode("jcr:content");
            if (brandContent != null && "mcm/components/brandpage".equals(brandContent.getProperty("sling:resourceType").getString())) {
                invalidResourceType = false;
            }
        }
        catch (PathNotFoundException e) {
            this.log.error("Could not find jcr:content or sling:resourceType for {}", (Object)brand.getPath());
        }
        return invalidResourceType;
    }

    private Node getOrCreateMasterAmbitPage(Node brandNode) throws RepositoryException {
        Node defaultAmbit;
        block4 : {
            defaultAmbit = null;
            try {
                Node defaultAmbitNode = brandNode.getNode("master");
                if (defaultAmbitNode != null) {
                    throw new RepositoryException("Unresolvable conflict, node named 'master' found.");
                }
            }
            catch (PathNotFoundException e) {
                if (!this.log.isDebugEnabled()) break block4;
                this.log.debug("No node named 'master' found.");
            }
        }
        if (defaultAmbit == null) {
            defaultAmbit = brandNode.addNode("master", "cq:Page");
            Node contentNode = defaultAmbit.addNode("jcr:content", "cq:PageContent");
            contentNode.setProperty("sling:resourceType", "cq/personalization/components/ambitpage");
            contentNode.setProperty("cq:template", "/libs/cq/personalization/templates/ambit");
            contentNode.setProperty("jcr:title", "Master Ambit");
            Node par = contentNode.addNode("par");
            par.setProperty("sling:resourceType", "foundation/components/parsys");
            brandNode.getSession().save();
        }
        return defaultAmbit;
    }

    private void migrateBrand(Node brand, Node ambit) throws RepositoryException {
        Session session = brand.getSession();
        NodeIterator campaigns = brand.getNodes();
        while (campaigns.hasNext()) {
            Node campaign = campaigns.nextNode();
            if (this.excludeCampaign(campaign)) continue;
            String name = campaign.getName();
            if (StringUtils.endsWith((String)name, (String)"-offer-library")) {
                name = "offer-library";
            }
            String dstPath = ambit.getPath() + "/" + name;
            try {
                this.log.info(String.format("Moving %s to %s", campaign.getPath(), dstPath));
                session.move(campaign.getPath(), dstPath);
                session.save();
            }
            catch (RepositoryException e) {
                this.log.error(String.format("Unable to move node %s to %s", campaign.getPath(), dstPath), (Throwable)e);
            }
        }
    }

    private boolean excludeCampaign(Node campaign) throws RepositoryException {
        return campaign.getName().matches("(jcr:content|rep:policy|master)");
    }

    private int migrateOfferLibraries(Session session) {
        int i = 0;
        try {
            Node campaignsRoot = session.getNode("/content/campaigns");
            NodeIterator brands = campaignsRoot.getNodes();
            while (brands.hasNext()) {
                Node brand = brands.nextNode();
                if (this.excludeBrand(brand)) {
                    this.log.info("Skipping node at " + brand.getPath());
                    continue;
                }
                try {
                    this.log.info("Migrating offer library of brand {}", (Object)brand.getPath());
                    Map<String, Node> folders = this.getFolders(brand);
                    for (Node folder : folders.values()) {
                        this.log.debug("Migrating [sling:Folder] to [cq:Page] at {}", (Object)folder.getPath());
                        String title = "";
                        if (folder.hasProperty("jcr:title")) {
                            Property titleProp = folder.getProperty("jcr:title");
                            title = titleProp.getString();
                            titleProp.remove();
                        }
                        folder.setPrimaryType("cq:Page");
                        Node content = folder.addNode("jcr:content");
                        content.setPrimaryType("cq:PageContent");
                        content.setProperty("jcr:title", title);
                        content.setProperty("sling:resourceType", "cq/personalization/components/offerfolderpage");
                        content.setProperty("cq:template", "/libs/cq/personalization/templates/offerfolder");
                        ++i;
                    }
                    session.save();
                }
                catch (RepositoryException e) {
                    this.log.error(String.format("Unable to migrate offer library folders of brand %s.", brand.getPath()), (Throwable)e);
                }
            }
        }
        catch (RepositoryException e) {
            this.log.error(String.format("Unable to migrate offer libraries, root not found at %s.", "/content/campaigns"), (Throwable)e);
        }
        return i;
    }

    private void save(Session session) throws RepositoryException {
        if (session.hasPendingChanges()) {
            session.save();
        }
    }

    Map<String, Node> getFolders(Node parent) throws RepositoryException {
        HashMap<String, Node> folders = new HashMap<String, Node>();
        NodeIterator nodeIt = parent.getNodes();
        while (nodeIt.hasNext()) {
            Node child = nodeIt.nextNode();
            if (child.getPrimaryNodeType().isNodeType("sling:Folder") && StringUtils.contains((String)child.getPath(), (String)"offer-library")) {
                folders.put(child.getPath(), child);
            }
            if (!child.getNodes().hasNext()) continue;
            folders.putAll(this.getFolders(child));
        }
        return folders;
    }
}