Search in sources :

Example 16 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project jstorm by alibaba.

the class JStormUtils method launchProcess.

/**
     * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler
     * If it is frontend, ByteArrayOutputStream.toString will return the calling result
     * <p/>
     * This function will ignore whether the command is successfully executed or not
     *
     * @param command       command to be executed
     * @param environment   env vars
     * @param workDir       working directory
     * @param resultHandler exec result handler
     * @return output stream
     * @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)) {
            cmd.addArgument(cmdItem);
        }
    }
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    if (!StringUtils.isBlank(workDir)) {
        executor.setWorkingDirectory(new File(workDir));
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    executor.setStreamHandler(streamHandler);
    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException ignored) {
    }
    return out;
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteException(org.apache.commons.exec.ExecuteException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 17 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project openhab1-addons by openhab.

the class ExecBinding method executeCommandAndWaitResponse.

/**
     * <p>
     * Executes <code>commandLine</code>. Sometimes (especially observed on
     * MacOS) the commandLine isn't executed properly. In that cases another
     * exec-method is to be used. To accomplish this please use the special
     * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
     * delimiter it is split into a String[] array and the special exec-method
     * is used.
     * </p>
     * <p>
     * A possible {@link IOException} gets logged but no further processing is
     * done.
     * </p>
     *
     * @param commandLine the command line to execute
     * @return response data from executed command line
     */
private String executeCommandAndWaitResponse(String commandLine) {
    String retval = null;
    CommandLine cmdLine = null;
    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);
        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);
    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);
    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);
    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }
    return retval;
}
Also used : DefaultExecuteResultHandler(org.apache.commons.exec.DefaultExecuteResultHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) CommandLine(org.apache.commons.exec.CommandLine) Executor(org.apache.commons.exec.Executor) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) ExecuteException(org.apache.commons.exec.ExecuteException)

Example 18 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project sakuli by ConSol.

the class CommandLineUtil method runCommand.

public static CommandLineResult runCommand(String command, boolean throwException) throws SakuliException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    CommandLineResult result = new CommandLineResult();
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(outputStream, error));
        int exitCode = executor.execute(CommandLine.parse(command));
        result.setExitCode(exitCode);
        result.setOutput(error.toString() + outputStream.toString());
    } catch (Exception e) {
        if (throwException) {
            throw new SakuliException(e, String.format("Error during execution of command '%s': %s", command, error.toString()));
        }
        result.setExitCode(resolveExitCode(e.getMessage()));
        result.setOutput(e.getMessage());
    }
    return result;
}
Also used : PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) SakuliException(org.sakuli.exceptions.SakuliException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SakuliException(org.sakuli.exceptions.SakuliException)

Example 19 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project opennms by OpenNMS.

the class SystemReportResourceLocator method slurpOutput.

@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;
    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;
}
Also used : HashMap(java.util.HashMap) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) PipedOutputStream(java.io.PipedOutputStream) PipedInputStream(java.io.PipedInputStream) DataInputStream(java.io.DataInputStream) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler)

Example 20 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project opennms by OpenNMS.

the class AbstractSystemReportPlugin method getOpenNMSProcesses.

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;
    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;
}
Also used : DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) PipedOutputStream(java.io.PipedOutputStream) PipedInputStream(java.io.PipedInputStream) DataInputStream(java.io.DataInputStream) IOException(java.io.IOException) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) PsParser(org.opennms.systemreport.system.PsParser) HashSet(java.util.HashSet)

Aggregations

PumpStreamHandler (org.apache.commons.exec.PumpStreamHandler)25 DefaultExecutor (org.apache.commons.exec.DefaultExecutor)20 CommandLine (org.apache.commons.exec.CommandLine)19 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 IOException (java.io.IOException)16 ExecuteException (org.apache.commons.exec.ExecuteException)11 ExecuteWatchdog (org.apache.commons.exec.ExecuteWatchdog)10 File (java.io.File)5 InputStream (java.io.InputStream)4 PipedInputStream (java.io.PipedInputStream)4 PipedOutputStream (java.io.PipedOutputStream)4 OutputStream (java.io.OutputStream)3 OutputStreamWriter (java.io.OutputStreamWriter)3 Map (java.util.Map)3 ExecuteResultHandler (org.apache.commons.exec.ExecuteResultHandler)3 ExecuteStreamHandler (org.apache.commons.exec.ExecuteStreamHandler)3 Executor (org.apache.commons.exec.Executor)3 BufferedWriter (java.io.BufferedWriter)2 DataInputStream (java.io.DataInputStream)2 FileOutputStream (java.io.FileOutputStream)2