Example usage for org.apache.commons.exec PumpStreamHandler PumpStreamHandler

List of usage examples for org.apache.commons.exec PumpStreamHandler PumpStreamHandler

Introduction

In this page you can find the example usage for org.apache.commons.exec PumpStreamHandler PumpStreamHandler.

Prototype

public PumpStreamHandler(final OutputStream out, final OutputStream err) 

Source Link

Document

Construct a new PumpStreamHandler.

Usage

From source file:org.geoserver.importer.transform.AbstractCommandLineTransform.java

@Override
public void apply(ImportTask task, ImportData data) throws Exception {
    boolean inline = isInline();
    File executable = getExecutable();
    File inputFile = getInputFile(data);
    Map<String, File> substitutions = new HashMap<>();
    substitutions.put("input", inputFile);
    File outputDirectory = null;//from w  w  w . ja v a2 s. c  om
    File outputFile = null;
    if (!inline) {
        outputDirectory = getOutputDirectory(data);
        outputFile = new File(outputDirectory, inputFile.getName());
        substitutions.put("output", outputFile);
    }

    // setup the options
    CommandLine cmd = new CommandLine(executable);
    cmd.setSubstitutionMap(substitutions);

    setupCommandLine(inline, cmd);

    // prepare to run
    DefaultExecutor executor = new DefaultExecutor();
    // make sure we don't try to execute for too much time
    executor.setWatchdog(new ExecuteWatchdog(DEFAULT_TIMEOUT));

    // grab at least some part of the outputs
    int limit = 16 * 1024;
    try {
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            try {
                int result = executor.execute(cmd);

                if (executor.isFailure(result)) {
                    // toString call is routed to ByteArrayOutputStream, which does the right string
                    // conversion
                    throw new IOException(
                            "Failed to execute command " + cmd.toString() + "\nStandard output is:\n"
                                    + os.toString() + "\nStandard error is:\n" + es.toString());
                }
            } catch (Exception e) {
                throw new IOException("Failure to execute command " + cmd.toString() + "\nStandard output is:\n"
                        + os.toString() + "\nStandard error is:\n" + es.toString(), e);
            }
        }

        // if not inline, replace inputs with output
        if (!inline) {
            List<String> names = getReplacementTargetNames(data);
            File inputParent = inputFile.getParentFile();
            for (String name : names) {
                File output = new File(outputDirectory, name);
                File input = new File(inputParent, name);
                if (output.exists()) {
                    // uses atomic rename on *nix, delete and copy on Windows
                    IOUtils.rename(output, input);
                } else if (input.exists()) {
                    input.delete();
                }
            }
        }
    } finally {
        if (outputDirectory != null) {
            FileUtils.deleteQuietly(outputDirectory);
        }
    }
}

From source file:org.jahia.modules.dm.thumbnails.video.impl.VideoThumbnailServiceImpl.java

public boolean generateThumbnail(File videoFile, File outputFile, int offsetSeconds, String size)
        throws DocumentOperationException {
    if (!isEnabled()) {
        logger.info("FFmpeg service is not enabled." + " Skip converting file {}", videoFile);

        return false;
    }/*from  w  ww.ja v  a  2  s. c  o  m*/

    long timer = System.currentTimeMillis();

    CommandLine cmd = getConvertCommandLine(videoFile, outputFile, String.valueOf(offsetSeconds),
            StringUtils.defaultIfEmpty(size, "320x240"));

    if (logger.isDebugEnabled()) {
        logger.debug("Execuiting thumbnail generation command: {}", cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream err = new StringOutputStream();
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(null, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (Exception e) {
        throw new DocumentOperationException(e);
    } finally {
        if (exitValue > 0 && err.getLength() > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled() && err.getLength() > 0) {
            logger.debug(err.toString());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Generating thumbnail {} from {} done (exit code: {}) in {} ms",
                new Object[] { outputFile, videoFile, exitValue, (System.currentTimeMillis() - timer) });
    }

    return exitValue == 0;
}

From source file:org.jahia.modules.dm.viewer.impl.PDF2SWFConverterService.java

public boolean convert(File inputPdfFile, File outputSwfFile) throws DocumentOperationException {
    if (!isEnabled()) {
        logger.info("pdf2swf conversion service is not enabled." + " Skip converting file {}", inputPdfFile);

        return false;
    }/* w ww  . j  av a  2 s  .  co m*/

    long timer = System.currentTimeMillis();

    CommandLine cmd = getConvertCommandLine(inputPdfFile, outputSwfFile);

    if (logger.isDebugEnabled()) {
        logger.debug("Execuiting conversion command: {}", cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream();
    StringOutputStream err = new StringOutputStream();
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (Exception e) {
        throw new DocumentOperationException(e);
    } finally {
        if (err.getLength() > 0) {
            logger.error("Conversion process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled() && out.getLength() > 0) {
            logger.debug(out.toString());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Conversion from {} to {} done (exit code: {}) in {} ms",
                new Object[] { inputPdfFile, outputSwfFile, exitValue, (System.currentTimeMillis() - timer) });
    }

    return exitValue == 0;
}

From source file:org.jahia.services.templates.SourceControlFactory.java

/**
 * Sets the executables for various SCM providers.
 * //w  ww  .j  a v  a  2s .c om
 * @param sourceControlExecutables
 *            a map with paths to SCM executables by SCM type
 */
public void setSourceControlExecutables(Map<String, String> sourceControlExecutables) {
    this.sourceControlExecutables = new HashMap<String, String>();
    for (Map.Entry<String, String> entry : sourceControlExecutables.entrySet()) {
        try {
            DefaultExecutor executor = new DefaultExecutor();
            executor.setStreamHandler(
                    new PumpStreamHandler(new StringOutputStream(), new StringOutputStream()));
            executor.execute(new CommandLine(entry.getValue()), System.getenv());
        } catch (ExecuteException e) {
            // ignore this one as the command always returns error code 1
        } catch (IOException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to execute the " + entry.getKey() + " SCM executable: " + entry.getValue()
                        + ". The SCM provider will be disabled. Cause: " + e.getMessage(), e);
            } else {
                logger.info("Cannot find a valid " + entry.getKey() + " SCM executable at: " + entry.getValue()
                        + ". The SCM provider will be skipped.");
            }
            continue;
        }
        this.sourceControlExecutables.put(entry.getKey(), entry.getValue());
    }
}

From source file:org.jahia.utils.ProcessHelper.java

/**
 * Executes the external process using the provided command, arguments (optional), parameter substitution map to expand variables in the
 * command or arguments in form of <code>${variable}<code> (optional) and a working directory (optional).
 * Buffers for process output and error stream can be provided.
 * /* ww w. j av a 2s .c  om*/
 * @param command
 *            the command to be executed
 * @param arguments
 *            optional arguments for the command
 * @param parameterSubstitutionMap
 *            optional values for variables to be expanded
 * @param workingDir
 *            optional working directory for the process to be started from
 * @param resultOut
 *            the buffer to write the process execution output into (optional)
 * @param resultErr
 *            the buffer to write the process execution error into (optional)
 * @return the execution status
 * @return redirectOutputs if set to <code>true</code> the output of the execution will be also redirected to standard system out and
 *         the error to error out
 * @throws JahiaRuntimeException
 *             in case the process execution failed
 */
public static int execute(String command, String arguments[], Map<String, Object> parameterSubstitutionMap,
        File workingDir, StringBuilder resultOut, StringBuilder resultErr, boolean redirectOutputs)
        throws JahiaRuntimeException {

    long timer = System.currentTimeMillis();

    CommandLine cmd = new CommandLine(command);

    if (arguments != null && arguments.length > 0) {
        cmd.addArguments(arguments, false);
    }

    if (parameterSubstitutionMap != null && !parameterSubstitutionMap.isEmpty()) {
        cmd.setSubstitutionMap(parameterSubstitutionMap);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Executing command: {}", cmd.toString());
    } else if (redirectOutputs) {
        logger.info("Executing command: ");
        logger.info(cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream(redirectOutputs ? System.out : null);
    StringOutputStream err = new StringOutputStream(redirectOutputs ? System.err : null);
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (ExecuteException ee) {
        return ee.getExitValue();
    } catch (Exception e) {
        throw new JahiaRuntimeException(e);
    } finally {
        if (resultErr != null) {
            resultErr.append(err.toString());
        }
        if (resultOut != null) {
            resultOut.append(out.toString());
        }
        if (exitValue > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Execution took {} ms and finished with status {} and output {}",
                    new Object[] { (System.currentTimeMillis() - timer), exitValue, out.toString() });
        }
    }

    return exitValue;
}

From source file:org.jboss.jdocbook.translate.PotSynchronizerImpl.java

private void executeXml2pot(File masterFile, File potFile) {
    CommandLine commandLine = CommandLine.parse("xml2pot");
    commandLine.addArgument(FileUtils.resolveFullPathName(masterFile));

    DefaultExecutor executor = new DefaultExecutor();

    try {//  w  ww  .j  a  v a2s.  com
        final FileOutputStream xmlStream = new FileOutputStream(potFile);
        PumpStreamHandler streamDirector = new PumpStreamHandler(xmlStream, System.err);
        executor.setStreamHandler(streamDirector);
        try {
            log.trace("updating POT file {0}", potFile);
            executor.execute(commandLine);
        } finally {
            try {
                xmlStream.flush();
                xmlStream.close();
            } catch (IOException ignore) {
                // intentionally empty...
            }
        }
    } catch (IOException e) {
        throw new JDocBookProcessException("unable to open output stream for POT file [" + potFile + "]");
    }
}

From source file:org.jboss.jdocbook.translate.TranslatorImpl.java

private void generateTranslatedXML(File masterFile, File poFile, File translatedFile) {
    if (!masterFile.exists()) {
        log.trace("skipping translation; source file did not exist : {}", masterFile);
        return;//from ww w  .ja va2  s .c  om
    }
    if (!poFile.exists()) {
        log.trace("skipping translation; PO file did not exist : {}", poFile);
        return;
    }

    if (translatedFile.exists() && translatedFile.lastModified() >= masterFile.lastModified()
            && translatedFile.lastModified() >= poFile.lastModified()) {
        log.trace("skipping translation; up-to-date : {0}", translatedFile);
        return;
    }

    if (!translatedFile.getParentFile().exists()) {
        boolean created = translatedFile.getParentFile().mkdirs();
        if (!created) {
            log.info("Unable to create directories for translation");
        }
    }

    CommandLine commandLine = CommandLine.parse("po2xml");
    commandLine.addArgument(FileUtils.resolveFullPathName(masterFile));
    commandLine.addArgument(FileUtils.resolveFullPathName(poFile));

    try {
        final FileOutputStream xmlStream = new FileOutputStream(translatedFile);
        DefaultExecutor executor = new DefaultExecutor();
        try {
            PumpStreamHandler streamDirector = new PumpStreamHandler(xmlStream, System.err);
            executor.setStreamHandler(streamDirector);
            executor.execute(commandLine);
        } catch (IOException ioe) {
            throw new JDocBookProcessException("unable to execute po2xml : " + ioe.getMessage());
        } finally {
            try {
                xmlStream.flush();
                xmlStream.close();
            } catch (IOException ignore) {
                // intentionally empty...
            }
        }
    } catch (IOException e) {
        throw new JDocBookProcessException(
                "unable to open output stream for translated XML file [" + translatedFile + "]");
    }
}

From source file:org.jcronjob.agent.AgentProcessor.java

@Override
public Response execute(Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }/*w  w w  . j a  v  a2 s .  c  o m*/

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");

    logger.info("[cronjob]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue = 1;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Response response = Response.response(request);
    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        exitValue = executor.execute(commandLine);
        exitValue = exitValue == null ? 0 : exitValue;
    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = CronJob.StatusCode.ERROR_EXEC.getValue();
        }
        if (exitValue == CronJob.StatusCode.KILL.getValue()) {
            logger.info("[cronjob]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[cronjob]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {
        if (outputStream != null) {
            String text = outputStream.toString();
            if (notEmpty(text)) {
                try {
                    response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                    response.setExitCode(Integer.parseInt(
                            text.substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()));
                } catch (IndexOutOfBoundsException e) {
                    response.setMessage(text);
                    response.setExitCode(exitValue);
                } catch (NumberFormatException e) {
                    response.setExitCode(exitValue);
                }
            } else {
                response.setExitCode(exitValue);
            }
            try {
                outputStream.close();
            } catch (Exception e) {
                logger.error("[cronjob]:error:{}", e);
            }
        } else {
            response.setExitCode(exitValue);
        }
        response.setSuccess(response.getExitCode() == CronJob.StatusCode.SUCCESS_EXIT.getValue()).end();
        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[cronjob]:execute result:{}", response.toString());
    return response;
}

From source file:org.moe.cli.utils.Utils.java

public static String[] execute(File dir, String command, Map<String, String> environment) {

    Map<String, String> current = null;
    try {//  w w  w.  ja va2  s .  co  m
        current = EnvironmentUtils.getProcEnvironment();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    if (environment != null && current != null) {
        current.putAll(environment);
    }

    CommandLine cmdLine = CommandLine.parse(command);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(dir);

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    PumpStreamHandler stHandler = new PumpStreamHandler(stdout, stderr);

    executor.setStreamHandler(stHandler);
    int exitValue = Executor.INVALID_EXITVALUE;

    try {
        exitValue = executor.execute(cmdLine, current);
    } catch (IOException e) {
    }

    return new String[] { stdout.toString(), executor.isFailure(exitValue) ? stderr.toString() : null };
}

From source file:org.ms123.common.management.ManagementServiceImpl.java

private int exec(String line, ByteArrayOutputStream outputStream, ByteArrayOutputStream outputErr,
        int[] exitValues) throws Exception {
    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(exitValues);/*from   ww  w. j  a v a 2s .  c om*/
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputErr);
    executor.setStreamHandler(streamHandler);
    int exitValue = executor.execute(cmdLine);
    return exitValue;
}