PIMUtils.java 8.44 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.cq.commerce.api.Product
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.AssetManager
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.commons.io.IOUtils
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.tika.config.TikaConfig
 *  org.apache.tika.detect.Detector
 *  org.apache.tika.io.TikaInputStream
 *  org.apache.tika.metadata.Metadata
 *  org.apache.tika.mime.MediaType
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.dam.pim.impl.util;

import com.adobe.cq.commerce.api.Product;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.AssetManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.io.IOUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PIMUtils {
    private static final Logger log = LoggerFactory.getLogger(PIMUtils.class);
    private static final String DEFAULT_PRODUCT_IMAGE_PATH = "/libs/dam/gui/components/admin/resources/img.png/jcr:content";
    private static Resource DEFAULT_PRODUCT_IMAGE_RESOURCE = null;
    private static String DEFAULT_PRODUCT_IMAGE_MIME_TYPE = "image/png";
    private static InputStream DEFAULT_PRODUCT_IMAGE_STREAM = null;

    public static String getFileNameForProductAsset(String productID) {
        return productID + ".jpg";
    }

    public static String getSKUFromFileName(String fileName) {
        String name = fileName.split("\\.")[0];
        String productID = name.split("_")[0];
        return productID;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static String streamToStr(InputStream inputStream) {
        String line = null;
        StringBuffer sb = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            reader.close();
        }
        catch (Exception e) {}
        finally {
            IOUtils.closeQuietly((InputStream)inputStream);
        }
        return sb.toString();
    }

    public static InputStream strToStream(String s) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(PIMUtils.dumpToTempFile(s.getBytes("UTF-8")));
        }
        catch (Exception e) {
            // empty catch block
        }
        return stream;
    }

    public static String dumpToTempFile(byte[] content) {
        try {
            File f = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".tmp");
            FileOutputStream out = new FileOutputStream(f);
            out.write(content);
            out.close();
            return f.getPath();
        }
        catch (Exception e) {
            return null;
        }
    }

    public static boolean isShotListSibling(Asset asset) {
        Resource res = (Resource)asset.adaptTo(Resource.class);
        String parent = ResourceUtil.getParent((String)asset.getPath());
        return res.getResourceResolver().getResource(parent).getChild("Shot List.csv") != null;
    }

    public static boolean isZipFile(InputStream inputStream) {
        try {
            TikaConfig config = TikaConfig.getDefaultConfig();
            Detector detector = config.getDetector();
            TikaInputStream stream = TikaInputStream.get((InputStream)inputStream);
            Metadata metadata = new Metadata();
            MediaType mediaType = detector.detect((InputStream)stream, metadata);
            return "application/zip".equalsIgnoreCase(mediaType.toString());
        }
        catch (Exception e) {
            log.warn("");
            return false;
        }
    }

    public static Node createApprovedProductAssetNode(ResourceResolver resourceResolver, String path, String id, String productPath) throws Exception {
        DEFAULT_PRODUCT_IMAGE_RESOURCE = resourceResolver.getResource("/libs/dam/gui/components/admin/resources/img.png/jcr:content");
        AssetManager assetManager = (AssetManager)resourceResolver.adaptTo(AssetManager.class);
        PIMUtils.initDefaultProductImageStream();
        Asset asset = assetManager.createAsset(path, DEFAULT_PRODUCT_IMAGE_STREAM, DEFAULT_PRODUCT_IMAGE_MIME_TYPE, true);
        Node node = (Node)asset.adaptTo(Node.class);
        PIMUtils.setMetadata(asset, "dam:productID", id, false);
        PIMUtils.setMetadata(asset, "cq:productReference", productPath, false);
        ((Session)resourceResolver.adaptTo(Session.class)).save();
        return node;
    }

    private static void initDefaultProductImageStream() throws Exception {
        ValueMap valueMap = ResourceUtil.getValueMap((Resource)DEFAULT_PRODUCT_IMAGE_RESOURCE);
        DEFAULT_PRODUCT_IMAGE_STREAM = (InputStream)valueMap.get("jcr:data", InputStream.class);
        DEFAULT_PRODUCT_IMAGE_MIME_TYPE = (String)valueMap.get("jcr:mimeType", String.class);
    }

    public static Iterator<Product> getProducts(Resource resource) {
        List<Product> products = PIMUtils.getProductsList(resource);
        return products.iterator();
    }

    public static List<Product> getProductsList(Resource resource) {
        ArrayList<Product> products = new ArrayList<Product>();
        if (resource.adaptTo(Product.class) != null && !PIMUtils.isVariant(resource)) {
            products.add((Product)resource.adaptTo(Product.class));
        }
        PIMUtils.traverse(resource, products);
        return products;
    }

    private static boolean isVariant(Resource resource) {
        try {
            if (((Node)resource.adaptTo(Node.class)).getProperty("cq:commerceType").getString().equals("variant")) {
                return true;
            }
        }
        catch (RepositoryException e) {
            // empty catch block
        }
        return false;
    }

    private static void traverse(Resource resource, List<Product> products) {
        for (Resource child : resource.getChildren()) {
            if (child.adaptTo(Product.class) != null && !PIMUtils.isVariant(child)) {
                products.add((Product)child.adaptTo(Product.class));
                continue;
            }
            Node node = (Node)child.adaptTo(Node.class);
            if (node == null) continue;
            try {
                if (!node.isNodeType("{http://www.jcp.org/jcr/nt/1.0}folder") && !node.isNodeType("sling:Folder") && !node.isNodeType("sling:OrderedFolder")) continue;
                PIMUtils.traverse(child, products);
            }
            catch (Exception e) {}
        }
    }

    public static void setMetadata(Asset asset, String name, String value, boolean doSave) throws RepositoryException {
        Resource resource = (Resource)asset.adaptTo(Resource.class);
        Resource content = resource.getChild("jcr:content");
        Resource metadata = content.getChild("metadata");
        ((Node)metadata.adaptTo(Node.class)).setProperty(name, value);
        if (doSave) {
            ((Session)resource.getResourceResolver().adaptTo(Session.class)).save();
        }
    }

    public static void setMetadata(Asset asset, String name, String[] values, boolean doSave) throws RepositoryException {
        Resource resource = (Resource)asset.adaptTo(Resource.class);
        Resource content = resource.getChild("jcr:content");
        Resource metadata = content.getChild("metadata");
        ((Node)metadata.adaptTo(Node.class)).setProperty(name, values);
        if (doSave) {
            ((Session)resource.getResourceResolver().adaptTo(Session.class)).save();
        }
    }
}