mitm.common.util.ProcessUtils.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.util.ProcessUtils.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import mitm.common.scheduler.DestroyProcessTimeoutTask;
import mitm.common.scheduler.Task;
import mitm.common.scheduler.TaskScheduler;
import mitm.common.scheduler.ThreadInterruptTimeoutTask;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;

public class ProcessUtils {
    /**
     * Helper method that executes the given cmd and returns the output. The process will be destroyed 
     * if the process takes longer to execute than the timeout.  
     */
    public static String executeCommand(List<String> cmd, long timeout, long maxOutputLength, InputStream input)
            throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        SizeLimitedOutputStream slos = new SizeLimitedOutputStream(bos, maxOutputLength);

        try {
            executeCommand(cmd, timeout, input, slos);

            return MiscStringUtils.toAsciiString(bos.toByteArray());
        } catch (IOException e) {
            throw new IOException(e.getMessage() + ". Output: " + MiscStringUtils.toAsciiString(bos.toByteArray()),
                    e);
        }
    }

    public static String executeCommand(List<String> cmd, long timeout, InputStream input) throws IOException {
        return executeCommand(cmd, timeout, Long.MAX_VALUE, input);
    }

    /**
     * Helper method that executes the given cmd and returns the output. The process will be destroyed 
     * if the process takes longer to execute than the timeout.  
     */
    public static void executeCommand(List<String> cmd, long timeout, InputStream input, OutputStream output)
            throws IOException {
        Check.notNull(cmd, "cmd");

        if (cmd.size() == 0) {
            throw new IOException("Process is missing.");
        }

        /*
         * Used for reporting
         */
        String name = StringUtils.join(cmd, ",");

        /*
         * Watchdog that will be used to destroy the process on a timeout
         */
        TaskScheduler watchdog = new TaskScheduler(ProcessUtils.class.getCanonicalName() + "#" + name);

        try {
            ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();

            /*
             * Task that will destroy the process on a timeout
             */
            Task processWatchdogTask = new DestroyProcessTimeoutTask(process, watchdog.getName());

            watchdog.addTask(processWatchdogTask, timeout);

            /*
             * Task that will interrup the current thread on a timeout
             */
            Task threadInterruptTimeoutTask = new ThreadInterruptTimeoutTask(Thread.currentThread(),
                    watchdog.getName());

            watchdog.addTask(threadInterruptTimeoutTask, timeout);

            /*
             * Send the input to the standard input of the process
             */
            if (input != null) {
                IOUtils.copy(input, process.getOutputStream());

                IOUtils.closeQuietly(process.getOutputStream());
            }

            /*
             * Get the standard output from the process
             */
            if (output != null) {
                IOUtils.copy(process.getInputStream(), output);
            }

            int exitValue;

            try {
                exitValue = process.waitFor();
            } catch (InterruptedException e) {
                throw new IOException("Error executing [" + name + "]", e);
            }

            if (exitValue != 0) {
                throw new ProcessException("Error executing [" + name + "]. exit value: " + exitValue, exitValue);
            }
        } finally {
            /*
             * Need to cancel any pending tasks
             */
            watchdog.cancel();
        }
    }
}