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:org.n52.movingcode.runtime.processors.python.PythonCLIProcessor.java

public void execute(int timeoutSeconds) throws IllegalArgumentException, RuntimeException, IOException {

    if (!init()) {
        throw new IOException("Could not initialize the processor. Aborting operation.");
    }//w w  w  .  j  a v a2 s  . c o m

    // load arguments and parse them to internal data format (--> Strings)
    for (IOParameter item : this.values()) {
        try {
            setValue(item);
        } catch (IOException e) {
            throw new IOException("Could not deal with parameter: " + item.getIdentifier().toString() + "\n"
                    + e.getMessage());
        }
    }

    // create command from parameters and values
    String executable = packageDescriptionDoc.getPackageDescription().getWorkspace().getExecutableLocation();
    if (executable.startsWith("./")) {
        executable = executable.substring(2);
    }

    if (executable.startsWith(".\\")) {
        executable = executable.substring(2);
    }
    executable = "python " + this.clonedWorkspace + File.separator + executable;

    CommandLine cmdLine = buildCommandLine(executable, this.executionValues, this);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    Executor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
    executor.setStreamHandler(streamHandler);

    // put a watchdog if required
    if (timeoutSeconds > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeoutSeconds) * 1000);
        executor.setWatchdog(watchdog);
    }

    try {
        executor.execute(cmdLine, resultHandler);
        resultHandler.waitFor();
        int exitVal = resultHandler.getExitValue();
        if (exitVal != 0) {
            LOGGER.error("stderr was: " + errorStream.toString());
            LOGGER.error("stdout was: " + outputStream.toString());
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("stdout was:" + outputStream.toString());
                LOGGER.debug("stderr was:" + errorStream.toString());
            }
        }
    } catch (ExecuteException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        throw new IOException(e.getMessage());
    } catch (InterruptedException e) {
        throw new RuntimeException(
                "Execution was interrupted. Process aborted.\n Message was: " + e.getMessage());
    }

    // update executionData - file data only
    // code below is all about setting the input stream for output media data
    for (ParameterID identifier : this.keySet()) {
        if (this.get(identifier).isMessageOut()) {
            if (this.get(identifier).supportsType(IODataType.MEDIA)) {
                @SuppressWarnings("unchecked")
                List<MediaData> mediaValues = (List<MediaData>) this.get(identifier);
                for (int i = 0; i < mediaValues.size(); i++) {
                    String fileName = this.executionValues.get(identifier)[i];
                    // <-- this is the important line -->
                    mediaValues.get(i).setMediaStream(new FileInputStream(fileName));
                }

            } else {
                // not supported for CLI
            }
        }
    }

}

From source file:org.obm.push.mail.greenmail.ExternalProcess.java

public ExternalProcess(String executablePath, long processTimeout, long processStartTimeNeeded) {
    Preconditions.checkNotNull(Strings.emptyToNull(executablePath));
    Preconditions.checkArgument(processTimeout > 0);

    this.cli = new CommandLine(executablePath);
    this.environment = Maps.newHashMap();
    this.processTimeout = processTimeout;
    this.processStartTimeNeeded = processStartTimeNeeded;
    this.processOutputStream = new ByteArrayOutputStream();
    this.streamHandler = new PumpStreamHandler(processOutputStream, System.err);
}

From source file:org.onehippo.forge.gallerymagick.core.command.AbstractMagickCommand.java

/**
 * Execute the Magick command with the sub-command and arguments.
 * @param stdOut standard output stream//from   ww  w .  j ava  2s  .c  om
 * @throws MagickExecuteException if an execution exception occurs
 * @throws IOException if IO exception occurs
 */
public void execute(final OutputStream stdOut) throws IOException {
    CommandLine cmdLine = createCommandLine();
    ByteArrayOutputStream errStream = null;
    int exitValue = 0;
    DefaultExecuteResultHandler resultHandler = null;

    try {
        errStream = new ByteArrayOutputStream(512);

        final DefaultExecutor executor = new DefaultExecutor();
        ExecuteStreamHandler streamHandler;

        if (stdOut != null) {
            streamHandler = new PumpStreamHandler(stdOut, errStream);
        } else {
            streamHandler = new PumpStreamHandler(System.out, errStream);
        }

        executor.setStreamHandler(streamHandler);

        if (getWorkingDirectory() != null) {
            executor.setWorkingDirectory(getWorkingDirectory());
        }

        long timeout = NumberUtils.toLong(System.getProperty(PROP_TIMEOUT), DEFAULT_COMMAND_TIMEOUT);

        if (timeout > 0) {
            ExecuteWatchdog watchdog = new ExecuteWatchdog(DEFAULT_COMMAND_TIMEOUT);
            executor.setWatchdog(watchdog);
            resultHandler = new DefaultExecuteResultHandler();
            executor.execute(cmdLine, resultHandler);
            log.debug("Executed with watchdog: {}", cmdLine);
            resultHandler.waitFor();
        } else {
            exitValue = executor.execute(cmdLine);
            log.debug("Executed without watchdog: {}", cmdLine);
        }
    } catch (ExecuteException | InterruptedException e) {
        if (resultHandler != null) {
            exitValue = resultHandler.getExitValue();
        }
        if (e.getCause() == null) {
            throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue);
        } else {
            throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue,
                    e.getCause());
        }
    } finally {
        IOUtils.closeQuietly(errStream);
    }
}

From source file:org.opencron.agent.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }/*w ww .  j  av  a  2 s.  c  om*/

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");
    //??
    Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L);

    boolean timeoutFlag = timeout > 0;

    logger.info("[opencron]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    final Response response = Response.response(request);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);

    final Timer timer = new Timer();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        final DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        //?0,shell
        executor.setExitValue(0);

        if (timeoutFlag) {
            //...
            executor.setWatchdog(watchdog);
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //,kill...
                    if (watchdog.isWatching()) {
                        /**
                         * watchdogdestroyProcesskill...
                         * watchdog.destroyProcess();
                         */
                        timer.cancel();
                        watchdog.stop();
                        //call  kill...
                        request.setAction(Action.KILL);
                        try {
                            kill(request);
                            response.setExitCode(Opencron.StatusCode.TIME_OUT.getValue());
                        } catch (TException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, timeout * 60 * 1000);

            //
            resultHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    super.onProcessComplete(exitValue);
                    timer.cancel();
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    super.onProcessFailed(e);
                    timer.cancel();
                }
            };
        }

        executor.execute(commandLine, resultHandler);

        resultHandler.waitFor();

    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = Opencron.StatusCode.ERROR_EXEC.getValue();
        }
        if (Opencron.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[opencron]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[opencron]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {

        exitValue = resultHandler.getExitValue();

        if (CommonUtils.notEmpty(outputStream.toByteArray())) {
            try {
                outputStream.flush();
                String text = outputStream.toString();
                if (notEmpty(text)) {
                    try {
                        text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), "");
                        response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                        exitValue = Integer.parseInt(text
                                .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim());
                    } catch (IndexOutOfBoundsException e) {
                        response.setMessage(text);
                    }
                }
                outputStream.close();
            } catch (Exception e) {
                logger.error("[opencron]:error:{}", e);
            }
        }

        if (Opencron.StatusCode.TIME_OUT.getValue() == response.getExitCode()) {
            response.setSuccess(false).end();
        } else {
            response.setExitCode(exitValue)
                    .setSuccess(response.getExitCode() == Opencron.StatusCode.SUCCESS_EXIT.getValue()).end();
        }

        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[opencron]:execute result:{}", response.toString());
    watchdog.stop();

    return response;
}

From source file:org.opennms.gizmo.k8s.portforward.KubeCtlPortForwardingStrategy.java

@Override
public ForwardedPort portForward(String namespace, String pod, int remotePort) {
    CommandLine cmdLine = new CommandLine("kubectl");
    cmdLine.addArgument("--namespace=${namespace}");
    cmdLine.addArgument("port-forward");
    cmdLine.addArgument("${pod}");
    cmdLine.addArgument(":${remotePort}");

    HashMap<String, String> map = new HashMap<>();
    map.put("namespace", namespace);
    map.put("pod", pod);
    map.put("remotePort", Integer.toString(remotePort));
    cmdLine.setSubstitutionMap(map);//from ww w.j  ava2s.c  o  m

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(out, err);

    DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog wd = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(wd);
    executor.setStreamHandler(psh);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    final int localPort = waitForLocalPort(wd, out, err);
    return new ForwardedPort() {
        @Override
        public InetSocketAddress getAddress() {
            return new InetSocketAddress(InetAddress.getLoopbackAddress(), localPort);
        }

        @Override
        public void close() throws IOException {
            wd.destroyProcess();
        }

        @Override
        public String toString() {
            return String.format("ForwardedPort[localPort=%d]", localPort);
        }
    };
}

From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java

protected Set<Integer> getOpenNMSProcesses() {
    LOG.trace("getOpenNMSProcesses()");
    final Set<Integer> processes = new HashSet<Integer>();

    final String jps = getResourceLocator().findBinary("jps");

    LOG.trace("jps = {}", jps);

    DataInputStream input = null;
    PsParser parser = null;//from ww  w  . ja  va  2  s  .c o  m
    PipedInputStream pis = null;
    PipedOutputStream output = new PipedOutputStream();
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(5000));

    if (jps != null) {
        CommandLine command = CommandLine.parse(jps + " -v");
        PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err);

        try {
            LOG.trace("executing '{}'", command);
            pis = new PipedInputStream(output);
            input = new DataInputStream(pis);
            parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
            parser.start();
            executor.setStreamHandler(streamHandler);
            int exitValue = executor.execute(command);
            IOUtils.closeQuietly(output);
            parser.join();
            processes.addAll(parser.getProcesses());
            LOG.trace("finished '{}'", command);

            if (exitValue != 0) {
                LOG.debug("error running '{}': exit value was {}", command, exitValue);
            }
        } catch (final Exception e) {
            LOG.debug("Failed to run '{}'", command, e);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(pis);
            IOUtils.closeQuietly(output);
        }
    }

    LOG.trace("looking for ps");
    final String ps = getResourceLocator().findBinary("ps");
    if (ps != null) {

        // try Linux/Mac style
        CommandLine command = CommandLine.parse(ps + " aww -o pid -o args");
        output = new PipedOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err);

        try {
            LOG.trace("executing '{}'", command);
            pis = new PipedInputStream(output);
            input = new DataInputStream(pis);
            parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
            parser.start();
            executor.setStreamHandler(streamHandler);
            int exitValue = executor.execute(command);
            IOUtils.closeQuietly(output);
            parser.join(MAX_PROCESS_WAIT);
            processes.addAll(parser.getProcesses());
            LOG.trace("finished '{}'", command);

            if (exitValue != 0) {
                LOG.debug("error running '{}': exit value was {}", command, exitValue);
            }
        } catch (final Exception e) {
            LOG.debug("error running '{}'", command, e);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(pis);
            IOUtils.closeQuietly(output);
        }

        if (processes.size() == 0) {
            // try Solaris style
            command = CommandLine.parse(ps + " -ea -o pid -o args");
            output = new PipedOutputStream();
            streamHandler = new PumpStreamHandler(output, System.err);

            try {
                LOG.trace("executing '{}'", command);
                pis = new PipedInputStream(output);
                input = new DataInputStream(pis);
                parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0);
                parser.start();
                executor.setStreamHandler(streamHandler);
                int exitValue = executor.execute(command);
                IOUtils.closeQuietly(output);
                parser.join(MAX_PROCESS_WAIT);
                processes.addAll(parser.getProcesses());
                LOG.trace("finished '{}'", command);

                if (exitValue != 0) {
                    LOG.debug("error running '{}': exit value was {}", command, exitValue);
                }
            } catch (final Exception e) {
                LOG.debug("error running '{}'", command, e);
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(pis);
                IOUtils.closeQuietly(output);
            }
        }
    }

    if (processes.size() == 0) {
        LOG.warn("Unable to find any OpenNMS processes.");
    }

    return processes;
}

From source file:org.opennms.systemreport.SystemReportResourceLocator.java

@Override
public String slurpOutput(final String commandString, final boolean ignoreExitCode) {
    final CommandLine command = CommandLine.parse(commandString);
    LOG.debug("running: {}", commandString);

    final Map<String, String> environment = new HashMap<String, String>(System.getenv());
    environment.put("COLUMNS", "2000");
    DataInputStream input = null;
    PipedInputStream pis = null;/*from w w  w  . ja  va  2  s .  c  o m*/
    OutputSuckingParser parser = null;
    String outputText = null;
    final DefaultExecutor executor = new DefaultExecutor();

    final PipedOutputStream output = new PipedOutputStream();
    final PumpStreamHandler streamHandler = new PumpStreamHandler(output, output);
    executor.setWatchdog(new ExecuteWatchdog(m_maxProcessWait));
    executor.setStreamHandler(streamHandler);
    if (ignoreExitCode) {
        executor.setExitValues(null);
    }

    try {
        LOG.trace("executing '{}'", commandString);
        pis = new PipedInputStream(output);
        input = new DataInputStream(pis);
        parser = new OutputSuckingParser(input);
        parser.start();
        final int exitValue = executor.execute(command, environment);
        IOUtils.closeQuietly(output);
        parser.join(m_maxProcessWait);
        if (!ignoreExitCode && exitValue != 0) {
            LOG.debug("error running '{}': exit value was {}", commandString, exitValue);
        } else {
            outputText = parser.getOutput();
        }
        LOG.trace("finished '{}'", commandString);
    } catch (final Exception e) {
        LOG.debug("Failed to run '{}'", commandString, e);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(pis);
    }

    return outputText;
}

From source file:org.openqa.selenium.iphone.IPhoneSimulatorBinary.java

public void shutdown() {
    try {/*from  ww  w  .  j a v a2s.co  m*/
        File scriptFile = File.createTempFile("iWebDriver.kill.", ".script");
        FileWriter writer = new FileWriter(scriptFile);
        writer.write("ps ax | grep 'iPhone Simulator' | grep -v grep | awk '{print $1}' | xargs kill");
        writer.flush();
        writer.close();
        FileHandler.makeExecutable(scriptFile);
        CommandLine killCommandLine = CommandLine.parse(scriptFile.getAbsolutePath());
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(null, null));
        getOutputIgnoringExecutor().execute(killCommandLine);
    } catch (Exception ignored) {
    }
    // Wait until the process really quits (nothing is bound to port 3001)
    // TODO something other than Thread.sleep
    // client = new HttpClientFactory().getHttpClient();
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    exitCode = null;
}

From source file:org.openqa.selenium.iphone.IPhoneSimulatorBinary.java

private static Executor getOutputIgnoringExecutor() {
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(null, null));
    return executor;
}

From source file:org.openqa.selenium.iphone.IPhoneSimulatorCommandExecutorTest.java

private void killIphoneSimulatorProcesses() {
    try {//from   w  w w.  ja v  a2s.  c  om
        File scriptFile = File.createTempFile("iWebDriver.kill.", ".script");
        FileWriter writer = new FileWriter(scriptFile);
        writer.write("ps ax | grep 'iPhone Simulator' | grep -v grep | awk '{print $1}' | xargs kill");
        writer.flush();
        writer.close();
        FileHandler.makeExecutable(scriptFile);
        CommandLine killCommandLine = CommandLine.parse(scriptFile.getAbsolutePath());
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(null, null));
        executor.execute(killCommandLine);
        // need to wait for the port to free up
        // TODO same as needs to be done in IPhoneSimulatorBinary
        Thread.sleep(5000);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}