Example usage for org.apache.commons.exec Executor setStreamHandler

List of usage examples for org.apache.commons.exec Executor setStreamHandler

Introduction

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

Prototype

void setStreamHandler(ExecuteStreamHandler streamHandler);

Source Link

Document

Set a custom the StreamHandler used for providing input and retrieving the output.

Usage

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

/**
 * Starts the Cassandra server.//  w w  w.ja v  a 2  s  .c om
 *
 * @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.codehaus.mojo.exec.ExecMojo.java

protected int executeCommandLine(Executor exec, final CommandLine commandLine, Map<String, String> enviro,
        final PumpStreamHandler psh) throws ExecuteException, IOException {
    exec.setStreamHandler(psh);

    int result;//www. ja  va 2s  .  c om
    try {
        psh.start();
        if (async) {
            if (asyncDestroyOnShutdown) {
                exec.setProcessDestroyer(getProcessDestroyer());
            }

            exec.execute(commandLine, enviro, new ExecuteResultHandler() {
                public void onProcessFailed(ExecuteException e) {
                    getLog().error("Async process failed for: " + commandLine, e);
                }

                public void onProcessComplete(int exitValue) {
                    getLog().info("Async process complete, exit value = " + exitValue + " for: " + commandLine);
                    try {
                        psh.stop();
                    } catch (IOException e) {
                        getLog().error("Error stopping async process stream handler for: " + commandLine, e);
                    }
                }
            });
            result = 0;
        } else {
            result = exec.execute(commandLine, enviro);
        }
    } finally {
        if (!async) {
            psh.stop();
        }
    }
    return result;
}

From source file:org.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java

private static DefaultExecuteResultHandler executeFFmpeg(final CommandLine command, final int timeoutSeconds,
        final PumpStreamHandler streamHandler) throws IOException {
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutSeconds * 1000);
    final Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);//from w  w w.  jav a 2  s  .co  m

    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(command, resultHandler);

    return resultHandler;
}

From source file:org.eclipse.smarthome.io.net.exec.ExecUtil.java

/**
 * <p>/*from  w ww  .j  av a2s . c  o  m*/
 * Executes <code>commandLine</code>. Sometimes (especially observed on
 * MacOS) the commandLine isn't executed properly. In that cases another
 * exec-method is to be used. To accomplish this please use the special
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
 * delimiter it is split into a String[] array and the special exec-method
 * is used.
 * </p>
 * <p>
 * A possible {@link IOException} gets logged but no further processing is
 * done.
 * </p>
 * 
 * @param commandLine
 *            the command line to execute
 * @param timeout
 *            timeout for execution in milliseconds
 * @return response data from executed command line
 */
public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

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 a  2s. c o  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.fornax.toolsupport.sculptor.maven.plugin.GeneratorMojo.java

/**
 * Executes the commandline running the Eclipse MWE2 launcher and returns
 * the commandlines exit value.//from  w  w  w . j ava2 s . c  o m
 * 
 * @param changedFiles
 *            list of files from <code>checkFileSets</code> which are
 *            modified since last generator execution or <code>null</code>
 *            if code generation is enforced
 */
protected List<File> executeGenerator(Set<String> changedFiles) throws MojoExecutionException {
    List<File> createdFiles = null;

    // Build executor for projects base directory
    ScanningMavenLogOutputStream stdout = getStdoutStream();
    ScanningMavenLogOutputStream stderr = getStderrStream();
    Executor exec = getExecutor();
    exec.setWorkingDirectory(project.getBasedir());
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

    // Execute commandline and check return code
    try {
        int exitValue = exec.execute(getGeneratorCommandLine(changedFiles));

        // Check exit value and output streams for errors
        if (exitValue == 0 && stdout.getErrorCount() == 0 && stderr.getLineCount() == 0) {

            // Return list of created files
            createdFiles = stdout.getCreatedFiles();
        }
    } catch (ExecuteException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    }
    return createdFiles;
}

From source file:org.fornax.toolsupport.sculptor.maven.plugin.GraphvizMojo.java

/**
 * Executes the command line tool <code>dot</code>.
 * //from   w ww. ja v  a  2s  .  com
 * @param dotFiles
 *            list of dot files from the
 *            {@link AbstractSculptorMojo#statusFile}
 */
protected boolean executeDot(Set<String> dotFiles) throws MojoExecutionException {

    // Build executor for projects base directory
    MavenLogOutputStream stdout = getStdoutStream();
    MavenLogOutputStream stderr = getStderrStream();
    Executor exec = getExecutor();
    exec.setWorkingDirectory(project.getBasedir());
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

    // Execute commandline and check return code
    try {
        int exitValue = exec.execute(getDotCommandLine(dotFiles));
        if (exitValue == 0 && stdout.getErrorCount() == 0) {
            return true;
        }
    } catch (ExecuteException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    }
    return false;
}

From source file:org.fuin.esmp.EventStoreStopMojo.java

@Override
protected final void executeGoal() throws MojoExecutionException {
    init();/*w  ww.ja  v  a2 s .c om*/
    LOG.info("command={}", command);

    final CommandLine cmdLine = createCommandLine();
    final Executor executor = new DefaultExecutor();
    try {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final PumpStreamHandler psh = new PumpStreamHandler(bos);
        executor.setStreamHandler(psh);
        executor.setWorkingDirectory(getEventStoreDir());
        final int result = executor.execute(cmdLine);
        if (result != 0) {
            throw new MojoExecutionException("Error stopping the event store: " + result);
        }
        final List<String> messages = asList(bos.toString());
        logDebug(messages);
        deletePid();
        LOG.info("Event store successfully stopped");

    } catch (final IOException ex) {
        throw new MojoExecutionException("Error executing the command line: " + cmdLine, ex);
    }

}

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

/**
 * Execute the target application.//from w  w  w .  j av  a2 s.c  o  m
 */
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.fuin.owndeb.commons.DebUtils.java

private static void execute(final CommandLine cmdLine, final File workingDir, final String errorMsg) {

    LOG.debug("Execute: " + cmdLine.toString());

    final Executor executor = new DefaultExecutor();
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final PumpStreamHandler psh = new PumpStreamHandler(bos);
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(workingDir);
    try {//w  ww.j  a  va 2s.  c  o m
        final int result = executor.execute(cmdLine);
        if (result != 0) {
            logError(asList(bos.toString()));
            throw new RuntimeException("Error # " + result + " / " + errorMsg);
        }
    } catch (final IOException ex) {
        logError(asList(bos.toString()));
        throw new RuntimeException(errorMsg, ex);
    }
}