EmailServiceFormsHelper.java 9.29 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.wcm.foundation.forms.FieldDescription
 *  com.day.cq.wcm.foundation.forms.FormsHelper
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.lock.LockException
 *  javax.jcr.nodetype.ConstraintViolationException
 *  javax.jcr.version.VersionException
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceMetadata
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.api.scripting.SlingBindings
 *  org.apache.sling.api.scripting.SlingScriptHelper
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.mcm.emailprovider;

import com.day.cq.mcm.emailprovider.EmailService;
import com.day.cq.mcm.emailprovider.service.EmailServiceProvider;
import com.day.cq.mcm.emailprovider.types.EmailServiceActions;
import com.day.cq.wcm.foundation.forms.FieldDescription;
import com.day.cq.wcm.foundation.forms.FormsHelper;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.version.VersionException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
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.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EmailServiceFormsHelper {
    private static final Logger log = LoggerFactory.getLogger((String)EmailServiceFormsHelper.class.getName());
    private static final String FOUNDATION_FORM_START = "foundation/components/form/start";
    private static final String FOUNDATION_FORM_END = "foundation/components/form/end";
    private static final String CTA_EMAIL_ID = "mcm/components/cta-form/emailId";
    private static final String PARAM_PATH = "cfgpath";

    private EmailServiceFormsHelper() {
    }

    public static List<Node> addFormFields(Resource formResource, SlingHttpServletRequest request, SlingHttpServletResponse response) {
        SlingBindings bindings = (SlingBindings)request.getAttribute(SlingBindings.class.getName());
        SlingScriptHelper sling = bindings.getSling();
        if (sling == null) {
            log.error("Error retrieving form parameters: SlingScriptHelper is null");
            return null;
        }
        EmailServiceProvider emailServiceProvider = (EmailServiceProvider)sling.getService(EmailServiceProvider.class);
        ConfigurationManager cfgMgr = (ConfigurationManager)request.getResourceResolver().adaptTo(ConfigurationManager.class);
        Configuration configuration = EmailServiceFormsHelper.getConfiguration(formResource, cfgMgr);
        EmailService emailService = emailServiceProvider.getEmailService(configuration);
        ValueMap map = ResourceUtil.getValueMap((Resource)formResource);
        List formFields = null;
        try {
            formFields = (List)emailService.execute(EmailServiceActions.GET_FORM_FIELDS, (Map<String, Object>)map, configuration);
            Iterator existingFields = FormsHelper.getFormElements((Resource)formResource);
            ArrayList<Resource> existingFieldsList = new ArrayList<Resource>();
            while (existingFields.hasNext()) {
                existingFieldsList.add((Resource)existingFields.next());
            }
            if (EmailServiceFormsHelper.matchFieldSets(formFields, existingFieldsList)) {
                return new ArrayList<Node>();
            }
            EmailServiceFormsHelper.deleteOldNodes(existingFieldsList, (Node)formResource.getParent().adaptTo(Node.class));
            return EmailServiceFormsHelper.addNodes(formFields, formResource);
        }
        catch (Exception e) {
            log.error("Error retrieving form parameters: " + e.getMessage());
            return null;
        }
    }

    private static String getNodeName(String tentativeName, Node parentNode) throws RepositoryException {
        int suffix = 0;
        String _name = tentativeName + "_";
        while (parentNode.hasNode(_name + suffix)) {
            ++suffix;
        }
        return parentNode.hasNode(tentativeName) ? _name + suffix : tentativeName;
    }

    private static List<Node> addNodes(List<FieldDescription> formFields, Resource formResource) {
        ArrayList<Node> addedNodes = new ArrayList<Node>();
        try {
            Node formParent = (Node)formResource.getParent().adaptTo(Node.class);
            Resource formEnd = EmailServiceFormsHelper.getFormEnd(formResource);
            Node orderBefore = (Node)formEnd.adaptTo(Node.class);
            for (FieldDescription fd : formFields) {
                Resource resource = fd.getFieldResource();
                ResourceMetadata rm = resource.getResourceMetadata();
                String resourceType = resource.getResourceType();
                String nodeName = EmailServiceFormsHelper.getNodeName(resourceType.substring(resourceType.lastIndexOf(47) + 1), formParent);
                Node node = formParent.addNode(nodeName, "nt:unstructured");
                node.setProperty("name", fd.getName());
                node.setProperty("sling:resourceType", resourceType);
                node.setProperty("sling:resourceSuperType", rm.get((Object)"sling:resourceSuperType").toString());
                node.setProperty("required", fd.isRequired());
                if (fd.getConstraintType() != null) {
                    node.setProperty("constraintType", fd.getConstraintType());
                }
                formParent.orderBefore(node.getName(), orderBefore.getName());
                addedNodes.add(node);
            }
            formParent.getSession().save();
        }
        catch (Exception e) {
            log.error("Error occured while adding form fields: " + e.getMessage());
        }
        return addedNodes;
    }

    private static Resource getFormEnd(Resource formResource) {
        boolean found;
        Resource resource;
        if (!ResourceUtil.isA((Resource)formResource, (String)"foundation/components/form/start")) {
            return null;
        }
        resource = null;
        found = false;
        try {
            Resource formParent = formResource.getParent();
            Iterator iter = formParent.listChildren();
            Boolean start = false;
            while (iter.hasNext()) {
                resource = (Resource)iter.next();
                if (start.booleanValue() && ResourceUtil.isA((Resource)resource, (String)"foundation/components/form/end")) {
                    found = true;
                    break;
                }
                if (start.booleanValue() || !resource.getName().equals(formResource.getName())) continue;
                start = true;
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }
        if (found) {
            return resource;
        }
        return null;
    }

    private static void deleteOldNodes(List<Resource> existingSiblings, Node parentNode) throws VersionException, LockException, ConstraintViolationException, RepositoryException {
        Node node = null;
        for (Resource resource : existingSiblings) {
            node = (Node)resource.adaptTo(Node.class);
            node.remove();
        }
        parentNode.getSession().save();
    }

    private static boolean matchFieldSets(List<FieldDescription> formFields, List<Resource> existingFields) {
        HashMap<String, Resource> existingFieldMap = new HashMap<String, Resource>();
        for (Resource fRes : existingFields) {
            ValueMap values = ResourceUtil.getValueMap((Resource)fRes);
            String name = (String)values.get("name", String.class);
            if (name == null) continue;
            existingFieldMap.put(name, fRes);
        }
        for (FieldDescription formField : formFields) {
            Resource existingFieldRes = (Resource)existingFieldMap.get(formField.getName());
            if (existingFieldRes != null || !formField.isRequired()) continue;
            return false;
        }
        return true;
    }

    private static Configuration getConfiguration(Resource formResource, ConfigurationManager cfgMgr) {
        Configuration configuration = null;
        ValueMap values = ResourceUtil.getValueMap((Resource)formResource);
        String path = (String)values.get("cfgpath", String.class);
        if (path != null) {
            configuration = cfgMgr.getConfiguration(path);
        }
        return configuration;
    }
}