CreateMobileAppOperation.java 14.5 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.ui.components.HtmlResponse
 *  com.adobe.granite.xss.XSSAPI
 *  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.api.WCMException
 *  com.day.text.Text
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.nodetype.NodeType
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.commons.lang3.StringUtils
 *  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.request.RequestParameter
 *  org.apache.sling.api.request.RequestParameterMap
 *  org.apache.sling.api.resource.ModifiableValueMap
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.servlets.post.Modification
 *  org.apache.sling.servlets.post.ModificationType
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.mobile.platform.impl.operations;

import com.adobe.cq.mobile.platform.MobileResource;
import com.adobe.cq.mobile.platform.MobileResourceType;
import com.adobe.cq.mobile.platform.impl.operations.MobileAbstractOperation;
import com.adobe.cq.mobile.platform.impl.operations.MobileOperationException;
import com.adobe.cq.mobile.platform.impl.utils.MobileAppJCRUtil;
import com.adobe.granite.ui.components.HtmlResponse;
import com.adobe.granite.xss.XSSAPI;
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.api.WCMException;
import com.day.text.Text;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.nodetype.NodeType;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
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.request.RequestParameter;
import org.apache.sling.api.request.RequestParameterMap;
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.ValueMap;
import org.apache.sling.servlets.post.Modification;
import org.apache.sling.servlets.post.ModificationType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=0, label="Create Mobile App Operation")
@Service
@Properties(value={@Property(name="sling.post.operation", value={"mobileapps:createMobileApp"})})
public class CreateMobileAppOperation
extends MobileAbstractOperation {
    private static final Logger LOGGER = LoggerFactory.getLogger(CreateMobileAppOperation.class);
    public static final String OPERATION_NAME = "createMobileApp";
    protected static final String PARAM_APP_ID = "appId";
    protected static final String PARAM_TEMPLATE = "template";
    protected static final String PARAM_PARENT_PATH = "parentPath";
    protected static final String PARAM_PAGE_NAME = "pageName";
    protected static final String PARAM_MERGE_SHELL = "mergeGroupAndShell";
    protected static final String PARAM_SUBFOLDERS = "subfolders";
    protected static final String PARAM_PAGE_DESC = "jcr:description";
    protected static final String PARAM_PAGE_TITLE = "pageTitle";
    protected static final String PARAM_ARCHIVE_PATH = "archivePath";
    protected static final String PARAM_DASHBOARD_CONFIG = "pge-dashboard-config";
    protected static final String PARAM_ICON_FILEREF = "widget/icon/fileReference";
    protected static final String PN_APP_TYPE = "pge-type";
    private static final String CQ_APPS_ADMIN_CREATEAPP_EDIT = "cq-apps-admin-createapp-edit";

    @Override
    protected void perform(SlingHttpServletRequest request, HtmlResponse response, List<Modification> modifications) {
        I18n i18n = new I18n((HttpServletRequest)request);
        try {
            this.createPage(request, response, modifications, i18n);
        }
        catch (MobileOperationException e) {
            String title = i18n.get("Error");
            this.generateError(response, e.getMessage(), title);
        }
        catch (Exception ex) {
            String message = i18n.get("The server has problem processing your request");
            String title = i18n.get("Error");
            if (ex.getCause() instanceof PathNotFoundException) {
                message = i18n.get("The provided path does not exist") + ":<br/>" + ex.getCause().getMessage();
            }
            this.generateError(response, message, title);
        }
    }

    protected Page createPage(SlingHttpServletRequest request, HtmlResponse response, List<Modification> modifications, I18n i18n) throws WCMException, MobileOperationException, UnsupportedEncodingException {
        boolean mergeShellWithGroup;
        ValueMap vm;
        String parentPath = request.getParameter("parentPath");
        String pageName = request.getParameter("pageName");
        String appId = request.getParameter("appId");
        String templatePath = request.getParameter("template");
        String pageTitle = request.getParameter("pageTitle");
        String appDescription = request.getParameter("jcr:description");
        String appIcon = request.getParameter("widget/icon/fileReference");
        String appDashboard = request.getParameter("pge-dashboard-config");
        String mergeShell = request.getParameter("mergeGroupAndShell");
        String[] subFolders = request.getParameterValues("subfolders");
        if (StringUtils.isBlank((CharSequence)parentPath)) {
            String message = i18n.get("Missing mandatory parameter {0}", null, new Object[]{"parentPath"});
            throw new MobileOperationException(message);
        }
        if ("/content/phonegap".equalsIgnoreCase(parentPath)) {
            parentPath = "/content/mobileapps";
        }
        if (StringUtils.isEmpty((CharSequence)pageName)) {
            pageName = (String)request.getAttribute("pageName");
        }
        if (StringUtils.isBlank((CharSequence)pageTitle) && StringUtils.isBlank((CharSequence)pageName)) {
            String message = i18n.get("Missing mandatory parameter {0}", null, new Object[]{"pageTitle"});
            throw new MobileOperationException(message);
        }
        if (StringUtils.isBlank((CharSequence)templatePath)) {
            String message = i18n.get("Missing mandatory parameter {0}", null, new Object[]{"template"});
            throw new MobileOperationException(message);
        }
        String appType = null;
        Resource templateRes = request.getResourceResolver().resolve(templatePath);
        if (templateRes != null && (vm = templateRes.getValueMap()) != null) {
            appType = (String)vm.get("pge-type", String.class);
        }
        PageManager pageManager = (PageManager)request.getResourceResolver().adaptTo(PageManager.class);
        if (StringUtils.isNotEmpty((CharSequence)pageName)) {
            pageName = JcrUtil.createValidName((String)pageName);
        }
        Page groupPage = pageManager.create(parentPath, pageName, templatePath, pageTitle, true);
        Node groupNode = (Node)groupPage.adaptTo(Node.class);
        try {
            groupNode.addMixin("cq:MobileApp");
        }
        catch (RepositoryException e) {
            this.log.error("Unable to add cq:MobileApp mixing to the node " + groupPage.getPath(), (Throwable)e);
            throw new MobileOperationException(e.getMessage());
        }
        ArrayList<String> types = new ArrayList<String>();
        types.add(MobileResourceType.GROUP.getType());
        Page shellPage = null;
        ModifiableValueMap groupPropertiesVM = (ModifiableValueMap)groupPage.getContentResource().adaptTo(ModifiableValueMap.class);
        boolean bl = mergeShellWithGroup = StringUtils.isNotEmpty((CharSequence)mergeShell) && mergeShell.equalsIgnoreCase("true");
        if (!mergeShellWithGroup) {
            NodeIterator nodeIterator;
            String archivePath = request.getParameter("archivePath");
            if (StringUtils.isBlank((CharSequence)archivePath) && StringUtils.isBlank((CharSequence)appId)) {
                String message = i18n.get("Missing mandatory parameter {0}", null, new Object[]{"appId"});
                throw new MobileOperationException(message);
            }
            Resource templateResource = request.getResourceResolver().getResource(templatePath);
            Node templateNode = (Node)templateResource.adaptTo(Node.class);
            try {
                nodeIterator = templateNode.getNodes();
            }
            catch (RepositoryException e) {
                String message = i18n.get("Error retrieving nodes.");
                throw new MobileOperationException(message);
            }
            while (nodeIterator.hasNext()) {
                Node node = nodeIterator.nextNode();
                try {
                    if (!"cq:Page".equals(node.getPrimaryNodeType().toString())) continue;
                    Node pageNode = JcrUtil.copy((Node)node, (Node)((Node)groupPage.adaptTo(Node.class)), (String)null);
                    Resource pageResource = request.getResourceResolver().getResource(pageNode.getPath());
                    MobileResource mobileResource = (MobileResource)pageResource.adaptTo(MobileResource.class);
                    if (!mobileResource.isA(MobileResourceType.INSTANCE.getType())) continue;
                    MobileAppJCRUtil.setMobileAppProperty(pageResource.getChild("jcr:content"), "widget/id", new String[]{appId});
                    MobileAppJCRUtil.setMobileAppProperty(pageResource.getChild("jcr:content"), "widget/name/text", new String[]{pageTitle});
                    MobileAppJCRUtil.setMobileAppProperty(pageResource.getChild("jcr:content"), "widget/description/text", new String[]{appDescription});
                    if (appIcon != null && !appIcon.isEmpty()) {
                        MobileAppJCRUtil.setMobileAppProperty(pageResource.getChild("jcr:content"), "widget/icon/fileReference", new String[]{appIcon});
                    }
                    shellPage = (Page)pageResource.adaptTo(Page.class);
                    continue;
                }
                catch (RepositoryException ex) {
                    String message = i18n.get("Error iterating nodes.");
                    throw new MobileOperationException(message);
                }
            }
        } else {
            shellPage = groupPage;
            ModifiableValueMap shellPropertiesVM = groupPropertiesVM;
            this.addAdditionalInformation(shellPropertiesVM, request);
            if (StringUtils.isNotEmpty((CharSequence)appType)) {
                types.add(appType);
                types.add(MobileResourceType.INSTANCE.getType());
            } else {
                types.add(MobileResourceType.INSTANCE.getType());
            }
            shellPropertiesVM.put((Object)"pge-type", (Object)types.toArray(new String[types.size()]));
            if (StringUtils.isNotEmpty((CharSequence)appDescription)) {
                shellPropertiesVM.put((Object)"jcr:description", (Object)appDescription);
            }
            if (StringUtils.isNotBlank((CharSequence)appDashboard)) {
                shellPropertiesVM.put((Object)"pge-dashboard-config", (Object)appDashboard);
            }
        }
        Session session = (Session)request.getResourceResolver().adaptTo(Session.class);
        String title = i18n.get("App created");
        String message = i18n.get("Your App has been created.");
        if (subFolders != null && subFolders.length > 0) {
            for (String nextFolder : subFolders) {
                String[] parts = nextFolder.split(";");
                if (parts.length != 2) continue;
                try {
                    JcrUtil.createPath((String)(groupPage.getPath() + "/" + parts[1]), (String)parts[0], (Session)session);
                    continue;
                }
                catch (RepositoryException repEx) {
                    message = i18n.get("Unable to create {}", groupPage.getPath() + "/" + parts[1]);
                }
            }
        }
        String openUrl = request.getContextPath() + "/libs/mobileapps/admin/content/dashboard.html" + shellPage.getPath();
        response.addLink("cq-apps-admin-createapp-edit", this.xssAPI.getValidHref(openUrl), i18n.get("Manage App"));
        try {
            session.save();
        }
        catch (Exception ex) {
            message = i18n.get("Error saving extra properties on {0}", "Path to Page", new Object[]{shellPage.getPath()});
            throw new MobileOperationException(message);
        }
        modifications.add(new Modification(ModificationType.CREATE, groupPage.getPath(), groupPage.getPath()));
        String redirectTo = this.getRedirect(request);
        if (StringUtils.isBlank((CharSequence)redirectTo)) {
            redirectTo = "/aem/apps.html" + Text.escapePath((String)parentPath);
        }
        this.generateResponse(response, 201, message, title, redirectTo, i18n.get("Done"));
        return groupPage;
    }

    private void addAdditionalInformation(ModifiableValueMap mvp, SlingHttpServletRequest request) {
        if (mvp == null) {
            return;
        }
        for (Map.Entry parameter : request.getRequestParameterMap().entrySet()) {
            if (!((String)parameter.getKey()).startsWith("app/")) continue;
            String realKey = ((String)parameter.getKey()).substring(4);
            for (int i = 0; i < ((RequestParameter[])parameter.getValue()).length; ++i) {
                try {
                    String value = ((RequestParameter[])parameter.getValue())[i].getString("utf-8");
                    if (StringUtils.isEmpty((CharSequence)value)) continue;
                    mvp.put((Object)realKey, (Object)value);
                    continue;
                }
                catch (UnsupportedEncodingException encodingEx) {
                    LOGGER.warn("Error with encoding utf-8 string: " + realKey, (Throwable)encodingEx);
                }
            }
        }
    }
}