CommandLineProcess.java 13.6 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  aQute.bnd.annotation.ProviderType
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.Rendition
 *  com.day.cq.dam.api.handler.AssetHandler
 *  com.day.cq.dam.api.renditions.RenditionMaker
 *  com.day.cq.dam.api.renditions.RenditionTemplate
 *  com.day.cq.dam.api.thumbnail.ThumbnailConfig
 *  com.day.cq.dam.commons.process.AbstractAssetWorkflowProcess
 *  com.day.cq.workflow.WorkflowException
 *  com.day.cq.workflow.WorkflowSession
 *  com.day.cq.workflow.exec.WorkItem
 *  com.day.cq.workflow.metadata.MetaDataMap
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.commons.exec.CommandLine
 *  org.apache.commons.exec.DefaultExecutor
 *  org.apache.commons.io.FileUtils
 *  org.apache.commons.io.IOUtils
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.commons.mime.MimeTypeService
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.dam.core.process;

import aQute.bnd.annotation.ProviderType;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.Rendition;
import com.day.cq.dam.api.handler.AssetHandler;
import com.day.cq.dam.api.renditions.RenditionMaker;
import com.day.cq.dam.api.renditions.RenditionTemplate;
import com.day.cq.dam.api.thumbnail.ThumbnailConfig;
import com.day.cq.dam.commons.process.AbstractAssetWorkflowProcess;
import com.day.cq.dam.core.process.CreateThumbnailProcess;
import com.day.cq.dam.core.process.CreateWebEnabledImageProcess;
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.metadata.MetaDataMap;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.mime.MimeTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=0)
@Service
@Property(name="process.label", value={"Command Line"})
@ProviderType
public class CommandLineProcess
extends AbstractAssetWorkflowProcess {
    private final Logger log;
    @Reference
    RenditionMaker renditionMaker;
    private CreateWebEnabledImageProcess webEnabledImageCreator;

    public CommandLineProcess() {
        this.log = LoggerFactory.getLogger(this.getClass());
        this.webEnabledImageCreator = new CreateWebEnabledImageProcess();
    }

    public void execute(WorkItem workItem, WorkflowSession wfsession, MetaDataMap args) throws WorkflowException {
        block22 : {
            String[] arguments = this.buildArguments(args);
            Asset asset = this.getAssetFromPayload(workItem, wfsession.getSession());
            File tmpDir = null;
            InputStream is = null;
            OutputStream os = null;
            try {
                LinkedList<String> mimeTypes = new LinkedList<String>();
                String assetMimeType = asset.getMimeType();
                for (String str : arguments) {
                    if (!str.startsWith(Arguments.MIME_TYPES.getArgumentPrefix())) continue;
                    String mt = str.substring(Arguments.MIME_TYPES.getArgumentPrefix().length()).trim();
                    this.log.debug("execute: accepted mime type [{}] for asset [{}].", (Object)mt, (Object)asset.getPath());
                    mimeTypes.add(mt);
                }
                if (!mimeTypes.contains(assetMimeType)) {
                    this.log.info("execute: mime type [{}] of asset [{}] is not in list of accepted mime types [" + mimeTypes + "], ignoring.", (Object)assetMimeType, (Object)asset.getPath());
                    return;
                }
                tmpDir = File.createTempFile("cqdam", null);
                tmpDir.delete();
                tmpDir.mkdir();
                if (null == asset) break block22;
                Rendition original = asset.getOriginal();
                final File tmpFile = new File(tmpDir, asset.getName());
                FileOutputStream fos = new FileOutputStream(tmpFile);
                IOUtils.copy((InputStream)original.getStream(), (OutputStream)fos);
                IOUtils.closeQuietly((OutputStream)fos);
                String lastLine = "";
                HashMap<String, String> parameters = new HashMap<String, String>();
                parameters.put("filename", tmpFile.getName());
                parameters.put("file", tmpFile.getAbsolutePath());
                parameters.put("directory", tmpDir.getAbsolutePath());
                parameters.put("basename", tmpFile.getName().replaceFirst("\\..*$", ""));
                parameters.put("extension", tmpFile.getName().replaceFirst("^.*\\.", ""));
                try {
                    for (String argument : arguments) {
                        if (!argument.startsWith(Arguments.COMMANDS.getArgumentPrefix())) continue;
                        String cmd = argument.substring(Arguments.COMMANDS.getArgumentPrefix().length()).trim();
                        CommandLine commandLine = CommandLine.parse((String)cmd, parameters);
                        lastLine = commandLine.toString();
                        DefaultExecutor exec = new DefaultExecutor();
                        exec.setWorkingDirectory(tmpDir);
                        this.log.info("execute: executing command line [{}] for asset [{}].", (Object)lastLine, (Object)asset.getPath());
                        exec.execute(commandLine);
                    }
                }
                catch (Exception e) {
                    this.log.error("execute: failed to execute command [{}] for asset [" + asset.getPath() + "]: ", (Object)lastLine, (Object)e);
                }
                for (String result : tmpDir.listFiles(new FileFilter(){

                    @Override
                    public boolean accept(File pathname) {
                        return !pathname.equals(tmpFile);
                    }
                })) {
                    Rendition rendition = asset.addRendition(result.getName(), (InputStream)new FileInputStream((File)((Object)result)), this.recheck(result.getName()));
                    HashSet<ThumbnailConfig> thumbnailConfigs = new HashSet<ThumbnailConfig>();
                    for (String str2 : arguments) {
                        int indexOf = str2.indexOf(Arguments.THUMBNAILS.getArgumentPrefix());
                        if (indexOf <= -1) continue;
                        ThumbnailConfig config = CreateThumbnailProcess.parseThumbnailArguments(str2.substring(indexOf + Arguments.THUMBNAILS.getArgumentPrefix().length()));
                        if (null != config) {
                            thumbnailConfigs.add(config);
                            this.log.debug("execute: thumbnail dimensions [{}] for asset [{}].", (Object)str2, (Object)asset.getPath());
                            continue;
                        }
                        this.log.error("execute: cannot add invalid thumbnail config [{}] for asset [{}].", (Object)str2, (Object)asset.getPath());
                    }
                    List<RenditionTemplate> templates = this.createRenditionTemplates(rendition, thumbnailConfigs.toArray((T[])new ThumbnailConfig[0]));
                    this.log.debug("thumbnail template created at [{}] with [{}] thumbnails for [" + asset.getPath() + "].", (Object)rendition.getPath(), (Object)templates.size());
                    Boolean createWebRend = (Boolean)args.get(Arguments.GENERATE_WEB_RENDITION.name(), Boolean.class);
                    if (createWebRend != null && createWebRend.booleanValue()) {
                        CreateWebEnabledImageProcess.Config config = this.webEnabledImageCreator.parseConfig(args);
                        RenditionTemplate webRendTemp = this.renditionMaker.createWebRenditionTemplate(rendition, config.width, config.height, config.quality, config.mimeType, config.mimeTypesToKeep);
                        templates.add(webRendTemp);
                        this.log.debug("Web rendition template created at [{}] with [{}] thumbnails for [" + asset.getPath() + "].", (Object)rendition.getPath());
                    }
                    this.renditionMaker.generateRenditions(asset, templates.toArray((T[])new RenditionTemplate[0]));
                    Boolean delCommRend = (Boolean)args.get(Arguments.DELETE_COMMAND_RENDITION.name(), Boolean.class);
                    if (delCommRend == null || !delCommRend.booleanValue()) continue;
                    asset.removeRendition(rendition.getName());
                }
            }
            catch (Exception e) {
                throw new WorkflowException((Throwable)e);
            }
            finally {
                IOUtils.closeQuietly((InputStream)is);
                IOUtils.closeQuietly((OutputStream)os);
                if (tmpDir != null) {
                    try {
                        FileUtils.deleteDirectory((File)tmpDir);
                    }
                    catch (IOException e) {
                        throw new WorkflowException((Throwable)e);
                    }
                }
            }
        }
    }

    protected void createThumbnails(Asset asset, Rendition rendition, Collection<ThumbnailConfig> configs) throws Exception {
        String mimeType = rendition.getMimeType();
        AssetHandler handler = this.getAssetHandler(mimeType);
        if (handler == null) {
            throw new IOException("No AssetHandler found for mimetype " + mimeType);
        }
        this.log.debug("createThumbnails: generating thumbnails for rendition [{}] with mime type [{}]...", (Object)asset.getPath(), (Object)mimeType);
        handler.createThumbnails(asset, rendition, configs);
    }

    protected String recheck(String fileName) throws RepositoryException {
        if (this.mimeTypeService.getMimeType(fileName.toLowerCase()) != null) {
            return this.mimeTypeService.getMimeType(fileName.toLowerCase());
        }
        return "application/octet-stream";
    }

    public String[] buildArguments(MetaDataMap metaData) {
        String[] mimetypes;
        String[] thumbnails;
        String processArgs = (String)metaData.get(Arguments.PROCESS_ARGS.name(), String.class);
        if (processArgs != null && !processArgs.equals("")) {
            return processArgs.split(",");
        }
        ArrayList<String> arguments = new ArrayList<String>();
        String[] commands = (String[])metaData.get(Arguments.COMMANDS.name(), String[].class);
        if (commands != null) {
            for (String command : commands) {
                StringBuilder builder = new StringBuilder();
                builder.append(Arguments.COMMANDS.getArgumentPrefix()).append(command);
                arguments.add(builder.toString());
            }
        }
        if ((mimetypes = (String[])metaData.get(Arguments.MIME_TYPES.name(), String[].class)) != null) {
            for (String mimetype : mimetypes) {
                StringBuilder builder = new StringBuilder();
                builder.append(Arguments.MIME_TYPES.getArgumentPrefix()).append(mimetype);
                arguments.add(builder.toString());
            }
        }
        if ((thumbnails = (String[])metaData.get(Arguments.THUMBNAILS.name(), String[].class)) != null) {
            for (String thumbnail : thumbnails) {
                StringBuilder builder = new StringBuilder();
                builder.append(Arguments.THUMBNAILS.getArgumentPrefix()).append(thumbnail);
                arguments.add(builder.toString());
            }
        }
        return arguments.toArray(new String[arguments.size()]);
    }

    private List<RenditionTemplate> createRenditionTemplates(Rendition rendition, ThumbnailConfig[] thumbnails) {
        ArrayList<RenditionTemplate> templates = new ArrayList<RenditionTemplate>(thumbnails.length);
        for (int i = 0; i < thumbnails.length; ++i) {
            ThumbnailConfig thumb = thumbnails[i];
            templates.add(this.renditionMaker.createThumbnailTemplate(rendition, thumb.getWidth(), thumb.getHeight(), thumb.doCenter()));
        }
        return templates;
    }

    protected void bindRenditionMaker(RenditionMaker renditionMaker) {
        this.renditionMaker = renditionMaker;
    }

    protected void unbindRenditionMaker(RenditionMaker renditionMaker) {
        if (this.renditionMaker == renditionMaker) {
            this.renditionMaker = null;
        }
    }

    public static enum Arguments {
        PROCESS_ARGS("PROCESS_ARGS"),
        MIME_TYPES("mime"),
        THUMBNAILS("tn"),
        COMMANDS("cmd"),
        GENERATE_WEB_RENDITION("genWebRendition"),
        DELETE_COMMAND_RENDITION("deleteCommandRendition");
        
        private String argumentName;

        private Arguments(String argumentName) {
            this.argumentName = argumentName;
        }

        public String getArgumentName() {
            return this.argumentName;
        }

        public String getArgumentPrefix() {
            return this.argumentName + ":";
        }
    }

}