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:ch.ivyteam.ivy.maven.engine.EngineControl.java

/**
 * Run a short living engine command where we expect a process failure as the engine invokes <code>System.exit(-1)</code>.
 * @param statusCmd //  w w w.  j  av a2 s.c  om
 * @return the output of the engine command.
 */
private String executeSynch(CommandLine statusCmd) {
    String engineOutput = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, System.err);
    Executor executor = createEngineExecutor();
    executor.setStreamHandler(streamHandler);
    executor.setExitValue(-1);
    try {
        executor.execute(statusCmd);
    } catch (IOException ex) { // expected!
    } finally {
        engineOutput = outputStream.toString();
        IOUtils.closeQuietly(outputStream);
    }
    return engineOutput;
}

From source file:com.walmart.gatling.commons.ScriptExecutor.java

private Object runJob(Object message) {
    Master.Job job = (Master.Job) message;
    TaskEvent taskEvent = (TaskEvent) job.taskEvent;

    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    log.info("Verified Script worker received task: {}", message);
    Map<String, Object> map = new HashMap<>();

    if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass()))
        cmdLine.addArgument(agentConfig.getJob().getCpOrJar());

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) {
        cmdLine.addArgument(agentConfig.getJob().getMainClass());
    }/*from  w w  w  .ja va2s  . c om*/
    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }
    cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId));

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    String outPath = "", errPath = "";
    try {
        outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId);
        errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));
        executor.setStreamHandler(psh);
        log.info("command: {}", cmdLine);
        int exitResult = executor.execute(cmdLine);
        //executor.getWatchdog().destroyProcess().
        Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath),
                agentConfig.getUrl(outPath), null, job);
        log.info("Exit code: {}", exitResult);
        if (executor.isFailure(exitResult) || exitResult == 1) {
            log.info("Script Executor Failed, job: " + job.jobId);
            //getSender().tell(new Worker.WorkFailed(result), getSelf());
            return new Worker.WorkFailed(result);
        } else {
            result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                    agentConfig.getUrl(getMetricsPath(job)), job);
            log.info("Script Executor Completed, job: " + result);
            //getSender().tell(new Worker.WorkComplete(result), getSelf());
            return new Worker.WorkComplete(result);
        }

    } catch (IOException e) {
        log.error(e.toString());
        Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                null, job);
        log.info("Executor Encountered run time exception, result: " + result.toString());
        //getSender().tell(new Worker.WorkFailed(result), getSelf());
        return new Worker.WorkFailed(result);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }
}

From source file:cc.arduino.contributions.packages.ContributionInstaller.java

private void executeScripts(File folder, Collection<File> postInstallScripts, boolean trusted, boolean trustAll)
        throws IOException {
    File script = postInstallScripts.iterator().next();

    if (!trusted && !trustAll) {
        System.err.println(/* w w  w. j  a  va2  s . c  om*/
                I18n.format(tr("Warning: non trusted contribution, skipping script execution ({0})"), script));
        return;
    }

    if (trustAll) {
        System.err.println(I18n.format(tr("Warning: forced untrusted script execution ({0})"), script));
    }

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr));
    executor.setWorkingDirectory(folder);
    executor.setExitValues(null);
    int exitValue = executor.execute(new CommandLine(script));
    executor.setExitValues(new int[0]);

    System.out.write(stdout.toByteArray());
    System.err.write(stderr.toByteArray());

    if (executor.isFailure(exitValue)) {
        throw new IOException();
    }
}

From source file:com.mooregreatsoftware.gitprocess.lib.Pusher.java

private static ThePushResult doGitProgPush(GitLib gitLib, Branch localBranch, String remoteBranchName,
        boolean forcePush, String remoteName) {
    String cmd = String.format("git push --porcelain %s %s %s:%s", remoteName, forcePush ? "--force" : "",
            localBranch.shortName(), remoteBranchName);
    CommandLine commandLine = CommandLine.parse(cmd);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(gitLib.workingDirectory());
    final StringWriter stdOutWriter = new StringWriter();
    final StringWriter stdErrWriter = new StringWriter();
    executor.setStreamHandler(//  w ww . j  a  v a2 s .  c  om
            new PumpStreamHandler(new WriterOutputStream(stdOutWriter), new WriterOutputStream(stdErrWriter)));
    final int exitCode = Try.of(() -> {
        try {
            return executor.execute(commandLine);
        } catch (ExecuteException e) {
            return e.getExitValue();
        } catch (IOException e) {
            final String message = e.getMessage();
            if (message != null && message.contains("No such file or directory")) {
                return 1;
            }
            e.printStackTrace();
            return -1;
        }
    }).get();

    return new ProcPushResult(stdOutWriter, stdErrWriter, exitCode);
}

From source file:com.alibaba.jstorm.yarn.utils.JStormUtils.java

/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result
 * <p/>/*from  www . j  a va 2 s.co m*/
 * This function don't care whether the command is successfully or not
 *
 * @param command
 * @param environment
 * @param workDir
 * @param resultHandler
 * @return
 * @throws IOException
 */
@Deprecated
public static ByteArrayOutputStream launchProcess(String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (StringUtils.isBlank(cmdItem) == false) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (StringUtils.isBlank(workDir) == false) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException e) {

        // @@@@
        // failed to run command
    }

    return out;

}

From source file:com.alibaba.jstorm.utils.JStormUtils.java

/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result
 * <p/>//from w  w  w  .  j a v a2  s  . c  o  m
 * This function don't care whether the command is successfully or not
 * 
 * @param command
 * @param environment
 * @param workDir
 * @param resultHandler
 * @return
 * @throws IOException
 */
public static ByteArrayOutputStream launchProcess(String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (StringUtils.isBlank(cmdItem) == false) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (StringUtils.isBlank(workDir) == false) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException e) {

        // @@@@
        // failed to run command
    }

    return out;

}

From source file:com.datastax.driver.core.CCMBridge.java

private String execute(String command, Object... args) {
    String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
    Closer closer = Closer.create();//w  w  w  .  j av a2 s.c  o m
    // 10 minutes timeout
    ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.MINUTES.toMillis(10));
    StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    closer.register(pw);
    try {
        logger.trace("Executing: " + fullCommand);
        CommandLine cli = CommandLine.parse(fullCommand);
        Executor executor = new DefaultExecutor();
        LogOutputStream outStream = new LogOutputStream() {
            @Override
            protected void processLine(String line, int logLevel) {
                String out = "ccmout> " + line;
                logger.debug(out);
                pw.println(out);
            }
        };
        LogOutputStream errStream = new LogOutputStream() {
            @Override
            protected void processLine(String line, int logLevel) {
                String err = "ccmerr> " + line;
                logger.error(err);
                pw.println(err);
            }
        };
        closer.register(outStream);
        closer.register(errStream);
        ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
        executor.setStreamHandler(streamHandler);
        executor.setWatchdog(watchDog);
        int retValue = executor.execute(cli, ENVIRONMENT_MAP);
        if (retValue != 0) {
            logger.error("Non-zero exit code ({}) returned from executing ccm command: {}", retValue,
                    fullCommand);
            pw.flush();
            throw new CCMException(
                    String.format("Non-zero exit code (%s) returned from executing ccm command: %s", retValue,
                            fullCommand),
                    sw.toString());
        }
    } catch (IOException e) {
        if (watchDog.killedProcess())
            logger.error("The command {} was killed after 10 minutes", fullCommand);
        pw.flush();
        throw new CCMException(String.format("The command %s failed to execute", fullCommand), sw.toString(),
                e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            Throwables.propagate(e);
        }
    }
    return sw.toString();
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * Executes a PBS command.//ww  w .ja va2s  . com
 *
 * @param cmdLine command
 * @param environment env vars
 * @param out output stream
 * @param err err stream
 * @return execute handler
 * @throws ExecuteException if there is an error executing a command
 * @throws IOException in case of an IO problem
 */
static DefaultExecuteResultHandler execute(CommandLine cmdLine, Map<String, String> environment,
        OutputStream out, OutputStream err) throws ExecuteException, IOException {
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteStreamHandler streamHandler = new PumpStreamHandler(out, err);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setStreamHandler(streamHandler);
    if (environment != null) {
        executor.execute(cmdLine, environment, resultHandler);
    } else {
        executor.execute(cmdLine, resultHandler);
    }
    return resultHandler;
}

From source file:net.tkausl.RunMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    File plugins = pluginfolder == null ? new File(serverPath, "plugins") : new File(serverPath, pluginfolder);
    if (!plugins.exists())
        plugins.mkdirs();//from  w w  w  .  j  a v  a2s. c  o  m

    File pluginFile = new File(plugins, fileName + ".dev");
    if (!pluginFile.exists()) {
        try {
            PrintWriter w = new PrintWriter(pluginFile);
            w.print(outputDir);
            w.close();
        } catch (FileNotFoundException ex) {
            throw new MojoExecutionException("Could not write .dev-file");
        }
    }
    Executor ex = new DefaultExecutor();
    CommandLine commandLine = CommandLine.parse("java");
    String execArgs = System.getProperty("exec.args");
    if (execArgs != null && execArgs.trim().length() > 0) {
        commandLine.addArguments(execArgs.split(" "));
    }
    commandLine.addArguments(new String[] { "-jar", serverJar });

    if (pluginfolder != null)
        commandLine.addArguments(new String[] { "--plugins", pluginfolder });

    ex.setWorkingDirectory(serverPath);
    //PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err, System.in);
    //ex.setStreamHandler(psh);
    ex.setStreamHandler(new ExecuteStreamHandler() {
        private PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err);
        InputStreamPumper isp;
        Thread ispt;

        public void setProcessInputStream(OutputStream os) throws IOException {
            isp = new InputStreamPumper(System.in, os);
        }

        public void setProcessErrorStream(InputStream is) throws IOException {
            psh.setProcessErrorStream(is);
        }

        public void setProcessOutputStream(InputStream is) throws IOException {
            psh.setProcessOutputStream(is);
        }

        public void start() throws IOException {
            if (isp != null) {
                ispt = new Thread(isp);
                ispt.setDaemon(true);
                ispt.start();
            }
            psh.start();
        }

        public void stop() throws IOException {
            if (ispt != null)
                ispt.interrupt();
            psh.stop();
        }
    });
    try {
        ex.execute(commandLine);
    } catch (IOException ex1) {
        throw new MojoExecutionException("Error in Execution");
    }
}

From source file:org.apache.falcon.regression.core.util.ExecUtil.java

public static ExecResult executeCommand(CommandLine commandLine) {
    LOGGER.info("Command to be executed: " + commandLine);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(5 * 1000)); //timeout of 5 seconds
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));
    int exitVal = 1;
    String exception = "";
    try {/* w  w  w  . j a  va  2s .  com*/
        exitVal = executor.execute(commandLine);
    } catch (IOException e) {
        LOGGER.warn("Caught exception: " + e);
        exception = e.toString();
    }
    final String output = outStream.toString();
    String errors = errStream.toString();
    errors = errors.isEmpty() ? exception : errors;

    LOGGER.info("exitVal: " + exitVal);
    LOGGER.info("output: " + output);
    LOGGER.info("errors: " + errors);
    return new ExecResult(commandLine, exitVal, output.trim(), errors.trim());
}