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.apache.hcatalog.templeton.ExecServiceImpl.java

private ExecBean auxRun(String program, List<String> args, Map<String, String> env)
        throws NotAuthorizedException, ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);// w  w  w .j  ava  2s .co  m

    // Setup stdout and stderr
    int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1);
    ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes);
    ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes);
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));

    // Only run for N milliseconds
    int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);

    CommandLine cmd = makeCommandLine(program, args);

    LOG.info("Running: " + cmd);
    ExecBean res = new ExecBean();
    res.exitcode = executor.execute(cmd, execEnv(env));
    String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME);
    res.stdout = outStream.toString(enc);
    res.stderr = errStream.toString(enc);

    return res;
}

From source file:org.apache.hive.hcatalog.templeton.StreamOutputWriter.java

private ExecBean auxRun(String program, List<String> args, Map<String, String> env)
        throws NotAuthorizedException, ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);/*  w w  w .java  2  s .c o  m*/

    // Setup stdout and stderr
    int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1);
    ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes);
    ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes);
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));

    // Only run for N milliseconds
    int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);

    CommandLine cmd = makeCommandLine(program, args);

    LOG.info("Running: " + cmd);
    ExecBean res = new ExecBean();

    res.exitcode = executor.execute(cmd, execEnv(env));

    String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME);
    res.stdout = outStream.toString(enc);
    res.stderr = errStream.toString(enc);
    try {
        watchdog.checkException();
    } catch (Exception ex) {
        LOG.error("Command: " + cmd + " failed. res=" + res, ex);
    }
    if (watchdog.killedProcess()) {
        String msg = " was terminated due to timeout(" + timeout + "ms).  See " + AppConfig.EXEC_TIMEOUT_NAME
                + " property";
        LOG.warn("Command: " + cmd + msg + " res=" + res);
        res.stderr += " Command " + msg;
    }
    if (res.exitcode != 0) {
        LOG.info("Command: " + cmd + " failed. res=" + res);
    }
    return res;
}

From source file:org.cloudifysource.shell.commands.TestRecipe.java

/**
 * Execute a command line in with a given map of environment settings. The execution outupt is filtered unless
 * verbose is set to true./*from www. j  av a 2 s  .  com*/
 *
 * @param cmdLine
 *            The command to execute
 * @param env
 *            Environment settings available for the command execution
 * @return the command's execution exit code, or -2 if the command failed to execute
 */
private int executeRecipe(final CommandLine cmdLine, final Map<Object, Object> env) {
    final DefaultExecutor executor = new DefaultExecutor();

    // The watchdog will terminate the process if it does not end within the
    // specified timeout
    final int externalProcessTimeout = (this.timeout + EXTERNAL_PROCESS_WATCHDOG_ADDITIONAL_TIMEOUT) * 1000;
    final ExecuteWatchdog watchdog = new TestRecipeWatchdog(externalProcessTimeout);
    executor.setWatchdog(watchdog);

    executor.setExitValue(0);
    int result = -1;

    PipedInputStream in = null;
    PipedOutputStream out = null;
    BufferedReader reader = null;
    try {
        in = new PipedInputStream();
        out = new PipedOutputStream(in);
        reader = new BufferedReader(new InputStreamReader(in));

        final Thread thread = new Thread(new FilteredOutputHandler(reader, this.verbose));
        thread.setDaemon(true);
        thread.start();

        final PumpStreamHandler psh = new PumpStreamHandler(out, out);
        executor.setStreamHandler(psh);
        result = executor.execute(cmdLine, env);
    } catch (final ExecuteException e) {
        logger.log(Level.SEVERE, "A problem was encountered while executing the recipe: " + e.getMessage(), e);
    } catch (final IOException e) {
        logger.log(Level.SEVERE,
                "An IO Exception was encountered while executing the recipe: " + e.getMessage(), e);
        result = UNEXPECTED_ERROR_EXIT_CODE;
    }

    return result;
}

From source file:org.codehaus.mojo.cassandra.Utils.java

/**
 * Starts the Cassandra server.//from ww  w .  j  a  v a 2  s .  c  o  m
 *
 * @param cassandraDir The directory to start the Server process in.
 * @param commandLine  The command line to use to start the Server process.
 * @param environment  The environment to start the Server process with.
 * @param log          The log to send the output to.
 * @return The {@link ExecuteResultHandler} for the started process.
 * @throws MojoExecutionException if something went wrong.
 */
protected static DefaultExecuteResultHandler startCassandraServer(File cassandraDir, CommandLine commandLine,
        Map environment, Log log) throws MojoExecutionException {

    try {
        Executor exec = new DefaultExecutor();
        DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
        exec.setWorkingDirectory(cassandraDir);
        exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

        LogOutputStream stdout = new MavenLogOutputStream(log);
        LogOutputStream stderr = new MavenLogOutputStream(log);

        log.debug("Executing command line: " + commandLine);

        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr));

        exec.execute(commandLine, environment, execHandler);

        return execHandler;
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:org.codice.git.GitIntegrationTest.java

private int executeGitCommand(String[] args) throws IOException {
    int exitValue = 0;
    List<String> outputLines = null;
    CommandLine cmdLine = new CommandLine("git");
    for (String arg : args) {
        cmdLine.addArgument(arg);/*from  www  .  j  ava 2s . c  o  m*/
    }
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWorkingDirectory(trash);
    CollectingLogOutputStream output = new CollectingLogOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output, output);
    executor.setStreamHandler(pump);
    try {
        exitValue = executor.execute(cmdLine);
        outputLines = output.getLines();
    } catch (IOException e) {
        boolean hookRan = false;
        String errorMessage = "";
        // Check if we got the aborted message from the hook - implies it ran successfully
        outputLines = output.getLines();
        if ((outputLines != null) && (outputLines.size() > 0)) {
            errorMessage = outputLines.get(0);
            for (String line : outputLines) {
                if (line.contains("HOOK ABORTED")) {
                    hookRan = true;
                    break;
                }
            }
        }
        if (hookRan) {
            LOGGER.debug("Hook ran successfully - returning an error to abort the git command");
        } else {
            LOGGER.warn("Unexpected error during hook processing - first line of output: {}", errorMessage, e);
            throw e;
        }
        exitValue = 1;
    }

    for (String line : outputLines) {
        System.err.println(line);
    }
    return exitValue;
}

From source file:org.eclipse.kura.linux.net.modem.SupportedUsbModems.java

/**
 * Execute command an return splitted lines
 *
 * @param command/*from   ww w .  j a v a 2 s . c  om*/
 *            the command to execute
 * @return the lines output by the command
 * @throws IOException
 *             if executing the commands fails
 */
private static List<String> execute(final String command) throws ExecuteException, IOException {
    final DefaultExecutor executor = new DefaultExecutor();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out, NullOutputStream.NULL_OUTPUT_STREAM));

    int rc = executor.execute(CommandLine.parse(command));

    s_logger.debug("Called {} - rc = {}", command, rc);

    return IOUtils.readLines(new ByteArrayInputStream(out.toByteArray()));
}

From source file:org.eclipse.php.composer.core.launch.execution.ScriptExecutor.java

public ScriptExecutor() {

    outBuilder = new StringBuilder();
    errBuilder = new StringBuilder();

    errStream = new LogOutputStream() {
        @Override//from  w w w.  j av a 2 s  . c om
        protected void processLine(String line, int level) {
            if (!line.isEmpty()) {
                errBuilder.append(line + "\n"); //$NON-NLS-1$
                for (ExecutionResponseListener listener : listeners) {
                    listener.executionMessage(line);
                }
            }
        }
    };

    outStream = new LogOutputStream() {
        @Override
        protected void processLine(String line, int level) {
            if (!line.isEmpty()) {
                outBuilder.append(line + "\n"); //$NON-NLS-1$
                for (ExecutionResponseListener listener : listeners) {
                    listener.executionMessage(line);
                }
            }
        }
    };

    streamHandler = new PumpStreamHandler(outStream, errStream);

    executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);

}

From source file:org.epics.archiverappliance.TomcatSetup.java

private void createAndStartTomcatInstance(String testName, final String applianceName, int port,
        int startupPort) throws IOException {
    File workFolder = makeTomcatFolders(testName, applianceName, port, startupPort);
    HashMap<String, String> environment = createEnvironment(testName, applianceName);
    File logsFolder = new File(workFolder, "logs");
    assert (logsFolder.exists());

    CommandLine cmdLine = new CommandLine(
            System.getenv("TOMCAT_HOME") + File.separator + "bin" + File.separator + "catalina.sh");
    cmdLine.addArgument("run");
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    final CountDownLatch latch = new CountDownLatch(1);
    PumpStreamHandler pump = new PumpStreamHandler(new LogOutputStream() {
        @Override/*  w  w  w .  j  a  v a2s  .  co m*/
        protected void processLine(String msg, int level) {
            if (msg != null && msg.contains("All components in this appliance have started up")) {
                logger.info(applianceName + " has started up.");
                latch.countDown();
            }
            System.out.println(msg);
        }
    }, System.err);

    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(pump);
    executor.setWorkingDirectory(logsFolder);
    executor.execute(cmdLine, environment, resultHandler);
    executorWatchDogs.add(watchdog);

    // We wait for some time to make sure the server started up
    try {
        latch.await(2, TimeUnit.MINUTES);
    } catch (InterruptedException ex) {
    }
    logger.info("Done starting tomcat for the testing.");

}

From source file:org.fuin.kickstart4j.ApplicationStarter.java

/**
 * Execute the target application.//from  ww w  .ja v a  2s.c  om
 */
public void execute() {

    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
    final Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(destDir);
    exec.setStreamHandler(new PumpStreamHandler(outStream, errStream));
    try {

        // Spawns an separate thread
        exec.execute(commandLine, new ExecuteResultHandler() {
            public void onProcessFailed(final ExecuteException ex) {
                failed = true;
                if (startFrame != null) {
                    startFrame.setVisible(false);
                }
                System.out.print(errStream.toString());
                ErrorDialog.showAndExit(errStream, ex, 1);
            }

            public void onProcessComplete(final int exitValue) {
                // We never get here because the Kickstart4J process
                // will be killed with "System.exit(..)" before...
            }
        });

        if (startFrame != null) {
            startFrameSleep();
            startFrame.setVisible(false);
        }

        // TODO Any idea for a better handling of this situation?
        // Should be a rare situation but "onProcessFailed(..)" and this
        // thread may interfere... If this part is faster than the
        // "Executor"
        // this may call "System.exit(..)" and kills the error message
        // display!

        // Abort processing if the concurrent thread signals a failure
        if (failed) {
            return;
        }
        System.out.print(outStream.toString());
        if (failed) {
            return;
        }
        if (config.isExitAfterExecute()) {
            if (failed) {
                return;
            }
            System.exit(0);
        }
        if (failed) {
            return;
        }
        listener.startupComplete();
    } catch (final IOException ex) {
        throw new RuntimeException("Error executing target application!", ex);
    }

}

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

protected boolean checkAvailable() throws IOException {
    try {/*from   w w  w . ja v a  2  s .  c om*/
        CommandLine cmd = new CommandLine(getExecutable());
        for (String option : getAvailabilityTestOptions()) {
            cmd.addArgument(option);
        }

        // prepare to run
        DefaultExecutor executor = new DefaultExecutor();

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

            if (result != 0) {
                LOGGER.log(Level.SEVERE, "Failed to execute command " + cmd.toString()
                        + "\nStandard output is:\n" + os.toString() + "\nStandard error is:\n" + es.toString());
                return false;
            }

        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Failure to execute command " + cmd.toString(), e);
            return false;
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Failure to locate executable for class " + this.getClass(), e);
        return false;
    }

    return true;
}