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, final InputStream input) 

Source Link

Document

Construct a new PumpStreamHandler.

Usage

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   ww w.  java  2 s  .com

    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:com.netflix.spinnaker.clouddriver.jobs.local.JobExecutorLocal.java

private JobResult<String> execute(JobRequest jobRequest) throws IOException {
    ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
    ByteArrayOutputStream stdErr = new ByteArrayOutputStream();

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

    return JobResult.<String>builder()
            .result(exitValue == 0 ? JobResult.Result.SUCCESS : JobResult.Result.FAILURE)
            .killed(executor.getWatchdog().killedProcess()).output(stdOut.toString()).error(stdErr.toString())
            .build();/* w  ww .  j a  v a  2s.  c om*/
}

From source file:io.gatling.mojo.GatlingJavaMainCallerByFork.java

@Override
public boolean run(boolean displayCmd, boolean throwFailure) throws Exception {
    List<String> cmd = buildCommand();
    displayCmd(displayCmd, cmd);//from   www  .j av a2  s.  co m
    Executor exec = new DefaultExecutor();

    // err and out are redirected to out
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));

    exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine cl = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        cl.addArgument(cmd.get(i), false);
    }
    try {
        int exitValue = exec.execute(cl);
        if (exitValue != 0) {
            if (throwFailure) {
                throw new MojoFailureException("command line returned non-zero value:" + exitValue);
            }
            return false;
        }
        return true;
    } catch (ExecuteException exc) {
        if (throwFailure) {
            throw exc;
        }
        return false;
    }
}

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  ww  .jav  a 2  s .  c o m*/

    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.github.peterjanes.node.NpmPackMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *///w ww .  j  a v a2  s .  c om
public void execute() throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(outputDirectory);

    List commandArguments = new ArrayList();
    commandArguments.add("pack");
    commandArguments.add("./commonjs");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        getLog().debug("Executing command line: " + commandLine);
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }

        Artifact artifact = mavenProject.getArtifact();
        String fileName = String.format("%s-%s.tgz", artifact.getArtifactId(),
                mavenProject.getProperties().getProperty("node.project.version"));
        artifact.setFile(new File(outputDirectory, fileName));
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:io.gatling.mojo.Fork.java

public void run() throws Exception {

    if (propagateSystemProperties) {
        for (Entry<Object, Object> systemProp : System.getProperties().entrySet()) {
            String name = systemProp.getKey().toString();
            String value = systemProp.getValue().toString();
            if (isPropagatableProperty(name)) {
                String escapedValue = StringUtils.escape(value);
                String safeValue = escapedValue.contains(" ") ? '"' + escapedValue + '"' : escapedValue;
                this.jvmArgs.add("-D" + name + "=" + safeValue);
            }/*from  w  w  w .j a va2 s .  c o  m*/
        }
    }

    this.jvmArgs.add("-jar");
    this.jvmArgs
            .add(MojoUtils.createBooterJar(classpath, MainWithArgsInFile.class.getName()).getCanonicalPath());

    List<String> command = buildCommand();

    Executor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));
    exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine cl = new CommandLine(javaExecutable);
    for (String arg : command) {
        cl.addArgument(arg, false);
    }

    int exitValue = exec.execute(cl);
    if (exitValue != 0) {
        throw new MojoFailureException("command line returned non-zero value:" + exitValue);
    }
}

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 {/* www .java 2  s . 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.features.verilog.simulator.VerilogSimulatorMenuDelegate.java

@Override
public void invoke(final Object context, final List<ResourceHandle> anchor, final Object parameter) {

    // check anchor
    logger.trace("VerilogSimulatorMenuDelegate invoked...");
    if (anchor.isEmpty()) {
        logger.trace("empty anchor (no file selected for simulation)");
        return;/*  w  ww  .  j a  v  a2s .co  m*/
    }
    final ResourceHandle inputFile = anchor.get(0);

    // make sure the anchor element is a file
    if (!inputFile.isFile()) {
        logger.trace("selected anchor is not a file");
        return;
    }
    logger.trace("selected file for simulation: " + inputFile.getPath());

    // catch exceptions to cleanly de-allocate the temporary folder
    TemporaryFolder temporaryFolder = null;
    try {

        // allocate a temporary folder for the output files
        temporaryFolder = new TemporaryFolder();
        logger.trace("allocation temporary folder: " + temporaryFolder.getInstanceFolder());

        // build the command line
        final CommandLine commandLine = new CommandLine(Configuration.getBashPath());
        commandLine.addArgument("--login");
        commandLine.addArgument("-c");
        commandLine.addArgument("vvp " + Configuration.getStdinPath(), false);
        logger.trace("command line: " + commandLine);

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

        // run Icarus
        final Executor executor = new DefaultExecutor();
        executor.setStreamHandler(streamHandler);
        executor.setWorkingDirectory(temporaryFolder.getInstanceFolder());
        executor.execute(commandLine);
        logger.trace("VVP finished");

        // create the output files
        final ResourceHandle outputFolder = inputFile.getParent();
        logger.trace("creating output files in folder: " + outputFolder);
        for (final File temporaryFile : temporaryFolder.getInstanceFolder().listFiles()) {
            if (temporaryFile.isFile()) {
                final ResourceHandle outputFile = outputFolder.getChild(temporaryFile.getName());
                logger.trace("creating output file " + outputFile + " from " + temporaryFile);
                outputFile.writeFile(temporaryFile, true, true);
                logger.trace("output file created");
            } else {
                logger.trace("skipping (not a file): " + temporaryFile);
            }
        }
        logger.trace("output files created");

    } catch (final IOException e) {
        logger.error("exception during VVP simulation", e);
        return;
    } finally {
        if (temporaryFolder != null) {
            temporaryFolder.dispose();
        }
    }

}

From source file:com.github.peterjanes.node.NpmTestMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *//*from w  w  w .j  a va2  s.c  o  m*/
public void execute() throws MojoExecutionException {
    if (!workingDirectory.exists()) {
        workingDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(workingDirectory);

    Map env = new HashMap();
    try {
        Map systemEnvVars = EnvironmentUtils.getProcEnvironment();
        env.putAll(systemEnvVars);
    } catch (IOException e) {
        getLog().error("Could not assign default system enviroment variables.", e);
    }
    env.put("NODE_PATH", new File(workingDirectory, "node_modules").getAbsolutePath());
    env.put("XUNIT_FILE", outputFile.getAbsolutePath());

    List commandArguments = new ArrayList();
    commandArguments.add("test");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        outputFile.getParentFile().mkdirs();
        getLog().debug("Executing command line " + commandLine + " in directory "
                + workingDirectory.getAbsolutePath());
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine, env);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);

    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.sonar.scanner.api.it.tools.CommandExecutor.java

private ExecuteStreamHandler createStreamHandler() throws IOException {
    logs = new ByteArrayOutputStream();
    PipedOutputStream outPiped = new PipedOutputStream();
    InputStream inPiped = new PipedInputStream(outPiped);
    in = outPiped;/*from  w  w  w .j  a  v  a 2 s  . c  o m*/

    TeeOutputStream teeOut = new TeeOutputStream(logs, System.out);
    TeeOutputStream teeErr = new TeeOutputStream(logs, System.err);

    return new PumpStreamHandler(teeOut, teeErr, inPiped);
}