EntityCreationUtil.java 18.2 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.cq.mobile.platform.MobileResource
 *  com.adobe.cq.mobile.platform.MobileResourceLocator
 *  com.adobe.cq.mobile.platform.MobileResourceType
 *  com.day.cq.commons.jcr.JcrUtil
 *  com.day.cq.i18n.I18n
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageManager
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.request.RequestParameter
 *  org.apache.sling.api.request.RequestParameterMap
 *  org.apache.sling.api.request.RequestPathInfo
 *  org.apache.sling.api.resource.ModifiableValueMap
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.mobile.dps.impl.utils;

import com.adobe.cq.mobile.dps.DPSCollection;
import com.adobe.cq.mobile.dps.DPSEntity;
import com.adobe.cq.mobile.dps.DPSException;
import com.adobe.cq.mobile.dps.DPSProject;
import com.adobe.cq.mobile.dps.impl.DPSClient;
import com.adobe.cq.mobile.dps.impl.DPSEntityImporter;
import com.adobe.cq.mobile.dps.impl.ImportStatus;
import com.adobe.cq.mobile.dps.impl.utils.DPSUtil;
import com.adobe.cq.mobile.platform.MobileResource;
import com.adobe.cq.mobile.platform.MobileResourceLocator;
import com.adobe.cq.mobile.platform.MobileResourceType;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.i18n.I18n;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.webservicesupport.Configuration;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.request.RequestParameterMap;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EntityCreationUtil {
    public static final String PARAM_TEMPLATE = "template";
    public static final String PARAM_UPLOAD = "upload";
    private static final Logger LOGGER = LoggerFactory.getLogger(EntityCreationUtil.class);

    private static void validateParameters(SlingHttpServletRequest request, String[] mandatoryParameters) throws DPSException {
        I18n i18n = new I18n((HttpServletRequest)request);
        ResourceResolver resolver = request.getResourceResolver();
        Session session = (Session)resolver.adaptTo(Session.class);
        String mandatoryMissing = "";
        for (String nextMandatory : mandatoryParameters) {
            RequestParameter mandatoryCheck = request.getRequestParameter(nextMandatory);
            if (mandatoryCheck != null) continue;
            if (mandatoryMissing.length() > 0) {
                mandatoryMissing = mandatoryMissing + ", ";
            }
            mandatoryMissing = mandatoryMissing + nextMandatory;
        }
        if (StringUtils.isNotEmpty((CharSequence)mandatoryMissing)) {
            throw new DPSException(i18n.get("Missing mandatory parameter(s): {0}", "missing parameters", new Object[]{mandatoryMissing}));
        }
        String appInstanceSuffix = request.getRequestPathInfo().getSuffix();
        if (StringUtils.isEmpty((CharSequence)appInstanceSuffix)) {
            throw new DPSException(i18n.get("Missing mandatory suffix."));
        }
        Resource appPublishInstance = resolver.getResource(appInstanceSuffix);
        if (appPublishInstance == null) {
            throw new DPSException(i18n.get("Invalid suffix: {0}", null, new Object[]{appInstanceSuffix}));
        }
        MobileResource suffixMobileResource = (MobileResource)appPublishInstance.adaptTo(MobileResource.class);
        if (suffixMobileResource == null) {
            throw new DPSException(i18n.get("Invalid suffix: {0}", null, new Object[]{appInstanceSuffix}));
        }
        MobileResourceLocator locator = (MobileResourceLocator)resolver.adaptTo(MobileResourceLocator.class);
        MobileResource group = locator.findClosestResourceByType(appPublishInstance, MobileResourceType.GROUP.getType(), new String[0]);
        if (group == null) {
            throw new DPSException(i18n.get("Error finding the app-group of {0}", "Path", new Object[]{appInstanceSuffix}));
        }
        try {
            String template = request.getRequestParameter("template").getString("utf-8");
            if (!session.nodeExists(template)) {
                throw new DPSException(i18n.get("Invalid template: {0}", "Template path", new Object[]{template}));
            }
        }
        catch (Exception ex) {
            if (ex instanceof DPSException) {
                throw (DPSException)ex;
            }
            throw new DPSException(ex.getMessage(), ex);
        }
    }

    public static Page createEntity(SlingHttpServletRequest request, String[] allowedProperties, String[] mandatoryParameters, DPSClient dpsClient, boolean creatingArticle, String dpsCapitalType, String entityHomeName, String nameParameter, MobileResource group, String entityTitle, ArrayList<String> warnings) throws DPSException {
        EntityCreationUtil.validateParameters(request, mandatoryParameters);
        Page newEntity = null;
        I18n i18n = new I18n((HttpServletRequest)request);
        ResourceResolver resolver = request.getResourceResolver();
        Session session = (Session)resolver.adaptTo(Session.class);
        PageManager pageManager = (PageManager)resolver.adaptTo(PageManager.class);
        MobileResourceLocator locator = (MobileResourceLocator)resolver.adaptTo(MobileResourceLocator.class);
        String appInstanceSuffix = request.getRequestPathInfo().getSuffix();
        Resource appPublishInstance = resolver.getResource(appInstanceSuffix);
        MobileResource suffixMobileResource = (MobileResource)appPublishInstance.adaptTo(MobileResource.class);
        String dpsType = i18n.getVar(dpsCapitalType).toLowerCase();
        String dpsTypeUpper = i18n.getVar(dpsCapitalType);
        try {
            String nodeName;
            String template = request.getRequestParameter("template").getString("utf-8");
            String entityHome = group.getPath() + "/" + entityHomeName;
            Resource articleHomeRes = resolver.resolve(entityHome);
            Resource imported = resolver.resolve(entityHome + "/" + "imported");
            if (ResourceUtil.isNonExistingResource((Resource)articleHomeRes) || ResourceUtil.isNonExistingResource((Resource)imported)) {
                HashMap<String, String> properties = new HashMap<String, String>();
                properties.put("jcr:primaryType", "sling:Folder");
                Resource home = articleHomeRes;
                if (ResourceUtil.isNonExistingResource((Resource)articleHomeRes)) {
                    home = resolver.create((Resource)group.adaptTo(Resource.class), entityHomeName, properties);
                }
                resolver.create(home, "imported", properties);
                if (resolver.isLive()) {
                    resolver.commit();
                }
            }
            if ("imported".equals(nodeName = request.getRequestParameter(nameParameter).getString())) {
                throw new DPSException(i18n.get("'{0}' is a reserved Name.", "The string 'imported'.", new Object[]{"imported"}));
            }
            if (!JcrUtil.isValidName((String)nodeName)) {
                throw new DPSException(i18n.get("Invalid {0} name: {1}", "Entity type and entity Node Name", new Object[]{dpsType, nodeName}));
            }
            if (session.nodeExists(entityHome + "/" + nodeName)) {
                throw new DPSException(i18n.get("{0} name, {1}, already exists in AEM.", "Entity type and entity Node Name", new Object[]{dpsTypeUpper, nodeName}));
            }
            DPSProject project = (DPSProject)DPSUtil.getDPSObject((Page)group.adaptTo(Page.class));
            if (project.getProjectId() == null || project.getDPSConfiguration() == null) {
                warnings.add(i18n.get("WARNING: The operation could not connect to Experience Manager Mobile to ensure {0} name was unique.", "Entity type", new Object[]{dpsCapitalType}));
            } else {
                boolean entityExists;
                try {
                    entityExists = creatingArticle ? dpsClient.articleExistsInDPS(project, nodeName) : dpsClient.bannerExistsInDPS(project, nodeName);
                }
                catch (DPSException dpsEx) {
                    warnings.add(i18n.get("WARNING: The operation failed to connect to Experience Manager Mobile to ensure {0} name was unique.", "Entity type", new Object[]{dpsCapitalType}));
                    entityExists = false;
                }
                if (entityExists) {
                    throw new DPSException(i18n.get("{0} name, {1}, already exists in Experience Manager Mobile.", "Entity type and entity Node Name", new Object[]{dpsCapitalType, nodeName}));
                }
            }
            newEntity = pageManager.create(entityHome, nodeName, template, entityTitle);
            session.save();
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            throw new DPSException(i18n.get("Error extracting properties and creating {0}: {1}", "Entity type and Path to Page", new Object[]{dpsCapitalType, appPublishInstance.getPath()}), ex);
        }
        return newEntity;
    }

    public static void saveProperties(SlingHttpServletRequest request, Page newEntity, String[] allowedProperties, String dpsResourceType, DPSClient dpsClient, DPSEntityImporter dpsEntityImporter, MobileResource group) throws DPSException {
        I18n i18n = new I18n((HttpServletRequest)request);
        ResourceResolver resolver = request.getResourceResolver();
        Session session = (Session)resolver.adaptTo(Session.class);
        PageManager pageManager = (PageManager)resolver.adaptTo(PageManager.class);
        String dpsCapitalType = dpsResourceType.substring(4);
        String dpsType = i18n.get(dpsCapitalType.toLowerCase());
        try {
            ModifiableValueMap addPropertiesVM = (ModifiableValueMap)newEntity.getContentResource().adaptTo(ModifiableValueMap.class);
            for (String nextProperty : allowedProperties) {
                RequestParameter[] requestParameters = request.getRequestParameters(nextProperty);
                if (requestParameters == null || requestParameters.length == 0) continue;
                String requestType = EntityCreationUtil.getPropertyType(requestParameters, request, nextProperty);
                if (!requestType.endsWith("[]")) {
                    Object obj = EntityCreationUtil.getSingleObject(requestParameters, requestType);
                    if (obj == null) continue;
                    addPropertiesVM.put((Object)nextProperty, obj);
                    continue;
                }
                Object[] values = EntityCreationUtil.getArrayObject(requestParameters, requestType);
                if (values == null || values.length <= 0) continue;
                addPropertiesVM.put((Object)nextProperty, (Object)values);
            }
            addPropertiesVM.put((Object)"dps-resourceType", (Object)dpsResourceType);
            if (session.hasPendingChanges()) {
                session.save();
            }
        }
        catch (Exception ex) {
            throw new DPSException(i18n.get("Error saving properties on {0}", "Path to Page", new Object[]{newEntity.getPath()}));
        }
        boolean uploadNewEntity = request.getRequestParameterMap().containsKey((Object)"upload") && "false".equalsIgnoreCase(request.getRequestParameter("upload").getString());
        RequestParameter[] collections = request.getRequestParameters("dps-collections");
        if (uploadNewEntity || collections != null) {
            DPSEntity dpsEntity = (DPSEntity)DPSUtil.getDPSObject(newEntity);
            try {
                if (!uploadNewEntity) {
                    LOGGER.warn("New {} {} uploaded in order to add to a collection's content.  Ignoring request parameter 'upload'.", (Object)dpsType, (Object)newEntity.getName());
                }
                dpsClient.uploadEntity(dpsEntity, true, false);
            }
            catch (DPSException dpsEx) {
                throw new DPSException(i18n.get("Error uploading the new {0} to Experience Manager Mobile", "Entity Type", new Object[]{dpsType}));
            }
            if (collections != null) {
                String collectionLinkErrorMessage = "";
                for (RequestParameter collection : collections) {
                    try {
                        Page nextCollection = pageManager.getPage(collection.getString("UTF-8"));
                        DPSCollection dpsCollection = (DPSCollection)DPSUtil.getDPSObject(nextCollection);
                        dpsClient.addContentToCollection(dpsCollection, dpsEntity);
                        dpsEntityImporter.importDPSEntity(dpsCollection);
                        continue;
                    }
                    catch (Exception ex) {
                        collectionLinkErrorMessage = collectionLinkErrorMessage + i18n.get("Error associating to collection {0} ", "collection name", new Object[]{collection.getString()});
                    }
                }
                if (StringUtils.isNotEmpty((CharSequence)collectionLinkErrorMessage)) {
                    throw new DPSException(i18n.get("{0} created successfully but had the following errors: {1}", "Entity Type and a list of errors", new Object[]{dpsCapitalType, collectionLinkErrorMessage}));
                }
            }
        }
    }

    public static void setImage(SlingHttpServletRequest request, Page newEntity, String dpsCapitalType, String imageParameterName, String imageNodeName) throws DPSException {
        I18n i18n = new I18n((HttpServletRequest)request);
        ResourceResolver resolver = request.getResourceResolver();
        Session session = (Session)resolver.adaptTo(Session.class);
        String dpsType = i18n.get(dpsCapitalType.toLowerCase());
        RequestParameter imageParameter = request.getRequestParameter(imageParameterName);
        if (imageParameter != null) {
            try {
                String imagePath = imageParameter.getString();
                if (StringUtils.isNotEmpty((CharSequence)imagePath)) {
                    Node imageNode = JcrUtil.createPath((String)(newEntity.getPath() + "/" + "jcr:content" + "/" + imageNodeName), (String)"nt:unstructured", (Session)session);
                    if (session.hasPendingChanges()) {
                        session.save();
                    }
                    imageNode.setProperty("sling:resourceType", "foundation/components/image");
                    imageNode.setProperty("fileReference", imagePath);
                    imageNode.setProperty("imageRotate", 0);
                    imageNode.setProperty("imageCrop", "");
                    if (session.hasPendingChanges()) {
                        session.save();
                    }
                }
            }
            catch (RepositoryException repEx) {
                throw new DPSException(i18n.get("{0} created successfully but the image could not be save.", "Entity Type", new Object[]{dpsCapitalType}));
            }
        }
    }

    private static String getPropertyType(RequestParameter[] requestParameters, SlingHttpServletRequest request, String property) {
        String type = "String";
        String typeHint = request.getParameter(property + "@TypeHint");
        if (StringUtils.isNotEmpty((CharSequence)typeHint)) {
            type = typeHint;
        } else if (requestParameters.length > 1) {
            type = "String[]";
        }
        return type;
    }

    private static Object getSingleObject(RequestParameter[] requestParameters, String type) {
        if (type.equals("String")) {
            String value = null;
            for (int i = 0; i < requestParameters.length; ++i) {
                try {
                    if (!StringUtils.isNotEmpty((CharSequence)requestParameters[i].getString("utf-8"))) continue;
                    value = requestParameters[i].getString("utf-8");
                    break;
                }
                catch (UnsupportedEncodingException encodingEx) {
                    // empty catch block
                }
            }
            return value;
        }
        if (type.equals("Boolean")) {
            return requestParameters[0].getString().equalsIgnoreCase("true") || requestParameters[0].getString().equalsIgnoreCase("on");
        }
        return requestParameters[0];
    }

    private static Object[] getArrayObject(RequestParameter[] requestParameters, String type) {
        if (type.equals("String[]")) {
            int i;
            int size = 0;
            for (i = 0; i < requestParameters.length; ++i) {
                try {
                    if (!StringUtils.isNotEmpty((CharSequence)requestParameters[i].getString("utf-8"))) continue;
                    ++size;
                    continue;
                }
                catch (UnsupportedEncodingException encodingEx) {
                    // empty catch block
                }
            }
            Object[] values = new String[size];
            for (i = 0; i < requestParameters.length; ++i) {
                try {
                    if (!StringUtils.isNotEmpty((CharSequence)requestParameters[i].getString("utf-8"))) continue;
                    values[i] = requestParameters[i].getString("utf-8");
                    continue;
                }
                catch (UnsupportedEncodingException encodingEx) {
                    // empty catch block
                }
            }
            return values;
        }
        return null;
    }
}