Example usage for org.apache.commons.exec DefaultExecuteResultHandler waitFor

List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler waitFor

Introduction

In this page you can find the example usage for org.apache.commons.exec DefaultExecuteResultHandler waitFor.

Prototype

public void waitFor() throws InterruptedException 

Source Link

Document

Causes the current thread to wait, if necessary, until the process has terminated.

Usage

From source file:io.manasobi.utils.CmdUtils.java

/**
 *   (commandLine) ?   ?? ?  ? ?/*from  w w  w.j a v  a2s  .c  o  m*/
 * 
 * @param commandLine    
 * @param argument     ?
 * @param timeout     
 * 
 * @return int ? 
 */
public static int execute(CommandLine commandLine, String argument, long timeout) {

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

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

    // ? 
    if (StringUtils.isNotEmpty(argument)) {
        commandLine.addArguments(argument);
    }

    //  
    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
    }

    // ??  ? 
    executor.setExitValue(SUCCESS_RETURN_CODE);

    try {

        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();

        return resultHandler.getExitValue();

    } catch (Exception e) {

        throw new CmdUtilsException(e.getMessage());
    }
}

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  va 2s  .com
        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:com.anrisoftware.mongoose.buildins.execbuildin.ExecBuildin.java

private void waitForCommand() throws InterruptedException, CommandException {
    if (handler instanceof DefaultExecuteResultHandler) {
        DefaultExecuteResultHandler h = (DefaultExecuteResultHandler) handler;
        h.waitFor();
        ExecuteException ex = h.getException();
        if (ex != null) {
            throw log.errorCommand(this, ex);
        }// w  w w  .j a  v  a2  s. c o m
    }
}

From source file:com.boulmier.machinelearning.jobexecutor.job.Job.java

public void start() throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final DefaultExecutor exec = new DefaultExecutor();
    final ExecuteWatchdog wd = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    final PumpStreamHandler output = new PumpStreamHandler(out);
    final DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();

    exec.setWatchdog(wd);/*from   w w w . j  av a  2s.  c  o m*/
    exec.setStreamHandler(output);
    exec.execute(cl, handler);
    JobExecutor.logger.info("Running job " + jobid);

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                handler.waitFor();
                Computer.ComputeProperties properties = Computer.ComputeProperties.buildFromRequest(req);
                new SenderComputer(new StorageComputer(out.toString(), properties)).compute();
                JobExecutor.logger.info("Job complete " + jobid);
            } catch (InterruptedException ex) {
                exec.getWatchdog().destroyProcess();
                JobExecutor.logger.error(
                        "Job (" + jobid + ") has been destroyed due to internal error " + ex.getMessage());
            }
        }

    }).start();

}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private void generateThumbnailsWithoutDuration(final String videoFilePath)
        throws IOException, InterruptedException {
    final CommandLine command = getFFmpegCreateThumbnailCommand(videoFilePath, getThumbnailFilePath(), null,
            THUMBNAIL_COUNT);/*from   w  ww .j  av a 2  s . c o m*/
    final DefaultExecuteResultHandler resultHandler = executeFFmpeg(command, 15, null);

    resultHandler.waitFor();

    if (resultHandler.getException() != null) {
        throw resultHandler.getException();
    }
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private Duration getVideoDuration(final String videoFilePath) throws IOException, InterruptedException {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    final CommandLine command = getFFmpegInfoCommand(videoFilePath);
    final DefaultExecuteResultHandler resultHandler = executeFFmpeg(command, 3, streamHandler);
    resultHandler.waitFor();

    return parseVideoDuration(outputStream.toString(StandardCharsets.UTF_8.name()));
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private byte[] createGifThumbnailWithDuration(final String videoFilePath, final Duration duration)
        throws IOException, InterruptedException {
    final Duration durationFraction = duration.dividedBy(THUMBNAIL_COUNT);

    // Start numbering files with 1 to match FFmpeg's convention.
    for (int clipNum = FFMPEG_FILE_NUMBERING_START; clipNum <= THUMBNAIL_COUNT; ++clipNum) {
        final String thumbnailPath = String.format(getThumbnailFilePath(), clipNum);

        final String seek = durationToString(durationFraction.multipliedBy(clipNum - 1));

        final CommandLine command = getFFmpegCreateThumbnailCommand(videoFilePath, thumbnailPath, seek, 1);

        final DefaultExecuteResultHandler resultHandler = executeFFmpeg(command, 15, null);
        resultHandler.waitFor();
    }//from   w  w w.  j a va 2  s  . c  o  m

    return createGifFromThumbnailFiles();
}

From source file:edu.emory.cci.aiw.neo4jetl.Neo4jHome.java

private void controlServer(String command) throws IOException, InterruptedException, CommandFailedException {
    LOGGER.debug("Executing neo4j command {}...", command);
    CommandLine serverControlCommand = new CommandLine(new File(this.home, SERVER_CONTROL_COMMAND));
    serverControlCommand.addArgument("${command}");
    Map<String, String> map = new HashMap<>();
    map.put("command", command);
    serverControlCommand.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);/*from w ww .  j  a v a  2s .  com*/
    executor.setWatchdog(watchdog);
    executor.execute(serverControlCommand, resultHandler);
    LOGGER.debug("Neo4j command {} is completed, checking exit value...", command);
    resultHandler.waitFor();
    int exitValue = resultHandler.getExitValue();
    if (exitValue != 0) {
        ExecuteException exception = resultHandler.getException();
        throw new CommandFailedException(exitValue, "Neo4j command '" + command + "' failed", exception);
    }
    LOGGER.debug("Neo4j command {} was successful", command);
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private byte[] createGifFromThumbnailFiles() throws IOException, InterruptedException {
    final DefaultExecuteResultHandler resultHandler = executeFFmpeg(getFFmpegCreateAnimatedGifCommand(), 3,
            null);//from w  w w .ja v  a2s .c o  m

    resultHandler.waitFor();

    if (resultHandler.getException() == null) {
        return FileUtils.readFileToByteArray(new File(getGifFilePath()));
    } else {
        throw resultHandler.getException();
    }
}

From source file:info.pancancer.arch3.worker.WorkflowRunner.java

@Override
public WorkflowResult call() throws IOException {
    PumpStreamHandler streamHandler = new PumpStreamHandler(this.outputStream, this.errorStream);
    WorkflowResult result = new WorkflowResult();

    DefaultExecutor executor = new DefaultExecutor();

    /*// www. j  av a2s .  co m
     * CommandLine cli = new CommandLine("docker"); cli.addArguments(new String[] { "run", "--rm", "-h", "master", "-t" ,"-v",
     * "/var/run/docker.sock:/var/run/docker.sock", "-v", job.getWorkflowPath() + ":/workflow", "-v",pathToINI + ":/ini", "-v",
     * "/datastore:/datastore", "-v","/home/"+this.userName+"/.ssh/gnos.pem:/home/ubuntu/.ssh/gnos.pem",
     * "seqware/seqware_whitestar_pancancer", "seqware", "bundle", "launch", "--dir", "/workflow", "--ini", "/ini", "--no-metadata" });
     */
    LOG.info("Executing command: " + this.cli.toString().replace(",", ""));

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.setStreamHandler(streamHandler);

    try {
        if (this.preworkDelay > 0) {
            LOG.info("Sleeping before executing workflow for " + this.preworkDelay + " ms.");
            Thread.sleep(this.preworkDelay);
        }

        executor.execute(cli, resultHandler);
        // Use the result handler for non-blocking call, so this way we should be able to get updates of
        // stdout and stderr while the command is running.
        resultHandler.waitFor();
        result.setWorkflowStdout(outputStream.getAllLinesAsString());
        result.setWorkflowStdErr(errorStream.getAllLinesAsString());
        LOG.debug("Exit code: " + resultHandler.getExitValue());
        result.setExitCode(resultHandler.getExitValue());
        if (this.postworkDelay > 0) {
            LOG.info("Sleeping after executing workflow for " + this.postworkDelay + " ms.");
            Thread.sleep(this.postworkDelay);
        }
    } catch (ExecuteException e) {
        LOG.error(e.getMessage(), e);
        result.setWorkflowStdout(this.getStdErr());
    } catch (InterruptedException | IOException e) {
        LOG.error(e.getMessage(), e);
        result.setWorkflowStdout(this.getStdErr());
    } finally {
        this.outputStream.close();
        this.errorStream.close();
    }
    LOG.debug("Workflowrunner exiting");
    return result;
}