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

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

Introduction

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

Prototype

void execute(CommandLine command, Map<String, String> environment, ExecuteResultHandler handler)
        throws ExecuteException, IOException;

Source Link

Document

Methods for starting asynchronous execution.

Usage

From source file:com.zxy.commons.exec.CmdExecutor.java

/**
 * /*from   w ww .j  av  a 2 s .  c  o m*/
 * 
 * @param workHome workHome
 * @param command command
 * @throws InterruptedException InterruptedException
 * @throws IOException IOException
 */
public static void execAsyc(String workHome, String command) throws InterruptedException, IOException {
    CommandLine cmdLine = CommandLine.parse(PRE_CMD + command);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(workHome));

    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override
        protected void processLine(String line, int level) {
            LOGGER.debug(line);
        }
    }, new LogOutputStream() {
        @Override
        protected void processLine(String line, int level) {
            LOGGER.debug(line);
        }
    }));

    ExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(cmdLine, EnvironmentUtils.getProcEnvironment(), resultHandler);
    // resultHandler.waitFor();
}

From source file:com.netflix.spinnaker.clouddriver.jobs.local.JobExecutorLocal.java

private <T> JobResult<T> executeStreaming(JobRequest jobRequest, ReaderConsumer<T> consumer)
        throws IOException {
    PipedOutputStream stdOut = new PipedOutputStream();
    ByteArrayOutputStream stdErr = new ByteArrayOutputStream();

    Executor executor = buildExecutor(new PumpStreamHandler(stdOut, stdErr, jobRequest.getInputStream()));
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(jobRequest.getCommandLine(), jobRequest.getEnvironment(), resultHandler);

    T result = consumer.consume(new BufferedReader(new InputStreamReader(new PipedInputStream(stdOut))));

    try {//from   w ww  .  j  a v a  2s.  co  m
        resultHandler.waitFor();
    } catch (InterruptedException e) {
        executor.getWatchdog().destroyProcess();
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }

    return JobResult.<T>builder()
            .result(resultHandler.getExitValue() == 0 ? JobResult.Result.SUCCESS : JobResult.Result.FAILURE)
            .killed(executor.getWatchdog().killedProcess()).output(result).error(stdErr.toString()).build();
}

From source file:name.martingeisse.webide.nodejs.AbstractNodejsServer.java

/**
 * Starts this server./*w ww  .  java  2 s.c  o m*/
 */
public void start() {

    // determine the path of the associated script
    URL url = getScriptUrl();
    if (!url.getProtocol().equals("file")) {
        throw new RuntimeException("unsupported protocol for associated script URL: " + url);
    }
    File scriptFile = new File(url.getPath());

    // build the command line
    CommandLine commandLine = new CommandLine(Configuration.getBashPath());
    commandLine.addArgument("--login");
    commandLine.addArgument("-c");
    commandLine.addArgument("node " + scriptFile.getName(), false);

    // build I/O streams
    ByteArrayInputStream inputStream = null;
    OutputStream outputStream = System.err;
    OutputStream errorStream = System.err;
    ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream);

    // build an environment map that contains the path to the node_modules
    Map<String, String> environment = new HashMap<String, String>();
    environment.put("NODE_PATH", new File("lib/node_modules").getAbsolutePath());

    // run Node.js
    Executor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setStreamHandler(streamHandler);
    try {
        executor.setWorkingDirectory(scriptFile.getParentFile());
        executor.execute(commandLine, environment, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(ExecuteException e) {
            }

            @Override
            public void onProcessComplete(int exitValue) {
            }

        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.netflix.spinnaker.halyard.deploy.job.v1.JobExecutorLocal.java

@Override
public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn) {
    List<String> tokenizedCommand = jobRequest.getTokenizedCommand();
    if (tokenizedCommand == null || tokenizedCommand.isEmpty()) {
        throw new IllegalArgumentException("JobRequest must include a tokenized command to run");
    }/*w  w  w.ja  va  2 s  .c  om*/

    final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT
            : jobRequest.getTimeoutMillis();

    String jobId = UUID.randomUUID().toString();

    log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId);

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
            ByteArrayOutputStream stdErr = new ByteArrayOutputStream();
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn);
            CommandLine commandLine;

            log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand);

            // Grab the first element as the command.
            commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0));

            // Treat the rest as arguments.
            String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1,
                    tokenizedCommand.size());

            commandLine.addArguments(arguments, false);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) {
                @Override
                public void timeoutOccured(Watchdog w) {
                    // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely
                    // the result of calling watchdog.destroyProcess().
                    if (w != null) {
                        log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms.");

                        cancelJob(jobId);
                    }

                    super.timeoutOccured(w);
                }
            };

            Executor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            executor.setWatchdog(watchdog);
            try {
                executor.execute(commandLine, env, resultHandler);
            } catch (IOException e) {
                throw new RuntimeException("Execution of " + jobId + " failed ", e);
            }

            // Give the job some time to spin up.
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }

            jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler)
                    .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr));
        }
    });

    return jobId;
}

From source file:com.netflix.spinnaker.halyard.core.job.v1.JobExecutorLocal.java

@Override
public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn,
        ByteArrayOutputStream stdOut, ByteArrayOutputStream stdErr) {
    List<String> tokenizedCommand = jobRequest.getTokenizedCommand();
    if (tokenizedCommand == null || tokenizedCommand.isEmpty()) {
        throw new IllegalArgumentException("JobRequest must include a tokenized command to run");
    }//from  w  w w  . jav a 2 s  .c  o  m

    final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT
            : jobRequest.getTimeoutMillis();

    String jobId = UUID.randomUUID().toString();

    pendingJobSet.add(jobId);

    log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId);

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn);
            CommandLine commandLine;

            log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand);

            // Grab the first element as the command.
            commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0));

            // Treat the rest as arguments.
            String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1,
                    tokenizedCommand.size());

            commandLine.addArguments(arguments, false);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) {
                @Override
                public void timeoutOccured(Watchdog w) {
                    // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely
                    // the result of calling watchdog.destroyProcess().
                    if (w != null) {
                        log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms.");

                        cancelJob(jobId);
                    }

                    super.timeoutOccured(w);
                }
            };

            Executor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            executor.setWatchdog(watchdog);
            try {
                executor.execute(commandLine, env, resultHandler);
            } catch (IOException e) {
                throw new RuntimeException("Execution of " + jobId + " failed ", e);
            }

            // Give the job some time to spin up.
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {
            }

            jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler)
                    .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr));

            if (pendingJobSet.contains(jobId)) {
                pendingJobSet.remove(jobId);
            } else {
                // If the job was removed from the set of pending jobs by someone else, its deletion was requested
                jobIdToHandlerMap.remove(jobId);
                watchdog.destroyProcess();
            }
        }
    });

    return jobId;
}

From source file:adb4j.executor.CmdExecutor.java

private CmdResultHandler runAsync(String command, CmdResultHandler resultHandler, boolean shouldClone)
        throws IOException, IOException, IOException, IOException {
    CmdResultHandler handler = shouldClone ? resultHandler.clone() : resultHandler;

    PumpStreamHandler streamHandler = handler.getStreamHandler(this);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);

    //        String[] arguments = CommandLine.parse(command).toStrings();
    //        CommandLine cmdLine = new CommandLine(arguments[0]);
    //        for (int i = 1; i < arguments.length; i++) {
    //            cmdLine.addArgument(command, true);
    //        }/* www.j a v  a 2  s.c o m*/
    CommandLine cmdLine = CommandLine.parse(command);
    executor.execute(cmdLine, getEnvironment(), handler.delegate);

    return handler;
}

From source file:name.martingeisse.webide.process.CompanionProcess.java

/**
 * Starts the subprocess.//from  w w w  .  ja  va  2  s.  co  m
 * 
 * @throws IOException on I/O errors
 */
public final synchronized void start() throws IOException {
    if (started) {
        throw new IllegalStateException("companion process has already been started");
    }
    started = true;
    onBeforeStart();
    CommandLine commandLine = buildCommandLine();
    Map<String, String> environment = buildEnvironment();
    Executor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    configureExecutor(executor);

    boolean successfullyStarted = false;
    try {
        runningProcesses.put(companionId, this);
        executor.execute(commandLine, environment, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(ExecuteException e) {
                messageHandler = null;
                runningProcesses.remove(companionId);
                CompanionProcess.this.onProcessFailed(e.getExitValue(), e.getMessage());
            }

            @Override
            public void onProcessComplete(int exitValue) {
                messageHandler = null;
                runningProcesses.remove(companionId);
                CompanionProcess.this.onProcessComplete(exitValue);
            }

        });
        successfullyStarted = true;
    } finally {
        if (!successfullyStarted) {
            runningProcesses.remove(companionId);
        }
    }

    onAfterStart();
}

From source file:org.apache.bigtop.itest.hive.HiveHelper.java

public static Map<String, String> execCommand(CommandLine commandline, Map<String, String> envVars) {

    System.out.println("Executing command:");
    System.out.println(commandline.toString());
    Map<String, String> env = null;
    Map<String, String> entry = new HashMap<String, String>();
    try {//from w  ww.ja  v  a 2s.c om
        env = EnvironmentUtils.getProcEnvironment();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to get process environment: " + e1.getMessage());
        e1.printStackTrace();
    }
    if (envVars != null) {
        for (String key : envVars.keySet()) {
            env.put(key, envVars.get(key));
        }
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 10000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(streamHandler);
    try {
        executor.execute(commandline, env, resultHandler);
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    }

    try {
        resultHandler.waitFor();
        /*System.out.println("Command output: "+outputStream.toString());*/
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        return entry;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        /*System.out.println("Command output: "+outputStream.toString());*/
        LOG.debug("exitValue: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        e.printStackTrace();
        return entry;
    }
}

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

/**
 * Starts the Cassandra server.// w w  w  .  ja va  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);/*  w  ww .  ja v a  2s .  c om*/

    int result;
    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;
}