DPSUtil.java 15.6 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.dps.client.producer.EntityType
 *  com.day.cq.commons.inherit.InheritanceValueMap
 *  com.day.cq.commons.jcr.JcrUtil
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  javax.jcr.Binary
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.ValueFactory
 *  javax.servlet.ServletOutputStream
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.commons.io.IOUtils
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.request.RequestPathInfo
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.mobile.dps.impl.utils;

import com.adobe.cq.mobile.dps.DPSArticle;
import com.adobe.cq.mobile.dps.DPSBanner;
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.DPSObject;
import com.adobe.cq.mobile.dps.DPSProject;
import com.adobe.cq.mobile.dps.impl.export.ExportOptions;
import com.adobe.dps.client.producer.EntityType;
import com.day.cq.commons.inherit.InheritanceValueMap;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DPSUtil {
    private static final String DPS_METADATA_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    private static final String LINE_SEP = System.getProperty("line.separator");
    private static final Logger LOGGER = LoggerFactory.getLogger(DPSUtil.class);

    public static boolean isADPSResource(Node currentNode) throws RepositoryException {
        return DPSUtil.getDPSResourceType(currentNode) != null;
    }

    public static boolean isADPSResource(Page currentPage) {
        return DPSUtil.getDPSResourceType(currentPage) != null;
    }

    public static String getDPSResourceType(Page page) {
        String dpsResourceType = null;
        if (page != null) {
            dpsResourceType = (String)page.getProperties().get("dps-resourceType", String.class);
        }
        return dpsResourceType;
    }

    public static String getDPSResourceType(Node currentNode) throws RepositoryException {
        Node contentNode;
        boolean hasDPSResourceTypeProp;
        String dpsResourceType = null;
        boolean hasContentNode = currentNode.hasNode("jcr:content");
        if (hasContentNode && (hasDPSResourceTypeProp = (contentNode = currentNode.getNode("jcr:content")).hasProperty("dps-resourceType"))) {
            dpsResourceType = contentNode.getProperty("dps-resourceType").getString();
        }
        return dpsResourceType;
    }

    public static Node getDPSFolioRefNode(Node currentNode) throws RepositoryException {
        Node issueNode = null;
        if (currentNode.getDepth() > 0) {
            String type = DPSUtil.getDPSResourceType(currentNode);
            if (type != null && type.equals("dps:Project")) {
                issueNode = currentNode;
            }
            if (issueNode == null) {
                issueNode = DPSUtil.getDPSFolioRefNode(currentNode.getParent());
            }
        }
        return issueNode;
    }

    public static String getProperty(Node node, String propKey, String defaultValue) throws RepositoryException, Exception {
        String value = defaultValue;
        if (node.hasProperty(propKey)) {
            value = node.getProperty(propKey).getString();
        } else if (value == null) {
            throw new Exception("Required property '" + propKey + "' not found for: " + (Object)node);
        }
        return value;
    }

    public static String getDateAsDPSString(Date date) {
        String stringDate = "";
        if (date != null) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            stringDate = formatter.format(date);
        }
        return stringDate;
    }

    public static DPSObject getDPSObject(Page page) {
        DPSObject dpsObject = null;
        String resourceType = DPSUtil.getDPSResourceType(page);
        if (resourceType != null) {
            if (resourceType.equals("dps:Project")) {
                dpsObject = (DPSObject)page.adaptTo(DPSProject.class);
            } else if (resourceType.equals("dps:Article")) {
                dpsObject = (DPSObject)page.adaptTo(DPSArticle.class);
            } else if (resourceType.equals("dps:Banner")) {
                dpsObject = (DPSObject)page.adaptTo(DPSBanner.class);
            } else if (resourceType.equals("dps:Collection")) {
                dpsObject = (DPSObject)page.adaptTo(DPSCollection.class);
            }
        }
        return dpsObject;
    }

    public static DPSProject getDPSProject(DPSObject dpsObject) {
        DPSProject project = null;
        if (dpsObject != null) {
            if (dpsObject instanceof DPSProject) {
                project = (DPSProject)dpsObject;
            } else if (dpsObject instanceof DPSEntity) {
                project = ((DPSEntity)dpsObject).getProject();
            }
        }
        return project;
    }

    public static Configuration getDPSConfiguration(ConfigurationManager configurationManager, String cloudServiceConfigPath) throws RepositoryException {
        if (StringUtils.isEmpty((CharSequence)cloudServiceConfigPath)) {
            LOGGER.debug("Path to cloudServiceConfigPath was null or empty.");
            return null;
        }
        Configuration dpsConfig = null;
        try {
            Configuration config = configurationManager.getConfiguration(cloudServiceConfigPath);
            if (config == null) {
                throw new DPSException("Experience Manager Mobile CloudService configuration is not found at: " + cloudServiceConfigPath);
            }
            String type = (String)config.getProperties().getInherited("sling:resourceType", String.class);
            if (type.endsWith("dps-cloudservice-config")) {
                dpsConfig = config;
            }
        }
        catch (DPSException ex) {
            LOGGER.warn("Failed to get Experience Manager Mobile account configuration", (Throwable)ex);
        }
        return dpsConfig;
    }

    public static boolean isImageSet(Resource imageResource) {
        boolean isImageSet = false;
        if (imageResource != null) {
            if (ResourceUtil.getValueMap((Resource)imageResource).containsKey((Object)"fileReference")) {
                isImageSet = true;
            } else {
                Node imageNode = (Node)imageResource.adaptTo(Node.class);
                try {
                    isImageSet = imageNode.hasNode("./file");
                }
                catch (RepositoryException e) {
                    // empty catch block
                }
            }
        }
        return isImageSet;
    }

    public static Long getJSONDateValue(Date date) {
        return date == null ? null : Long.valueOf(date.getTime());
    }

    public static long sendZip(Session userSession, HttpServletResponse response, String zipPath, String zipName) throws RepositoryException, IOException {
        if (zipName != null) {
            response.setHeader("Content-Disposition", "attachment;filename=" + zipName);
        }
        response.setContentType("application/zip");
        long size = DPSUtil.writeNodeToStream(userSession, (OutputStream)response.getOutputStream(), zipPath);
        response.setContentLength((int)size);
        return size;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static long writeNodeToStream(Session userSession, OutputStream outStream, String path) throws RepositoryException, IOException {
        long size;
        block5 : {
            String binaryDataPath = path + "/jcr:content/jcr:data";
            Binary binary = null;
            InputStream is = null;
            size = 0;
            try {
                if (userSession.itemExists(binaryDataPath)) {
                    binary = userSession.getProperty(binaryDataPath).getBinary();
                    size = binary.getSize();
                    is = binary.getStream();
                    IOUtils.copy((InputStream)is, (OutputStream)outStream);
                    break block5;
                }
                throw new RepositoryException("Content missing: " + binaryDataPath);
            }
            finally {
                IOUtils.closeQuietly((InputStream)is);
                if (binary != null) {
                    binary.dispose();
                }
            }
        }
        return size;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static void writeFileToNode(Session userSession, File file, String path) throws RepositoryException, IOException {
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            JcrUtil.createPath((String)path, (String)"sling:Folder", (String)"nt:file", (Session)userSession, (boolean)false);
            Node contentNode = JcrUtil.createPath((String)(path + "/jcr:content"), (String)"nt:resource", (Session)userSession);
            contentNode.setProperty("jcr:mimeType", "application/zip");
            contentNode.setProperty("jcr:data", userSession.getValueFactory().createBinary((InputStream)fin));
        }
        finally {
            IOUtils.closeQuietly((InputStream)fin);
        }
    }

    public static String getZipName(Page page, ExportOptions exportOptions) {
        String name = null;
        if (exportOptions.getExportMode().equals((Object)ExportOptions.ExportMode.EXPORT_RESOURCES)) {
            name = "HTMLResources.zip";
        } else {
            boolean exportFolio = exportOptions.getExportMode().equals((Object)ExportOptions.ExportMode.EXPORT_ARTICLE);
            if (exportFolio) {
                name = page.getName() + ".folio.zip";
            }
        }
        return name;
    }

    public static final Date getLastModificationDate(DPSProject dpsProject) {
        Date ret = dpsProject.getLastCQModified();
        for (DPSArticle article : dpsProject.getArticles()) {
            Date articleDate = article.getLastCQModified();
            if (ret != null && !ret.before(articleDate)) continue;
            ret = articleDate;
        }
        return ret;
    }

    public static Resource getReferencedResource(SlingHttpServletRequest request) {
        ResourceResolver resolver = request.getResourceResolver();
        Session session = (Session)resolver.adaptTo(Session.class);
        RequestPathInfo requestPathInfo = request.getRequestPathInfo();
        String targetResourceId = requestPathInfo.getSuffix();
        if (targetResourceId == null || targetResourceId.length() == 0) {
            return null;
        }
        targetResourceId = targetResourceId.substring(1);
        Resource targetResource = null;
        try {
            Node targetResourceNode = session.getNodeByIdentifier(targetResourceId);
            if (targetResourceNode != null) {
                targetResource = resolver.getResource(targetResourceNode.getPath());
            }
        }
        catch (RepositoryException e) {
            // empty catch block
        }
        return targetResource;
    }

    public static ResourceResolver getResourceResolver(ResourceResolverFactory resourceResolverFactory, Session session) {
        ResourceResolver resolver = null;
        HashMap<String, Session> authInfo = new HashMap<String, Session>();
        authInfo.put("user.jcr.session", session);
        try {
            resolver = resourceResolverFactory.getResourceResolver(authInfo);
        }
        catch (LoginException ex) {
            LOGGER.error("Unable to obtain the resource resolver", (Throwable)ex);
        }
        return resolver;
    }

    public static String getEntityURI(DPSEntity dpsEntity) {
        return DPSUtil.getEntityURI(dpsEntity.getProjectId(), DPSUtil.getEntityType(dpsEntity), dpsEntity.getEntityName());
    }

    public static String getEntityURI(String publicationId, EntityType entityType, String name) {
        String typeURIName = "article";
        if (entityType.equals((Object)EntityType.COLLECTION)) {
            typeURIName = "collection";
        } else if (entityType.equals((Object)EntityType.BANNER)) {
            typeURIName = "banner";
        } else if (entityType.equals((Object)EntityType.LAYOUT)) {
            typeURIName = "layout";
        }
        return "/publication/" + publicationId + "/" + typeURIName + "/" + name;
    }

    public static EntityType getEntityType(DPSEntity dpsEntity) {
        EntityType entityType = EntityType.ARTICLE;
        if (dpsEntity instanceof DPSCollection) {
            entityType = EntityType.COLLECTION;
        } else if (dpsEntity instanceof DPSBanner) {
            entityType = EntityType.BANNER;
        }
        return entityType;
    }

    public static File createTempFile(String name, String label, String fileExtension) throws IOException {
        String filename = "aem-" + label + "-" + name;
        File file = File.createTempFile(filename, fileExtension);
        LOGGER.debug("Created temp file " + file.getAbsolutePath());
        return file;
    }

    public static String getAndAssertProjectId(DPSObject dpsObject) throws DPSException {
        String projectId = dpsObject.getProjectId();
        if (projectId == null) {
            throw new DPSException("Project not set for " + dpsObject.getPath());
        }
        return projectId;
    }

    public static String getArticleImportRoot(DPSProject dpsProject) {
        return dpsProject.getPath() + "/" + "articles" + "/" + "imported";
    }

    public static String getBannerImportRoot(DPSProject dpsProject) {
        return dpsProject.getPath() + "/" + "banners" + "/" + "imported";
    }

    public static String getCollectionImportRoot(DPSProject dpsProject) {
        return dpsProject.getPath() + "/" + "collections" + "/" + "imported";
    }

    public static String getNestedExceptionMessage(Throwable ex) {
        StringBuffer messageBuf = new StringBuffer();
        messageBuf.append(ex.getMessage());
        if (ex.getCause() != null) {
            messageBuf.append(LINE_SEP);
            messageBuf.append(DPSUtil.getNestedExceptionMessage(ex.getCause()));
        }
        return messageBuf.toString();
    }
}