Search in sources :

Example 36 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor 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 37 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor 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 38 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor 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)

Example 39 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project robovm by robovm.

the class Executor method exec.

public int exec() throws ExecuteException, IOException {
    CommandLine commandLine = generateCommandLine();
    logCommandLine(commandLine);
    try {
        return initExecutor(new DefaultExecutor()).execute(commandLine, generateEnv());
    } catch (ExecuteException e) {
        ExecuteException ex = new ExecuteException("Command '" + commandLine + "' failed ", e.getExitValue());
        ex.setStackTrace(e.getStackTrace());
        throw ex;
    }
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ExecuteException(org.apache.commons.exec.ExecuteException)

Example 40 with DefaultExecutor

use of org.apache.commons.exec.DefaultExecutor in project robovm by robovm.

the class ObjectFileTest method testLineNumberInfo.

@Test
public void testLineNumberInfo() throws Exception {
    String cc = "gcc";
    String symbolPrefix = "";
    if (System.getProperty("os.name").toLowerCase().contains("mac")) {
        cc = "clang";
        symbolPrefix = "_";
    }
    File cFile = File.createTempFile(getClass().getSimpleName(), ".c");
    FileUtils.writeStringToFile(cFile, "int main() {\n" + "  return 0;\n" + "}\n");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(cFile.getParentFile());
    executor.execute(new CommandLine(cc).addArgument("-g").addArgument("-c").addArgument(cFile.getAbsolutePath()));
    List<LineInfo> mainLineInfos = null;
    File oFile = new File(cFile.getParentFile(), cFile.getName().substring(0, cFile.getName().lastIndexOf('.')) + ".o");
    try (ObjectFile objectFile = ObjectFile.load(oFile)) {
        for (Symbol symbol : objectFile.getSymbols()) {
            if (symbol.getSize() > 0) {
                List<LineInfo> lineInfos = objectFile.getLineInfos(symbol);
                if (!lineInfos.isEmpty() && symbol.getName().equals(symbolPrefix + "main")) {
                    mainLineInfos = lineInfos;
                    break;
                }
            }
        }
    }
    assertNotNull(mainLineInfos);
    // Assert that the info for main() contains lines 1 and 2 and possibly 3
    Set<Integer> lineNumbers = new HashSet<>();
    for (LineInfo lineInfo : mainLineInfos) {
        lineNumbers.add(lineInfo.getLineNumber());
    }
    assertTrue(lineNumbers.size() >= 2 && lineNumbers.size() <= 3);
    assertTrue(lineNumbers.contains(1));
    assertTrue(lineNumbers.contains(2));
    if (lineNumbers.size() == 3) {
        assertTrue(lineNumbers.contains(3));
    }
}
Also used : CommandLine(org.apache.commons.exec.CommandLine) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) File(java.io.File) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

DefaultExecutor (org.apache.commons.exec.DefaultExecutor)82 CommandLine (org.apache.commons.exec.CommandLine)62 PumpStreamHandler (org.apache.commons.exec.PumpStreamHandler)47 IOException (java.io.IOException)36 ExecuteWatchdog (org.apache.commons.exec.ExecuteWatchdog)34 ExecuteException (org.apache.commons.exec.ExecuteException)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)26 File (java.io.File)25 Executor (org.apache.commons.exec.Executor)12 DefaultExecuteResultHandler (org.apache.commons.exec.DefaultExecuteResultHandler)9 ShutdownHookProcessDestroyer (org.apache.commons.exec.ShutdownHookProcessDestroyer)9 HashMap (java.util.HashMap)5 Test (org.junit.Test)5 URL (java.net.URL)4 Properties (java.util.Properties)4 LogOutputStream (org.apache.commons.exec.LogOutputStream)4 InputStream (java.io.InputStream)3 PipedInputStream (java.io.PipedInputStream)3 PipedOutputStream (java.io.PipedOutputStream)3 HashSet (java.util.HashSet)3