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: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");
    }/*  ww w  . j a va 2  s  . co 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:com.tascape.qa.th.android.comm.Adb.java

public List<String> adb(final List<Object> arguments) throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    if (!this.serial.isEmpty()) {
        cmdLine.addArgument("-s");
        cmdLine.addArgument(serial);//from  w ww .j a va2  s  . com
    }
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    List<String> output = new ArrayList<>();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new ESH(output));
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }
    return output;
}

From source file:com.tascape.qa.th.android.comm.Adb.java

public ExecuteWatchdog adbAsync(final List<Object> arguments, long timeoutMillis) throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    if (!this.serial.isEmpty()) {
        cmdLine.addArgument("-s");
        cmdLine.addArgument(serial);//from  ww  w.j  a  v  a2  s.  co m
    }
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis);
    Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new ESH());
    executor.execute(cmdLine, new DefaultExecuteResultHandler());

    return watchdog;
}

From source file:com.github.mjeanroy.maven.plugins.node.commands.CommandExecutor.java

/**
 * Execute command line and return the result status.
 *
 * @param workingDirectory Working directory (i.e where the command line is executed).
 * @param command Command, containing executable path with arguments.
 * @param logger Logger to use to log command output.
 * @return Command result object.//from   ww  w .j  a  v a2s.  c  o m
 */
public CommandResult execute(File workingDirectory, Command command, Log logger) {
    CommandLine commandLine = new CommandLine(command.getExecutable());
    for (String argument : command.getArguments()) {
        commandLine.addArgument(argument);
    }

    try {
        Executor executor = new DefaultExecutor();
        executor.setWorkingDirectory(workingDirectory);
        executor.setExitValue(0);

        // Define custom output stream
        LogStreamHandler stream = new LogStreamHandler(logger);
        PumpStreamHandler handler = new PumpStreamHandler(stream);
        executor.setStreamHandler(handler);

        int status = executor.execute(commandLine);
        return new CommandResult(status);
    } catch (ExecuteException ex) {
        return new CommandResult(ex.getExitValue());
    } catch (IOException ex) {
        throw new CommandException(ex);
    }
}

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(//from  w  w  w.j av a 2s .  c  o m
                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:net.minecraft.client.MineExec.java

@Override
protected Integer doInBackground() throws IOException, InterruptedException {
    Executor exe = new DefaultExecutor();
    CommandLine mineExec = CommandLine.parse(mineCmd);

    PipedOutputStream stdout = new PipedOutputStream();
    PipedOutputStream stderr = new PipedOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr);
    exe.setStreamHandler(streamHandler);
    MinecraftApplet configCrusher = new MinecraftApplet();
    try {/*from  ww  w .j a v a 2  s. c o  m*/
        File target = new File(VersionInfo.getTechnicFolder());
        BufferedInputStream biserr = new BufferedInputStream(new PipedInputStream(stderr));
        ExecuteResultHandler rh = new DefaultExecuteResultHandler();
        exe.execute(mineExec, rh);
        BufferedReader reader = new BufferedReader(new InputStreamReader(biserr));
        configCrusher.minecraftLoaded();
        String line = reader.readLine();
        logWindow.append(line + "\n");
        int dupLen = 0;
        int dupMax = 25;
        while (line != null) {
            String line2 = reader.readLine();
            if ((line2.contains("Aether") || line2.contains("aether") && watchCfg
                    && new File(target + File.separator + VersionInfo.getModpackName(), "MenuAPI.properties")
                            .exists())) {
                configCrusher.prepareConfigs();
            }
            if ((Boolean) nbDebug[2]) {
                if (!line.equals(line2) || dupLen >= dupMax) {
                    if (dupLen > 0) {
                        logWindow.append(line + "(" + dupLen + ")\n");
                    } else {
                        if (!line.equals(line2)) {
                            logWindow.append(line2 + "\n");
                        }
                    }
                    dupLen = 0;
                } else {
                    dupLen++;
                }
                line = line2;
            } else {
                logWindow.append(line2 + "\n");
                line = line2;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    if ((Integer) (nbDebug[1]) <= 1) {
        configCrusher.remExtras();
        configCrusher.minecraftClosed(password);
    }
    return 1;
}

From source file:com.adaptris.hpcc.DfuPlusWrapper.java

protected void executeInternal(CommandLine cmdLine, OutputStream stdout)
        throws ProduceException, AbortJobException {
    int exit = -1;
    ExecuteWatchdog watchdog = new ExecuteWatchdog(EXEC_TIMEOUT_INTERVAL.toMilliseconds());
    try (OutputStream out = stdout) {
        Executor cmd = new DefaultExecutor();
        cmd.setWatchdog(watchdog);//from   www  .  j a va2 s  .c  o m
        PumpStreamHandler pump = new ManagedPumpStreamHandler(out);
        cmd.setStreamHandler(pump);
        cmd.setExitValues(null);
        exit = cmd.execute(cmdLine);
    } catch (Exception e) {
        throw ExceptionHelper.wrapProduceException(e);
    }
    if (watchdog.killedProcess() || exit != 0) {
        throw new AbortJobException("Job killed due to timeout/ExitCode != 0");
    }
}

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

private 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  ww .j  a va2 s  .  c o m*/

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

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

    return resultHandler;
}

From source file:com.adaptris.core.services.system.SystemCommandExecutorService.java

/**
 * Invokes the command line executable//from w  w  w.j  a  v a2s .  c  o m
 * @see com.adaptris.core.Service#doService(com.adaptris.core.AdaptrisMessage)
 */
@Override
public void doService(AdaptrisMessage msg) throws ServiceException {

    try (OutputStream out = getOutputCapture().startCapture(msg)) {
        Executor cmd = getCommandBuilder().configure(new DefaultExecutor());
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMs());
        cmd.setWatchdog(watchdog);
        CommandLine cl = getCommandBuilder().createCommandLine(msg);
        Map<String, String> env = getCommandBuilder().createEnvironment(msg);

        PumpStreamHandler pump = new PumpStreamHandler(out);
        cmd.setStreamHandler(pump);
        log.trace("Executing {}", cl);
        int exit = cmd.execute(cl, env);
        msg.addMetadata(COMMAND_RETURN_VALUE_METADATA_KEY, "" + exit);
    } catch (Exception e) {
        throw ExceptionHelper.wrapServiceException(e);
    }
}

From source file:hr.fer.zemris.vhdllab.service.impl.GhdlSimulator.java

private List<String> executeProcess(CommandLine cl, java.io.File tempDirectory)
        throws ExecuteException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing process: " + cl.toString());
    }//ww  w .  j a  v a 2  s.co m

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ExecuteStreamHandler handler = new PumpStreamHandler(bos);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(PROCESS_TIMEOUT);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(tempDirectory);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(handler);
    /*
     * It seems that when ExecuteWatchdog terminates process by invoking
     * destroy method, process terminates with exit code 143. And since we
     * manually ask watchdog if he killed the process, exit code 143 is
     * marked as successful (just so our code can be executed).
     * 
     * Exit code 1 in case of compilation error(s).
     */
    executor.setExitValues(new int[] { 0, 1, 143 });
    try {
        executor.execute(cl);
    } catch (ExecuteException e) {
        LOG.warn("Process output dump:\n" + bos.toString());
        throw e;
    }

    if (watchdog.killedProcess()) {
        throw new SimulatorTimeoutException(PROCESS_TIMEOUT);
    }
    String output;
    try {
        output = bos.toString(IOUtil.DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new UnhandledException(e);
    }
    if (StringUtils.isBlank(output)) {
        return Collections.emptyList();
    }
    return Arrays.asList(StringUtil.splitToNewLines(output));
}