LeadFormParagraphPostProcessor.java 11.4 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.servlets.post.Modification
 *  org.apache.sling.servlets.post.ModificationType
 *  org.apache.sling.servlets.post.SlingPostProcessor
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.mcm.landingpage.leadform;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.servlets.post.Modification;
import org.apache.sling.servlets.post.ModificationType;
import org.apache.sling.servlets.post.SlingPostProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
@Service(value={SlingPostProcessor.class})
@Properties(value={@Property(name="service.ranking", intValue={101})})
public class LeadFormParagraphPostProcessor
implements SlingPostProcessor {
    private final Logger logger;
    private final String PAGE_MARKER = "/jcr:content/";
    public static final String RT_LEAD_FORM_PREFIX = "mcm/components/cta-form/";
    public static final String RT_LEAD_FORM_BEGIN = "mcm/components/cta-form/start";
    public static final String RT_LEAD_FORM_END = "mcm/components/cta-form/end";
    public static final String START_PROPERTY_FORMID = "formid";
    public static final String START_PROPERTY_END_RESOURCE_TYPE = "endResourceType";
    private static final String START_PROPERTY_ACTION_TYPE = "actionType";
    private static final String DEFAULT_ACTION_TYPE = "mcm/components/cta-form/actions/createLead";

    public LeadFormParagraphPostProcessor() {
        this.logger = LoggerFactory.getLogger((String)this.getClass().getName());
        this.PAGE_MARKER = "/jcr:content/";
    }

    public void process(SlingHttpServletRequest request, List<Modification> changes) throws Exception {
        HashSet<String> fixPaths = new HashSet<String>();
        for (Modification mod : changes) {
            switch (mod.getType()) {
                case ORDER: 
                case MOVE: 
                case COPY: {
                    break;
                }
                case MODIFY: 
                case CREATE: 
                case DELETE: {
                    int pageEndPos = mod.getSource().indexOf("/jcr:content/");
                    if (pageEndPos == -1) break;
                    String pagePath = mod.getSource().substring(0, pageEndPos);
                    fixPaths.add(pagePath);
                }
            }
        }
        ResourceResolver resolver = request.getResourceResolver();
        for (String pagePath : fixPaths) {
            String contentPath = pagePath + '/' + "jcr:content";
            this.logger.debug("Checking page for form paragraphs {}", (Object)pagePath);
            Resource contentResource = resolver.getResource(contentPath);
            if (contentResource == null) continue;
            this.fixStructure(contentResource);
        }
    }

    private void fixStructure(Resource contentResource) throws RepositoryException {
        Iterator rI = ResourceUtil.listChildren((Resource)contentResource);
        while (rI.hasNext()) {
            Resource res = (Resource)rI.next();
            if (ResourceUtil.isA((Resource)res, (String)"mcm/components/cta-form/start") || ResourceUtil.isA((Resource)res, (String)"mcm/components/cta-form/end")) {
                if (this.checkFormStructure(res) == null) continue;
                this.logger.debug("Fixed forms structure at {}", (Object)contentResource.getPath());
                continue;
            }
            this.fixStructure(res);
        }
    }

    private Resource searchFormStart(Resource resource) {
        Resource current;
        if (ResourceUtil.getName((Resource)resource).equals("jcr:content")) {
            return null;
        }
        if (resource.getPath().lastIndexOf("/") == 0) {
            return null;
        }
        if ("mcm/components/cta-form/start".equals(resource.getResourceType())) {
            return resource;
        }
        Resource parent = ResourceUtil.getParent((Resource)resource);
        ArrayList<Resource> predecessor = new ArrayList<Resource>();
        Iterator i = ResourceUtil.listChildren((Resource)parent);
        while (i.hasNext() && !(current = (Resource)i.next()).getPath().equals(resource.getPath())) {
            predecessor.add(current);
        }
        Collections.reverse(predecessor);
        for (Resource current2 : predecessor) {
            if ("mcm/components/cta-form/start".equals(current2.getResourceType())) {
                return resource;
            }
            if (!"mcm/components/cta-form/end".equals(current2.getResourceType())) continue;
            return null;
        }
        return this.searchFormStart(parent);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public Resource checkFormStructure(Resource rsrc) {
        Resource formStart;
        if (LeadFormParagraphPostProcessor.checkResourceType(rsrc, "mcm/components/cta-form/start")) {
            Node start = (Node)rsrc.adaptTo(Node.class);
            if (start != null) {
                try {
                    if (!start.hasProperty("formid")) {
                        start.setProperty("formid", rsrc.getPath().replaceAll("[/:.]", "_"));
                    }
                    if (!start.hasProperty("actionType")) {
                        start.setProperty("actionType", "mcm/components/cta-form/actions/createLead");
                    }
                    start.getSession().save();
                }
                catch (RepositoryException e) {
                    this.logger.error("Unable to add default action type and form id " + (Object)rsrc, (Throwable)e);
                }
            } else {
                this.logger.error("Resource is not adaptable to node - unable to add default action type and form id for " + (Object)rsrc);
            }
            Iterator iter = ResourceUtil.listChildren((Resource)ResourceUtil.getParent((Resource)rsrc));
            while (!((Resource)iter.next()).getPath().equals(rsrc.getPath())) {
            }
            Resource formEnd = null;
            Resource nextPar = null;
            boolean stop = false;
            while (iter.hasNext() && formEnd == null && !stop) {
                Resource current = (Resource)iter.next();
                if (nextPar == null) {
                    nextPar = current;
                }
                if (LeadFormParagraphPostProcessor.checkResourceType(current, "mcm/components/cta-form/end")) {
                    formEnd = current;
                    continue;
                }
                if (!LeadFormParagraphPostProcessor.checkResourceType(current, "mcm/components/cta-form/start")) continue;
                stop = true;
            }
            if (formEnd == null) {
                Node parent = (Node)ResourceUtil.getParent((Resource)rsrc).adaptTo(Node.class);
                if (parent != null) {
                    try {
                        String nodeName = "form_end_" + System.currentTimeMillis();
                        Node node = parent.addNode(nodeName);
                        ValueMap props = ResourceUtil.getValueMap((Resource)rsrc);
                        String resourceType = "mcm/components/cta-form/end";
                        if (props != null) {
                            resourceType = (String)props.get("endResourceType", (Object)resourceType);
                        }
                        node.setProperty("sling:resourceType", resourceType);
                        if (!resourceType.equals("mcm/components/cta-form/end")) {
                            node.setProperty("sling:resourceSuperType", "mcm/components/cta-form/end");
                        }
                        if (nextPar != null) {
                            parent.orderBefore(node.getName(), ResourceUtil.getName((Resource)nextPar));
                        }
                        parent.getSession().save();
                        Iterator i = ResourceUtil.listChildren((Resource)ResourceUtil.getParent((Resource)rsrc));
                        while (i.hasNext()) {
                            Resource r = (Resource)i.next();
                            if (!nodeName.equals(ResourceUtil.getName((Resource)r))) continue;
                            Resource resource = r;
                            return resource;
                        }
                    }
                    catch (RepositoryException re) {
                        this.logger.error("Unable to create missing form end element for form start " + (Object)rsrc, (Throwable)re);
                    }
                    finally {
                        try {
                            if (parent.getSession().hasPendingChanges()) {
                                parent.getSession().refresh(false);
                            }
                        }
                        catch (RepositoryException re) {}
                    }
                } else {
                    this.logger.error("Resource is not adaptable to node - unable to add missing form end element for " + (Object)rsrc);
                }
            }
        } else if (LeadFormParagraphPostProcessor.checkResourceType(rsrc, "mcm/components/cta-form/end") && (formStart = this.searchFormStart(rsrc)) == null) {
            Node node = (Node)rsrc.adaptTo(Node.class);
            Node parent = (Node)ResourceUtil.getParent((Resource)rsrc).adaptTo(Node.class);
            if (node != null && parent != null) {
                try {
                    node.remove();
                    parent.getSession().save();
                    Resource nextPar = rsrc;
                    return nextPar;
                }
                catch (RepositoryException re) {
                    this.logger.error("Unable to create missing form end element for form start " + (Object)rsrc, (Throwable)re);
                }
                finally {
                    try {
                        if (node.getSession().hasPendingChanges()) {
                            node.getSession().refresh(false);
                        }
                    }
                    catch (RepositoryException re) {}
                }
            }
            this.logger.error("Resource is not adaptable to node - unable to remove form element " + (Object)rsrc);
        }
        return null;
    }

    public static boolean checkResourceType(Resource resource, String type) {
        return ResourceUtil.isA((Resource)resource, (String)type);
    }

}