Example usage for org.apache.commons.exec CommandLine parse

List of usage examples for org.apache.commons.exec CommandLine parse

Introduction

In this page you can find the example usage for org.apache.commons.exec CommandLine parse.

Prototype

public static CommandLine parse(final String line) 

Source Link

Document

Create a command line from a string.

Usage

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   w ww  . j  a v a 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.system.LsofReportPlugin.java

@Override
public TreeMap<String, Resource> getEntries() {
    final TreeMap<String, Resource> map = new TreeMap<String, Resource>();
    String lsofOutput = null;/*w w w  .j a v a 2 s . com*/

    final String lsof = findBinary("lsof");

    if (lsof != null) {
        lsofOutput = slurpOutput(CommandLine.parse(lsof), false);
    }

    if (lsofOutput != null) {
        File tempFile = createTemporaryFileFromString(lsofOutput);
        if (tempFile != null) {
            map.put("Output", new FileSystemResource(tempFile));
        }
    }

    return map;
}

From source file:org.opennms.systemreport.system.ThreadReportPlugin.java

private void triggerThreadDump() {
    String kill = findBinary("kill");

    if (kill != null) {
        for (final Integer pid : getOpenNMSProcesses()) {
            LOG.debug("pid = {}", pid);
            CommandLine command = CommandLine.parse(kill + " -3 " + pid.toString());
            try {
                LOG.trace("running '{}'", command);
                DefaultExecutor executor = new DefaultExecutor();
                executor.setWatchdog(new ExecuteWatchdog(5000));
                int exitValue = executor.execute(command);
                LOG.trace("finished '{}'", command);
                if (exitValue != 0) {
                    LOG.warn("'{}' exited non-zero: {}", command, exitValue);
                }/*from  w ww .  ja v a2  s.  c  om*/
            } catch (final Exception e) {
                LOG.warn("Unable to run kill -3 on '{}': you might need to run system-report as root.", pid, e);
            }
        }
    }
}

From source file:org.opennms.systemreport.system.TopReportPlugin.java

@Override
public TreeMap<String, Resource> getEntries() {
    final TreeMap<String, Resource> map = new TreeMap<String, Resource>();

    final String top = findBinary("top");

    String topOutput = null;/*from w  w w.j a  v a  2s.co  m*/

    if (top != null) {
        topOutput = slurpOutput(CommandLine.parse(top + " -h"), true);

        if (topOutput.contains("-b") && topOutput.contains("-n")) {
            topOutput = slurpOutput(CommandLine.parse(top + " -n 1 -b"), false);
        } else if (topOutput.contains("-l")) {
            topOutput = slurpOutput(CommandLine.parse(top + " -l 1"), false);
        } else {
            topOutput = null;
        }
    }

    if (topOutput != null) {
        File tempFile = createTemporaryFileFromString(topOutput);
        if (tempFile != null) {
            map.put("Output", new FileSystemResource(tempFile));
        }
    }

    return map;
}

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  ww.  j a  v a  2 s  .co  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

/**
 * Creates a new IPhoneSimulatorBinary that will run the given application on the iPhone
 * Simulator. The simulator will be run using the SDK specified by the
 * {@code webdriver.iphone.sdk} system property.
 * //w w w  .  j av a 2 s. c  o  m
 * @param iWebDriverApp Path to the executable to run on the simulator. This file should specify
 *        the executable that is an immediate child of the {@code iwebDriver.app} directory.
 * @throws IOException If an I/O error occurs.
 */
public IPhoneSimulatorBinary(File iWebDriverApp) {
    System.out.println(String.format("%s launch %s --exit", getIphoneSimPath(),
            iWebDriverApp.getParentFile().getAbsoluteFile()));
    this.commandLine = CommandLine.parse(String.format("%s launch %s --exit", getIphoneSimPath(),
            iWebDriverApp.getParentFile().getAbsoluteFile()));
}

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

public void shutdown() {
    try {/*  w ww  .j a v a  2  s.  c o  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.IPhoneSimulatorCommandExecutorTest.java

private void killIphoneSimulatorProcesses() {
    try {//from   ww w .  j a  va2  s. 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));
        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);
    }
}

From source file:org.robovm.eclipse.internal.AbstractLaunchConfigurationDelegate.java

private List<String> splitArgs(String args) {
    if (args == null || args.trim().length() == 0) {
        return Collections.emptyList();
    }/*from  w ww  .j  a  va  2 s .c o m*/
    String[] parts = CommandLine.parse("foo " + args).toStrings();
    if (parts.length <= 1) {
        return Collections.emptyList();
    }
    List<String> result = new ArrayList<String>(parts.length - 1);
    for (int i = 1; i < parts.length; i++) {
        result.add(unquoteArg(parts[i]));
    }
    return result;
}

From source file:org.robovm.idea.compilation.RoboVmCompileTask.java

public static List<String> splitArgs(String args) {
    if (args == null || args.trim().length() == 0) {
        return new ArrayList<String>();
    }/* www . j  a  va  2 s.  co m*/
    String[] parts = CommandLine.parse("foo " + args).toStrings();
    if (parts.length <= 1) {
        return Collections.emptyList();
    }
    List<String> result = new ArrayList<String>(parts.length - 1);
    for (int i = 1; i < parts.length; i++) {
        result.add(unquoteArg(parts[i]));
    }
    return result;
}