Search in sources :

Example 31 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project Robot by fo0.

the class Commander method execute.

public String execute(boolean shell, String homedir, String cmds) {
    if (cmds == null || cmds.isEmpty()) {
        Logger.info("stopped cmd command is empty");
        return null;
    }
    CommandLine cli = null;
    DefaultExecutor executor = null;
    switch(OSCheck.getOperatingSystemType()) {
        case Windows:
            cli = new CommandLine("cmd");
            if (shell) {
                cli.addArgument("/c ");
            }
            break;
        case Linux:
            cli = new CommandLine("/bin/bash");
            if (shell) {
                cli.addArgument("-c");
            }
            break;
    }
    cli.addArgument(cmds, false);
    Logger.debug("HomeDir: " + homedir + " => " + StringUtils.join(cli.getArguments(), ","));
    try {
        executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                try {
                    String str = String.valueOf((char) b);
                    if (listener != null)
                        listener.event(str);
                    buffer.append(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                error = true;
                try {
                    String str = String.valueOf((char) b);
                    if (listener != null)
                        listener.event(str);
                    buffer.append(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }));
        executor.execute(cli);
        executor.setWorkingDirectory(new File(homedir));
        try {
            executor.wait(30 * 1000);
        } catch (Exception e) {
        // TODO: handle exception
        }
    } catch (Exception e) {
        error = true;
        Logger.error("failed commander in Cmd: " + cli + " | " + e);
        e.printStackTrace();
    }
    return buffer.toString();
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) OutputStream(java.io.OutputStream) File(java.io.File) IOException(java.io.IOException)

Example 32 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project camel by apache.

the class DefaultExecCommandExecutor method execute.

@Override
public ExecResult execute(ExecCommand command) {
    notNull(command, "command");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    DefaultExecutor executor = prepareDefaultExecutor(command);
    // handle error and output of the process and write them to the given
    // out stream
    PumpStreamHandler handler = new PumpStreamHandler(out, err, command.getInput());
    executor.setStreamHandler(handler);
    CommandLine cl = toCommandLine(command);
    try {
        int exitValue = executor.execute(cl);
        // if the size is zero, we have no output, so construct the result
        // with null (required by ExecResult)
        InputStream stdout = out.size() == 0 ? null : new ByteArrayInputStream(out.toByteArray());
        InputStream stderr = err.size() == 0 ? null : new ByteArrayInputStream(err.toByteArray());
        ExecResult result = new ExecResult(command, stdout, stderr, exitValue);
        return result;
    } catch (ExecuteException ee) {
        LOG.error("ExecException while executing command: " + command.toString() + " - " + ee.getMessage());
        InputStream stdout = out.size() == 0 ? null : new ByteArrayInputStream(out.toByteArray());
        InputStream stderr = err.size() == 0 ? null : new ByteArrayInputStream(err.toByteArray());
        throw new ExecException("Failed to execute command " + command, stdout, stderr, ee.getExitValue(), ee);
    } catch (IOException ioe) {
        InputStream stdout = out.size() == 0 ? null : new ByteArrayInputStream(out.toByteArray());
        InputStream stderr = err.size() == 0 ? null : new ByteArrayInputStream(err.toByteArray());
        // use 0 as exit value as the executor didn't return the value
        int exitValue = 0;
        if (executor instanceof ExecDefaultExecutor) {
            // get the exit value from the executor as it captures this to work around the common-exec bug
            exitValue = ((ExecDefaultExecutor) executor).getExitValue();
        }
        // workaround to ignore if the stream was already closes due some race condition in commons-exec
        String msg = ioe.getMessage();
        if (msg != null && "stream closed".equals(msg.toLowerCase(Locale.ENGLISH))) {
            LOG.debug("Ignoring Stream closed IOException", ioe);
            ExecResult result = new ExecResult(command, stdout, stderr, exitValue);
            return result;
        }
        // invalid working dir
        LOG.error("IOException while executing command: " + command.toString() + " - " + ioe.getMessage());
        throw new ExecException("Unable to execute command " + command, stdout, stderr, exitValue, ioe);
    } finally {
        // the inputStream must be closed after the execution
        IOUtils.closeQuietly(command.getInput());
    }
}
Also used : ExecDefaultExecutor(org.apache.camel.component.exec.ExecDefaultExecutor) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ExecException(org.apache.camel.component.exec.ExecException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ExecEndpoint(org.apache.camel.component.exec.ExecEndpoint) ExecDefaultExecutor(org.apache.camel.component.exec.ExecDefaultExecutor) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) ByteArrayInputStream(java.io.ByteArrayInputStream) ExecuteException(org.apache.commons.exec.ExecuteException) ExecResult(org.apache.camel.component.exec.ExecResult)

Example 33 with PumpStreamHandler

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

the class RScriptExecutor method exec.

/**
 * Executes by given script by:
 *   - Searching both the classpath and the filesystem for the path
 *   - Copying the script at the given path to a temporary file and
 *     performing variable substitution with the arguments using Freemarker.
 *   - Invoking the script with commons-exec
 *   - Converting the input table to CSV and passing this to the process via stdin
 *   - Parsing stdout, expecting CSV output, and converting this to an immutable table
 */
public RScriptOutput exec(String script, RScriptInput input) throws RScriptException {
    Preconditions.checkNotNull(script, "script argument");
    Preconditions.checkNotNull(input, "input argument");
    // Grab the script/template
    Template template;
    try {
        template = m_freemarkerConfiguration.getTemplate(script);
    } catch (IOException e) {
        throw new RScriptException("Failed to read the script.", e);
    }
    // Create a temporary file
    File scriptOnDisk;
    try {
        scriptOnDisk = File.createTempFile("Rcsript", "R");
        scriptOnDisk.deleteOnExit();
    } catch (IOException e) {
        throw new RScriptException("Failed to create a temporary file.", e);
    }
    // Perform variable substitution and write the results to the temporary file
    try (FileOutputStream fos = new FileOutputStream(scriptOnDisk);
        Writer out = new OutputStreamWriter(fos)) {
        template.process(input.getArguments(), out);
    } catch (IOException | TemplateException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to process the template.", e);
    }
    // Convert the input matrix to a CSV string which will be passed to the script via stdin.
    // The table may be large, so we try and avoid writing it to disk
    final StringBuilder inputTableAsCsv;
    try {
        inputTableAsCsv = toCsv(input.getTable());
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to convert the input table to CSV.", e);
    }
    // Invoke Rscript against the script (located in a temporary file)
    CommandLine cmdLine = new CommandLine(RSCRIPT_BINARY);
    cmdLine.addArgument(scriptOnDisk.getAbsolutePath());
    // Use commons-exec to execute the process
    DefaultExecutor executor = new DefaultExecutor();
    // Use the CharSequenceInputStream in order to avoid explicitly converting
    // the StringBuilder a string and then an array of bytes.
    InputStream stdin = new CharSequenceInputStream(inputTableAsCsv, StandardCharsets.UTF_8);
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, stdin));
    // Fail if we get a non-zero exit code
    executor.setExitValue(0);
    // Fail if the process takes too long
    ExecuteWatchdog watchdog = new ExecuteWatchdog(SCRIPT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);
    // Execute
    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("An error occured while executing Rscript, or the requested script.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), e);
    }
    // Parse and return the results
    try {
        ImmutableTable<Long, String, Double> table = fromCsv(stdout.toString());
        return new RScriptOutput(table);
    } catch (Throwable t) {
        throw new RScriptException("Failed to parse the script's output.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), t);
    } finally {
        scriptOnDisk.delete();
    }
}
Also used : CharSequenceInputStream(org.apache.commons.io.input.CharSequenceInputStream) TemplateException(freemarker.template.TemplateException) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) CharSequenceInputStream(org.apache.commons.io.input.CharSequenceInputStream) InputStream(java.io.InputStream) ExecuteWatchdog(org.apache.commons.exec.ExecuteWatchdog) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Template(freemarker.template.Template) CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer)

Example 34 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project jackrabbit-oak by apache.

the class HybridIndexTest method dumpOpenFilePaths.

private static void dumpOpenFilePaths() throws IOException {
    String jvmName = ManagementFactory.getRuntimeMXBean().getName();
    String pid = jvmName.split("@")[0];
    CommandLine cl = new CommandLine("/bin/sh");
    cl.addArguments(new String[] { "-c", "lsof -p " + pid + " | grep '/nrt'" }, false);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(baos));
    executor.execute(cl);
    System.out.println(new String(baos.toByteArray()));
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 35 with PumpStreamHandler

use of org.apache.commons.exec.PumpStreamHandler in project my_curd by qinyou.

the class ToolNet method ping.

/**
 * ping ip并返回结果
 *
 * @param ip
 * @return 描述apache-common-exec 示例
 */
public static String ping(String ip) {
    String encode = "GBK";
    String os = System.getProperties().getProperty("os.name");
    if (os.toLowerCase().indexOf("windows") == -1) {
        encode = "UTF-8";
    }
    try {
        String command = "ping " + ip;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
        CommandLine commandline = CommandLine.parse(command);
        DefaultExecutor exec = new DefaultExecutor();
        exec.setExitValues(null);
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
        exec.setStreamHandler(streamHandler);
        exec.execute(commandline);
        String out = outputStream.toString(encode);
        String error = errorStream.toString(encode);
        return out + error;
    } catch (Exception e) {
        LOG.error("ping task failed.", e);
        return e.toString();
    }
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Aggregations

PumpStreamHandler (org.apache.commons.exec.PumpStreamHandler)59 DefaultExecutor (org.apache.commons.exec.DefaultExecutor)50 CommandLine (org.apache.commons.exec.CommandLine)45 IOException (java.io.IOException)33 ByteArrayOutputStream (java.io.ByteArrayOutputStream)29 ExecuteWatchdog (org.apache.commons.exec.ExecuteWatchdog)23 ExecuteException (org.apache.commons.exec.ExecuteException)22 File (java.io.File)17 DefaultExecuteResultHandler (org.apache.commons.exec.DefaultExecuteResultHandler)9 Executor (org.apache.commons.exec.Executor)9 InputStream (java.io.InputStream)5 OutputStream (java.io.OutputStream)5 HashMap (java.util.HashMap)5 ExecuteStreamHandler (org.apache.commons.exec.ExecuteStreamHandler)5 PipedInputStream (java.io.PipedInputStream)4 PipedOutputStream (java.io.PipedOutputStream)4 LogOutputStream (org.apache.commons.exec.LogOutputStream)4 FileOutputStream (java.io.FileOutputStream)3 URL (java.net.URL)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3