AbstractAssetHandler.java 15.2 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.asset.api.AssetRelation
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.AssetHandlerException
 *  com.day.cq.dam.api.AssetManager
 *  com.day.cq.dam.api.ProcessorException
 *  com.day.cq.dam.api.Rendition
 *  com.day.cq.dam.api.cache.BufferedImageCache
 *  com.day.cq.dam.api.cache.BufferedImageCache$Entry
 *  com.day.cq.dam.api.handler.AssetHandler
 *  com.day.cq.dam.api.metadata.ExtractedMetadata
 *  com.day.cq.dam.api.thumbnail.ThumbnailConfig
 *  javax.jcr.Binary
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.commons.io.IOUtils
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.jcr.resource.JcrResourceResolverFactory
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.dam.commons.handler;

import com.adobe.granite.asset.api.AssetRelation;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.AssetHandlerException;
import com.day.cq.dam.api.AssetManager;
import com.day.cq.dam.api.ProcessorException;
import com.day.cq.dam.api.Rendition;
import com.day.cq.dam.api.cache.BufferedImageCache;
import com.day.cq.dam.api.handler.AssetHandler;
import com.day.cq.dam.api.metadata.ExtractedMetadata;
import com.day.cq.dam.api.thumbnail.ThumbnailConfig;
import com.day.cq.dam.commons.handler.XMPProcessor;
import com.day.cq.dam.commons.thumbnail.ThumbnailGenerator;
import com.day.cq.dam.commons.util.DamUtil;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
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 org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.jcr.resource.JcrResourceResolverFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(componentAbstract=1, metatype=0)
public abstract class AbstractAssetHandler
implements AssetHandler {
    private static final Logger log = LoggerFactory.getLogger(AbstractAssetHandler.class);
    public static String PROPERTY_DEACTIVATED_MIME_TYPES = "dam.assethandler.deactivateMimeTypes";
    @Reference(policy=ReferencePolicy.STATIC)
    private JcrResourceResolverFactory jcrResolverFactory;
    @Reference(policy=ReferencePolicy.STATIC)
    private BufferedImageCache imageCache;

    public void createThumbnails(Node asset, Node renditionFolder, Session session, List<Integer[]> dimensions) {
        Resource assetResource = this.getResourceResolver(session).getResource(this.safeGetPath(asset));
        if (null != assetResource) {
            Asset a = DamUtil.resolveToAsset(assetResource);
            if (null != a) {
                try {
                    this.createThumbnails(a, ThumbnailGenerator.getConfigs(dimensions));
                }
                catch (IOException e) {
                    log.error("createThumbnails: I/O error while creating thumbnails for [{}]: ", (Object)a.getPath(), (Object)e);
                }
            } else {
                log.error("createThumbnails: could not find asset [{}] to create thumbnails for.", (Object)assetResource.getPath());
            }
        } else {
            log.error("createThumbnails: could not find resource [{}] to create thumbnails for.", (Object)this.safeGetPath(asset));
        }
    }

    public void createThumbnailsExt(Node asset, Node renditionFolder, Session session, List<Map<String, Object>> thumbnailConfigs) throws IOException {
        Resource assetResource = this.getResourceResolver(session).getResource(this.safeGetPath(asset));
        if (null != assetResource) {
            Asset a = DamUtil.resolveToAsset(assetResource);
            if (null != a) {
                try {
                    HashSet<ThumbnailConfig> configs = new HashSet<ThumbnailConfig>();
                    for (Map<String, Object> entry : thumbnailConfigs) {
                        String width = (String)entry.get("width");
                        String height = (String)entry.get("height");
                        String doCenter = (String)entry.get("doCenter");
                        String configStr = width + ":" + height + ":" + doCenter;
                        ThumbnailConfig config = ThumbnailGenerator.parseConfig(configStr);
                        if (null != config) {
                            configs.add(config);
                            continue;
                        }
                        log.error("createThumbnailsExt: cannot add invalid thumbnail config [{}] for asset [{}]", (Object)configStr, (Object)this.safeGetPath(asset));
                    }
                    this.createThumbnails(a, configs);
                }
                catch (IOException e) {
                    log.error("createThumbnails: I/O error while creating thumbnails for [{}]: ", (Object)a.getPath(), (Object)e);
                }
            } else {
                log.error("createThumbnails: could not find asset [{}] to create thumbnails for.", (Object)assetResource.getPath());
            }
        } else {
            log.error("createThumbnails: could not find resource [{}] to create thumbnails for.", (Object)this.safeGetPath(asset));
        }
    }

    public void createThumbnails(Asset asset, Collection<ThumbnailConfig> configs) throws IOException {
        this.createThumbnails(asset, asset.getOriginal(), configs);
    }

    public void createThumbnails(Asset asset) throws IOException {
        this.createThumbnails(asset, asset.getOriginal(), this.getThumbnailConfigs(asset));
    }

    public void createThumbnails(Asset asset, Rendition rendition, Collection<ThumbnailConfig> configs) throws IOException {
        block8 : {
            if (rendition == null) {
                throw new IOException("cannot create  thumbnail for for asset [" + asset.getPath() + "]: " + "rendition doesn't exist.");
            }
            BufferedImageCache.Entry image = this.imageCache.getImage(rendition, (AssetHandler)this);
            try {
                if (image != null && image.getImage() != null) {
                    ThumbnailGenerator generator = new ThumbnailGenerator(asset, image.getImage());
                    generator.generate(configs);
                    break block8;
                }
                log.error("createThumbnails: cannot create thumbnails for asset [{}], failed loading graphical representation for rendition [{}].", (Object)asset.getPath(), (Object)rendition.getPath());
            }
            catch (RepositoryException re) {
                throw new IOException("createThumbnails: error while storing thumbnail(s) for asset [" + asset.getPath() + "]: ");
            }
            finally {
                if (image != null) {
                    image.release();
                }
            }
        }
    }

    public boolean canHandleSubAssets() {
        return false;
    }

    public List<String> processSubAssets(Node asset, Session session) {
        log.debug("processSubAssets: no subassets to process for asset [{}].", (Object)this.safeGetPath(asset));
        return new ArrayList<String>();
    }

    public List<String> processSubAssets(Asset asset) {
        log.debug("processSubAssets: no subassets to process for asset [{}].", (Object)asset.getPath());
        return new ArrayList<String>();
    }

    public Iterator<? extends AssetRelation> processRelated(Asset asset) {
        log.debug("processReferences: no references to process for asset [{}].", (Object)asset.getPath());
        return Collections.emptyList().iterator();
    }

    public BufferedImage getImage(Rendition rendition) throws IOException {
        return null;
    }

    public BufferedImage getImage(Rendition rendition, Dimension maxDimension) throws IOException {
        return this.getImage(rendition);
    }

    public void exportAsset(Node asset, OutputStream stream) throws AssetHandlerException {
        try {
            Resource assetResource = this.getResourceResolver(asset.getSession()).getResource(this.safeGetPath(asset));
            if (null != assetResource) {
                Asset a = DamUtil.resolveToAsset(assetResource);
                if (null != a) {
                    this.exportAsset(a, stream);
                } else {
                    log.error("exportAsset: cannot export, asset [{}] doesn't exist.", (Object)this.safeGetPath(asset));
                }
            }
        }
        catch (Exception e) {
            throw new AssetHandlerException("Cannot export asset: " + e.getMessage(), (Throwable)e);
        }
    }

    public void exportAsset(Asset asset, OutputStream stream) throws AssetHandlerException {
        try {
            InputStream is = asset.getOriginal().getStream();
            IOUtils.copy((InputStream)is, (OutputStream)stream);
            is.close();
        }
        catch (Exception e) {
            throw new AssetHandlerException("Cannot export asset: " + e.getMessage(), (Throwable)e);
        }
    }

    public ExtractedMetadata extractMetadata(Node asset) {
        try {
            Asset a;
            Resource assetResource = this.getResourceResolver(asset.getSession()).getResource(this.safeGetPath(asset));
            if (null != assetResource && null != (a = (Asset)assetResource.adaptTo(Asset.class))) {
                return this.extractMetadata(a);
            }
        }
        catch (RepositoryException e) {
            log.error("extractMetadata: error while extracting metadata for asset [{}]: ", (Object)this.safeGetPath(asset), (Object)e);
        }
        return null;
    }

    public BufferedImage getImage(Node file) throws IOException {
        return null;
    }

    protected BufferedImage getThumbnailImage(Node asset) {
        try {
            Resource resource = this.getResourceResolver(asset.getSession()).getResource(this.safeGetPath(asset));
            if (null != resource) {
                Rendition rendition = null;
                if (DamUtil.isAsset(resource)) {
                    rendition = ((Asset)resource.adaptTo(Asset.class)).getOriginal();
                } else if (DamUtil.isRendition(resource)) {
                    rendition = (Rendition)resource.adaptTo(Rendition.class);
                }
                if (null != rendition) {
                    return this.getImage(rendition);
                }
                log.error("getThumbnailImage: could not get image, resource [{}] doesn't exist.", (Object)this.safeGetPath(asset));
            }
        }
        catch (RepositoryException e) {
            log.error("getThumbnailImage: error while access repository: ", (Throwable)e);
        }
        catch (IOException e) {
            log.error("getThumbnailImage: I/O error: ", (Throwable)e);
        }
        return null;
    }

    protected ResourceResolver getResourceResolver(Session session) {
        return this.jcrResolverFactory.getResourceResolver(session);
    }

    protected AssetManager getAssetManager(Session session) {
        return (AssetManager)this.getResourceResolver(session).adaptTo(AssetManager.class);
    }

    protected InputStream getInputStream(Node file) {
        try {
            String dataPath;
            String string = dataPath = file.isNodeType("dam:Asset") ? "jcr:content/renditions/original/jcr:content/jcr:data" : "jcr:content/jcr:data";
            if (file.hasProperty(dataPath)) {
                return file.getProperty(dataPath).getBinary().getStream();
            }
        }
        catch (RepositoryException e) {
            log.warn("getInputStream: repository error while getting stream for file [{}]: ", (Object)this.safeGetPath(file), (Object)e);
        }
        return new ByteArrayInputStream(new byte[0]);
    }

    protected void setMimetype(ExtractedMetadata metadata, Asset asset) {
        Rendition original = asset.getOriginal();
        if (original != null) {
            metadata.setMetaDataProperty("dc:format", (Object)original.getMimeType());
        }
    }

    protected String safeGetPath(Node node) {
        try {
            return node.getPath();
        }
        catch (RepositoryException e) {
            log.warn("safeGetPath: error while getting path from node: ", (Throwable)e);
            return "(unknown)";
        }
    }

    protected Collection<ThumbnailConfig> getThumbnailConfigs(Asset asset) {
        HashSet<ThumbnailConfig> set = new HashSet<ThumbnailConfig>();
        List renditions = asset.getRenditions();
        for (Rendition rendition : renditions) {
            String name = rendition.getName();
            if (!name.startsWith("cq5dam.thumbnail.")) continue;
            String[] fragments = name.split("\\.");
            String width = fragments[2];
            String height = fragments[3];
            String configStr = width + ":" + height + ":true";
            ThumbnailConfig config = ThumbnailGenerator.parseConfig(configStr);
            if (null != config) {
                set.add(config);
                continue;
            }
            log.error("getThumbnailConfigs: cannot add invalid config [{}] for asset [{}].", (Object)configStr, (Object)asset.getPath());
        }
        return set;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void execGenericProcessor(InputStream is, ExtractedMetadata metadata) {
        try {
            InputStream xmp = XMPProcessor.process(is);
            if (xmp != null) {
                metadata.setXmp(xmp);
            }
        }
        catch (IOException e) {
            log.error("I/O error while getting metadata", (Throwable)e);
        }
        catch (ProcessorException e) {
            log.error("Failed to extract metadata : {}", (Object)e.getMessage());
            if (log.isDebugEnabled()) {
                log.debug("Stack trace.", (Throwable)e);
            }
        }
        finally {
            IOUtils.closeQuietly((InputStream)is);
        }
    }

    protected void bindJcrResolverFactory(JcrResourceResolverFactory jcrResourceResolverFactory) {
        this.jcrResolverFactory = jcrResourceResolverFactory;
    }

    protected void unbindJcrResolverFactory(JcrResourceResolverFactory jcrResourceResolverFactory) {
        if (this.jcrResolverFactory == jcrResourceResolverFactory) {
            this.jcrResolverFactory = null;
        }
    }

    protected void bindImageCache(BufferedImageCache bufferedImageCache) {
        this.imageCache = bufferedImageCache;
    }

    protected void unbindImageCache(BufferedImageCache bufferedImageCache) {
        if (this.imageCache == bufferedImageCache) {
            this.imageCache = null;
        }
    }
}