ProjectServletUtil.java 19.3 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.cq.projects.api.Project
 *  com.adobe.granite.asset.api.Asset
 *  com.adobe.granite.security.user.UserProperties
 *  com.adobe.granite.workflow.WorkflowException
 *  com.adobe.granite.workflow.WorkflowSession
 *  com.adobe.granite.workflow.exec.Workflow
 *  com.day.cq.i18n.I18n
 *  javax.jcr.RepositoryException
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.commons.lang.StringUtils
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.request.RequestParameter
 *  org.apache.sling.api.resource.ModifiableValueMap
 *  org.apache.sling.api.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.projects.impl.servlet;

import com.adobe.cq.projects.api.Project;
import com.adobe.cq.projects.impl.servlet.ListItem;
import com.adobe.cq.projects.impl.servlet.WorkflowListItem;
import com.adobe.cq.projects.impl.team.TeamException;
import com.adobe.cq.projects.impl.util.ProjectUtils;
import com.adobe.granite.asset.api.Asset;
import com.adobe.granite.security.user.UserProperties;
import com.adobe.granite.workflow.WorkflowException;
import com.adobe.granite.workflow.WorkflowSession;
import com.adobe.granite.workflow.exec.Workflow;
import com.day.cq.i18n.I18n;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ProjectServletUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectServletUtil.class);
    static final String OPERATION_ADD_LINK = "addLink";
    static final String OPERATION_ADD_EXTERNAL_LINK = "addExternalLink";
    static final String OPERATION_ADD_GADGET = "addGadget";
    static final String OPERATION_DELETE_LINK = "deleteLink";
    static final String OPERATION_UPDATE_PROJECT = "updateProject";
    static final String OPERATION_CREATE = "projectcreate";
    static final String OPERATION_DELETE = "projectdelete";
    static final String OPERATION_UPDATE_TEAM = "updateTeam";
    static final String OPERATION_START_WORKFLOW = "startWorkflow";
    static final String OPERATION_ADD_TASK = "addTask";
    static final String OPERATION_DELETE_EXPERIENCE = "deleteExperience";
    static final String OPERATION_ADD_EXPERIENCE = "addExperience";
    static final String OPERATION_GRANITE_COMMENT = "granite:comment";
    static final String OPERATION_CREATE_PROJECT_PACKAGE = "createProjectPackage";
    static final String OPERATION_PROJECTS_CREATEFOLDER = "projects:createfolder";
    static final String OPERATION_PROJECTS_DELETEFOLDER = "projects:deletefolder";
    static final String PARAMETER_PATH = "path";
    static final String PARAMETER_THUMBNAIL = "coverImage";
    static final String PARAMETER_TEAM_MEMBER_USER_ID = "teamMemberUserId";
    static final String PARAMETER_TEAM_MEMBER_ROLE_ID = "teamMemberRoleId";
    static final String PARAMETER_WORKFLOW_MODEL_ID = "modelId";
    static final String PARAMETER_WORKFLOW_TITLE = "workflowTitle";
    static final String PARAMETER_WIZRD = "wizard";
    static final String PARAMETER_ASSIGNEE = "assignee";
    static final String WORK_NODE = "work";
    static final String TASKS_NODE = "tasks";
    static final String TASKS_LINK_NODE = "taskslink";
    static final String TASKS_LINK_RESOURCE_TYPE = "cq/gui/components/projects/admin/pod/taskpod";
    static final String TP_ASSIGNEE = "assignee";
    static final String TP_TASK_PRIORITY = "taskPriority";
    static final String TP_TASK_SLING_RSC = "sling:resourceType";
    static final String TP_TASK_DUE_DATE = "taskDueDate";
    static final String TP_CONTENT_PATH = "contentPath";
    static final String TP_NAME = "name";
    static final String TP_DESCRIPTION = "description";
    static final String TP_SEND_EMAIL_NOTIFICATION = "sendEmailNotification";
    static final String TP_PROJECT_PATH = "projectPath";
    static final String LP_LINK_TYPE = "linkType";
    static final String LP_LINK_CONSOLE = "linkConsolePath";
    static final String LP_LINK_SUFFIX = "linkSuffix";
    private static final Set<String> DefaultParameters = new HashSet<String>(Arrays.asList("project.dueDate", "jcr:description", "name", "template", "jcr:title", "active", "teamMemberRoleId", "teamMemberUserId", "coverImage", "assignee", "wizard", "damFolderPath", "coverUrl", "parentPath", "detailsHref"));
    static final String DEFAULT_USER_ICON = "/libs/granite/security/clientlib/themes/default/resources/sample-user-thumbnail.36.png";
    static final String DEFAULT_GROUP_ICON = "/libs/granite/security/clientlib/themes/default/resources/sample-group-thumbnail.36.png";

    private ProjectServletUtil() {
    }

    public static void updateProjectCover(SlingHttpServletRequest request, Project project) throws IOException {
        RequestParameter thumbnailParameter = request.getRequestParameter("coverImage");
        if (thumbnailParameter != null && thumbnailParameter.getSize() > 0) {
            String mimeType = thumbnailParameter.getContentType();
            InputStream thumbnailStream = thumbnailParameter.getInputStream();
            project.setProjectCover(mimeType, thumbnailStream);
        }
    }

    public static Resource getOrCreateTasksFolder(SlingHttpServletRequest request, Resource projectResource) throws PersistenceException {
        Resource projectContent = projectResource.getChild("jcr:content");
        Resource tasksNode = projectContent.getChild("tasks");
        if (tasksNode == null) {
            tasksNode = request.getResourceResolver().create(projectContent, "tasks", null);
            ProjectServletUtil.addTaskPod(request, projectResource);
            ModifiableValueMap valueMap = (ModifiableValueMap)projectContent.adaptTo(ModifiableValueMap.class);
            valueMap.put((Object)"tasks.folder", (Object)tasksNode.getName());
        }
        return tasksNode;
    }

    private static void addTaskPod(SlingHttpServletRequest request, Resource projectResource) throws PersistenceException {
        Resource gadgetsResource = ProjectUtils.getOrCreateGadgetFolder(projectResource);
        if (!ProjectServletUtil.hasTaskPod(gadgetsResource)) {
            Map<String, Object> gadgetDefinition = ProjectServletUtil.findTaskGadgetDefinition(projectResource.getResourceResolver());
            if (gadgetDefinition == null) {
                HashMap<String, String> properties = new HashMap<String, String>(2);
                properties.put("sling:resourceType", "cq/gui/components/projects/admin/pod/taskpod");
                properties.put("cardWeight", "70");
                request.getResourceResolver().create(gadgetsResource, "taskslink", properties);
            } else {
                request.getResourceResolver().create(gadgetsResource, "taskslink", gadgetDefinition);
            }
        }
    }

    private static Map<String, Object> findTaskGadgetDefinition(ResourceResolver resourceResolver) {
        Resource globalGadgets;
        if (resourceResolver != null && (globalGadgets = resourceResolver.getResource("/etc/projects/dashboard/gadgets")) != null) {
            Iterable gadgetsIterable = globalGadgets.getChildren();
            for (Resource gadget : gadgetsIterable) {
                Resource jcrContent = gadget.getChild("jcr:content");
                if (!gadget.isResourceType("cq/gui/components/projects/admin/pod/taskpod") && (jcrContent == null || !jcrContent.isResourceType("cq/gui/components/projects/admin/pod/taskpod"))) continue;
                HashMap<String, Object> result = new HashMap<String, Object>();
                ValueMap gadgetMap = (ValueMap)gadget.adaptTo(ValueMap.class);
                ValueMap contentMap = (ValueMap)jcrContent.adaptTo(ValueMap.class);
                result.put("type", gadgetMap.get("type", String.class));
                result.put("allow", gadgetMap.get("allow", String.class));
                result.put("cardWeight", contentMap.get("cardWeight", String.class));
                result.put("jcr:description", contentMap.get("jcr:description", String.class));
                result.put("jcr:title", contentMap.get("jcr:title", String.class));
                result.put("sling:resourceType", contentMap.get("sling:resourceType", String.class));
                return result;
            }
        }
        return null;
    }

    private static boolean hasTaskPod(Resource gadgetsResource) {
        Iterable children = gadgetsResource.getChildren();
        if (children != null) {
            for (Resource child : children) {
                if (child.isResourceType("cq/gui/components/projects/admin/pod/taskpod")) {
                    return true;
                }
                Resource jcrContentResource = child.getChild("jcr:content");
                if (jcrContentResource == null || !jcrContentResource.isResourceType("cq/gui/components/projects/admin/pod/taskpod")) continue;
                return true;
            }
        }
        return false;
    }

    public static void updateProjectTeam(SlingHttpServletRequest request, Project project) throws TeamException {
        String[] teamMemberUserIds = request.getParameterValues("teamMemberUserId");
        String[] teamMemberRoleIds = request.getParameterValues("teamMemberRoleId");
        if (teamMemberUserIds == null || teamMemberRoleIds == null) {
            throw new TeamException(I18n.get((HttpServletRequest)request, (String)"Team members and their roles must be specified"));
        }
        ProjectServletUtil.updateProjectTeam(project, teamMemberUserIds, teamMemberRoleIds);
    }

    public static void updateProjectTeam(Project project, String[] teamMemberUserIds, String[] teamMemberRoleIds) {
        List<String> userIds = Arrays.asList(teamMemberUserIds);
        List<String> roleIds = Arrays.asList(teamMemberRoleIds);
        project.updateMembers(userIds, roleIds);
    }

    public static boolean isAsset(ResourceResolver resourceResolver, String resourcePath) {
        if (org.apache.commons.lang3.StringUtils.isBlank((CharSequence)resourcePath)) {
            return false;
        }
        Resource resource = resourceResolver.getResource(resourcePath);
        if (resource != null) {
            return resource.adaptTo(Asset.class) != null;
        }
        return false;
    }

    public static Calendar parseDate(String dueDateString) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Date dueDate = formatter.parse(dueDateString);
        Calendar cal = null;
        if (dueDate != null) {
            cal = Calendar.getInstance();
            cal.setTime(dueDate);
        }
        return cal;
    }

    public static String getProjectDetailsUrl(Resource resource) {
        String detailsHref;
        ValueMap map;
        Resource content = resource.getChild("jcr:content");
        if (content != null && org.apache.commons.lang3.StringUtils.isNotEmpty((CharSequence)(detailsHref = (String)(map = (ValueMap)content.adaptTo(ValueMap.class)).get("detailsHref", String.class)))) {
            return detailsHref;
        }
        return "/projects/details.html";
    }

    public static Resource getOrCreateWorkFolder(Project project) throws PersistenceException {
        Resource projectResource = (Resource)project.adaptTo(Resource.class);
        Resource workResource = projectResource.getChild("jcr:content/work");
        if (workResource == null) {
            Resource projectContent = projectResource.getChild("jcr:content");
            workResource = projectResource.getResourceResolver().create(projectContent, "work", null);
            ModifiableValueMap valueMap = (ModifiableValueMap)projectContent.adaptTo(ModifiableValueMap.class);
            valueMap.put((Object)"work.folder", (Object)workResource.getName());
        }
        return workResource;
    }

    static Map<String, Object> convertParameterMap(SlingHttpServletRequest request, Map existingValues) {
        HashMap<String, Object> parameterMap = existingValues != null ? existingValues : new HashMap<String, Object>();
        String dueDateParameter = request.getParameter("project.dueDate");
        if (org.apache.commons.lang3.StringUtils.isNotBlank((CharSequence)dueDateParameter)) {
            try {
                Calendar dueDate = ProjectServletUtil.parseDate(dueDateParameter);
                parameterMap.put("project.dueDate", dueDate);
            }
            catch (ParseException e) {
                LOGGER.info("invalid due date on project: " + dueDateParameter);
            }
        } else {
            parameterMap.remove("project.dueDate");
        }
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = (String)parameterNames.nextElement();
            if (ProjectServletUtil.includeParameter(parameterName)) {
                String[] parameterValues = request.getParameterValues(parameterName);
                if (parameterValues != null) {
                    if (parameterValues.length == 1) {
                        if (parameterMap.containsKey(parameterName) && parameterMap.get(parameterName).getClass().isArray()) {
                            String[] newParameterValues = new String[]{parameterValues[0]};
                            parameterMap.put(parameterName, newParameterValues);
                            continue;
                        }
                        if (parameterValues[0] == null) continue;
                        parameterMap.put(parameterName, parameterValues[0]);
                        continue;
                    }
                    if (parameterMap.containsKey(parameterName) && !parameterMap.get(parameterName).getClass().isArray()) {
                        parameterMap.remove(parameterName);
                    }
                    parameterMap.put(parameterName, parameterValues);
                    continue;
                }
                LOGGER.warn("Null parameter values for parameter {} ?", (Object)parameterName);
                continue;
            }
            String deleteParameter = ProjectServletUtil.isDeleteParameter(parameterName, request.getParameterMap());
            if (deleteParameter == null) continue;
            parameterMap.remove(deleteParameter);
        }
        return parameterMap;
    }

    private static String isDeleteParameter(String parameterName, Map<String, ?> requestParameterMap) {
        if (parameterName != null && parameterName.endsWith("@Delete")) {
            String propName = parameterName.substring(0, parameterName.indexOf("@Delete"));
            if (DefaultParameters.contains(propName)) {
                return null;
            }
            for (String thisParameter : requestParameterMap.keySet()) {
                if (!org.apache.commons.lang3.StringUtils.equals((CharSequence)propName, (CharSequence)thisParameter)) continue;
                return null;
            }
            return propName;
        }
        return null;
    }

    static List<ListItem> loadWork(SlingHttpServletRequest request, String projectPath, String modelPath) throws WorkflowException {
        Resource workNode;
        ArrayList<ListItem> workList = new ArrayList<ListItem>();
        ResourceResolver resourceResolver = request.getResourceResolver();
        WorkflowSession wfSession = (WorkflowSession)resourceResolver.adaptTo(WorkflowSession.class);
        Resource projectContent = resourceResolver.getResource(projectPath + "/" + "jcr:content");
        if (wfSession != null && projectContent != null && (workNode = projectContent.getChild("work")) != null) {
            Iterator allWork = workNode.listChildren();
            while (allWork.hasNext()) {
                String modelId;
                Resource workRef = (Resource)allWork.next();
                ValueMap workRefProps = (ValueMap)workRef.adaptTo(ValueMap.class);
                String workflowId = (String)workRefProps.get("workflow.id", String.class);
                if (workflowId == null || (modelId = (String)workRefProps.get("model.id", String.class)) == null || !StringUtils.isEmpty((String)modelPath) && !modelPath.equals(modelId)) continue;
                WorkflowListItem item = null;
                Workflow workflow = null;
                try {
                    workflow = wfSession.getWorkflow(workflowId);
                    item = new WorkflowListItem(workflow);
                }
                catch (WorkflowException e) {
                    LOGGER.debug("Failed to load workflow for workflowInstanceId '{}'", (Object)workflowId);
                    item = new WorkflowListItem(workflowId);
                }
                workList.add(item);
            }
        }
        Collections.sort(workList, new Comparator<ListItem>(){

            @Override
            public int compare(ListItem lhs, ListItem rhs) {
                if (lhs != null) {
                    return ((WorkflowListItem)lhs).compareStartDates((WorkflowListItem)rhs);
                }
                if (rhs != null) {
                    return -1;
                }
                return 0;
            }
        });
        return workList;
    }

    static String getUserThumbnailPath(Authorizable authorizable, UserProperties userProperties) {
        String image = null;
        try {
            if (authorizable != null && userProperties != null && ((image = userProperties.getResourcePath("photos", "/primary/image.prof.thumbnail.36.png", "")) == null || image.equals(""))) {
                image = authorizable.isGroup() ? "/libs/granite/security/clientlib/themes/default/resources/sample-group-thumbnail.36.png" : "/libs/granite/security/clientlib/themes/default/resources/sample-user-thumbnail.36.png";
            }
        }
        catch (RepositoryException e) {
            // empty catch block
        }
        if (image == null) {
            image = "/libs/granite/security/clientlib/themes/default/resources/sample-user-thumbnail.36.png";
        }
        return image;
    }

    private static boolean includeParameter(String parameterName) {
        if (!(!org.apache.commons.lang3.StringUtils.isNotBlank((CharSequence)parameterName) || parameterName.contains(":") || parameterName.contains("@") || parameterName.startsWith("_") || DefaultParameters.contains(parameterName))) {
            return true;
        }
        return false;
    }

}