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

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

Introduction

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

Prototype

public String[] toStrings() 

Source Link

Document

Returns the command line as an array of strings.

Usage

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Start the TG server synchronously./*from  w w  w .  j av  a  2s  .  c  o  m*/
 * 
 * @param timeout
 *            Number of milliseconds allowed to start the server
 * @throws TGStartException Start operation fails
 */
public void start(long timeout) throws TGStartException {

    if (this.configFile == null)
        throw new TGStartException("TGServer - Config file not set");

    if (this.logFile == null)
        this.setLogFile("tgdb_" + this.dbName);

    //this.outStream = new ByteArrayOutputStream(); // reset
    //this.errStream = new ByteArrayOutputStream(); // reset
    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    Executor tgExec = new DefaultExecutor();
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    tgExec.setStreamHandler(psh);
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    tgCL.addArguments(new String[] { "-s", "-c", this.configFile.getAbsolutePath(), "-l", this.logFileBase });

    System.out.println("TGServer - Starting " + StringUtils.toString(tgCL.toStrings(), " "));
    try {
        tgExec.execute(tgCL, resultHandler);
    } catch (IOException ioe) {
        try {
            Thread.sleep(1000); // Make sure output/error fill up
        } catch (InterruptedException ie) {
            ;
        }
        throw new TGStartException(ioe.getMessage());
    }

    if (timeout > 0) {
        Calendar future = Calendar.getInstance();
        future.add(Calendar.MILLISECOND, (int) timeout);
        boolean started = false;
        boolean error = false;
        List<String> acceptedClients = new ArrayList<String>();
        String acceptedClient;
        while (!future.before(Calendar.getInstance())) {
            try {
                Thread.sleep(1000);
                BufferedReader reader = new BufferedReader(new StringReader(this.getOutput()));
                String line = reader.readLine();
                while (line != null) {
                    if (line.contains("Process pid:"))
                        this.setPid(Integer.parseInt(line.substring(line.lastIndexOf("Process pid:") + 12,
                                line.indexOf(",", line.lastIndexOf("Process pid:") + 12))));
                    if (line.contains("[Error]")) {
                        error = true;
                    }
                    if (line.contains("Accepting clients on")) {
                        started = true;
                        acceptedClient = line.substring(line.indexOf("- Accepting clients on") + 2);
                        if (!acceptedClients.contains(acceptedClient))
                            acceptedClients.add(acceptedClient);
                    }
                    line = reader.readLine();
                }
                reader.close();
                if (started)
                    break;
            } catch (Exception e) {
                throw new TGStartException("TGServer - " + e.getMessage());
            }
        }
        if (!started)
            throw new TGStartException(
                    "TGServer - Did not start on time (after " + timeout + " msec) - See log " + this.logFile);
        else {
            this.running = true;
            System.out.println("TGServer - Started successfully with pid " + this.pid + " :");
            System.out.println("\t\t- Log file: " + this.logFile);
            if (error)
                System.out.println("\t\t- With some error(s) - See log");
            for (String client : acceptedClients)
                System.out.println("\t\t- " + client);
            try {
                this.setBanner(this.getOutput());
            } catch (TGGeneralException tge) {
                throw new TGStartException(tge.getMessage());
            }
        }
    }
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Initialize the TG server synchronously. This Init operation blocks until
 * it is completed.//from  w  ww.  j a v  a  2  s .  c o  m
 * 
 * @param initFile
 *            TG server init config file
 * @param forceCreation
 *            Force creation. Delete all the data in the db directory first.
 * @param timeout
 *            Number of milliseconds allowed to initialize the server
 * @return the output stream of init operation 
 * @throws TGInitException
 *             Init operation fails or timeout occurs 
 */
public String init(String initFile, boolean forceCreation, long timeout) throws TGInitException {

    File initF = new File(initFile);
    if (!initF.exists())
        throw new TGInitException("TGServer - Init file '" + initFile + "' does not exist");
    try {
        this.setInit(initF);
    } catch (TGGeneralException e) {
        throw new TGInitException(e.getMessage());
    }

    //ByteArrayOutputStream output = new ByteArrayOutputStream();

    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    if (forceCreation)
        tgCL.addArguments(new String[] { "-i", "-f", "-Y", "-c", initFile, "-l", this.initLogFileBase });
    else
        tgCL.addArguments(new String[] { "-i", "-Y", "-c", initFile, "-l", this.initLogFileBase });

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGServer - Initializing " + StringUtils.toString(tgCL.toStrings(), " "));
    String output = "";
    try {
        tgExec.execute(tgCL);
        output = new String(Files.readAllBytes(Paths.get(this.getInitLogFile().toURI())));
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGInitException("TGServer - Init did not complete within " + timeout + " ms");
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up

            } catch (InterruptedException ie) {
                ;
            }
            throw new TGInitException("TGServer - Init failed: " + ee.getMessage(), output);
        }
    }
    try {
        this.setBanner(output);
    } catch (TGGeneralException tge) {
        throw new TGInitException(tge.getMessage());
    }

    if (output.contains("TGSuccess")) {
        System.out.println("TGServer - Initialized successfully");
        return output;
    } else
        throw new TGInitException("TGServer - Init failed", output);
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Invoke TG admin synchronously. //from   w  ww.j av a  2  s  . co m
 * Admin operation blocks until it is completed.
 * 
 * @param tgHome TG admin home
 * @param url Url to connect to TG server
 * @param user System User name
 * @param pwd System User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmd TG admin command file or command string
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String invoke(String tgHome, String url, String user, String pwd, String logFile, String logLevel,
        String cmd, int memSize, long timeout) throws TGAdminException {
    if (tgHome == null)
        throw new TGAdminException("TGAdmin - TGDB home is not defined");
    File ftgHome = new File(tgHome);
    if (!ftgHome.exists())
        throw new TGAdminException("TGAdmin - TGDB home '" + tgHome + "' does not exist");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(tgHome + "/bin"));

    CommandLine tgCL = new CommandLine((new File(tgHome + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }

    File cmdFile = null;
    if (cmd == null)
        throw new TGAdminException("TGAdmin - Command is required.");
    if (cmd.matches(
            "(?s)^(kill|show|describe|create|stop|info|checkpoint|dump|set|connect|disconnect|export|import|exit).*$")) {
        try {
            cmdFile = new File(tgHome + "/invokeAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), cmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }
    } else {
        cmdFile = new File(cmd);
    }

    if (!cmdFile.exists()) {
        throw new TGAdminException("TGAdmin - Command file '" + cmdFile + "' does not exist");
    }
    args.add("--file");
    args.add(cmdFile.getAbsolutePath());

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));

    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        TGAdmin.startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (url != null && !output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server " + url + " with user " + user,
                output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - TGAdmin.startProcTime;
    if (TGAdmin.showOperationBanner)
        System.out.println(
                "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Invoke TG admin synchronously. /*from  ww  w. j  ava 2  s.  c  o m*/
 * Admin operation blocks until it is completed.
 * 
 * @param url Url to connect to TG server
 * @param user User name
 * @param pwd User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmdFile TG admin command file - Need to exist before invoking admin
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public String invoke(String url, String user, String pwd, String logFile, String logLevel, String cmdFile,
        int memSize, long timeout) throws TGAdminException {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));

    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }
    if (cmdFile == null)
        throw new TGAdminException("TGAdmin - Command file is required.");
    args.add("--file");
    args.add(cmdFile);

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));
    long startProcTime = 0;
    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (!output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server", output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - startProcTime;
    System.out.println(
            "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:org.codehaus.mojo.exec.ExtendedExecutor.java

@Override
protected Process launch(CommandLine command, Map<String, String> env, File dir) throws IOException {
    if (dir != null && !dir.exists()) {
        throw new IOException(dir + " doesn't exist.");
    }//www .  jav  a 2 s.c  o  m
    ProcessBuilder pb = new ProcessBuilder(command.toStrings());
    pb.environment().putAll(env);
    pb.directory(dir);
    if (inheritIo) {
        pb.inheritIO();
    }
    return pb.start();
}

From source file:org.lucidj.launcher.Launcher.java

private void launch(String[] args) {
    System.out.println("Exec: " + java_exe);

    CommandLine cmdline = new CommandLine(java_exe);

    //----------/* w w  w  .ja va  2s. c om*/
    // JVM args
    //----------

    cmdline.addArgument("-server");
    cmdline.addArgument("-Xms128M");
    cmdline.addArgument("-Xmx1024M");
    cmdline.addArgument("-XX:+UnlockDiagnosticVMOptions");
    cmdline.addArgument("-XX:+UnsyncloadClass");
    cmdline.addArgument("-Djava.awt.headless=true");
    cmdline.addArgument("-Dcom.sun.management.jmxremote");

    //-----------
    // Classpath
    //-----------

    List<String> path_elements = new ArrayList<>();

    String classpath_extra = karaf_properties.getProperty(".classpath.extra");

    if (classpath_extra != null) {
        // TODO: HANDLE COMPOUND classpath_extra; HANDLE MULTIPLE .classpath.*
        // Get all exported classpath files
        File[] file_list = new File(classpath_extra).listFiles();

        // And add to classpath if found
        if (file_list != null) {
            for (int i = 0; i < file_list.length; i++) {
                if (file_list[i].isFile() && file_list[i].getName().toLowerCase().endsWith(".jar")) {
                    path_elements.add(file_list[i].getAbsolutePath());
                }
            }
        }
    }

    cmdline.addArgument("-classpath");
    cmdline.addArgument(string_join(path_separator, path_elements), false);

    //-------------
    // LucidJ args
    //-------------

    addArgument(cmdline, "system.home", System.getProperty("system.home"));
    addArgument(cmdline, "system.conf", System.getProperty("system.conf"));
    addArgument(cmdline, "system.bootstrap", System.getProperty("system.bootstrap"));
    addArgument(cmdline, "system.deploy", System.getProperty("system.deploy"));

    // Copy the parsed properties to command line
    for (String key : karaf_properties.stringPropertyNames()) {
        if (!key.startsWith(".")) {
            addArgument(cmdline, key, karaf_properties.getProperty(key));
        }
    }

    if (System.getProperty("user.conf") != null) {
        addArgument(cmdline, "user.conf", System.getProperty("user.conf"));
    }

    // Class to exec
    cmdline.addArgument(main_class);

    // Add class arguments
    if (args != null) {
        for (String arg : args) {
            cmdline.addArgument(arg);
        }
    }

    //------------------
    // Ready to launch!
    //------------------

    if (verbose) {
        String[] argv = cmdline.toStrings();

        for (int i = 0; i < argv.length; i++) {
            System.out.println("argv[" + i + "] = '" + argv[i] + "'");
        }
    }

    launch_cmdline(cmdline);
}

From source file:org.opennms.netmgt.measurements.impl.RrdtoolXportFetchStrategy.java

/**
 * {@inheritDoc}/*from   w  w w  .j a  va 2  s .com*/
 */
@Override
protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows,
        Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException {

    String rrdBinary = System.getProperty("rrd.binary");
    if (rrdBinary == null) {
        throw new RrdException("No RRD binary is set.");
    }

    final long startInSeconds = (long) Math.floor(start / 1000);
    final long endInSeconds = (long) Math.floor(end / 1000);

    long stepInSeconds = (long) Math.floor(step / 1000);
    // The step must be strictly positive
    if (stepInSeconds <= 0) {
        stepInSeconds = 1;
    }

    final CommandLine cmdLine = new CommandLine(rrdBinary);
    cmdLine.addArgument("xport");
    cmdLine.addArgument("--step");
    cmdLine.addArgument("" + stepInSeconds);
    cmdLine.addArgument("--start");
    cmdLine.addArgument("" + startInSeconds);
    cmdLine.addArgument("--end");
    cmdLine.addArgument("" + endInSeconds);
    if (maxrows > 0) {
        cmdLine.addArgument("--maxrows");
        cmdLine.addArgument("" + maxrows);
    }

    // Use labels without spaces when executing the xport command
    // These are mapped back to the requested labels in the response
    final Map<String, String> labelMap = Maps.newHashMap();

    int k = 0;
    for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) {
        final Source source = entry.getKey();
        final String rrdFile = entry.getValue();
        final String tempLabel = Integer.toString(++k);
        labelMap.put(tempLabel, source.getLabel());

        cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, Utils.escapeColons(rrdFile),
                Utils.escapeColons(source.getEffectiveDataSource()), source.getAggregation()));
        cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel));
    }

    // Use commons-exec to execute rrdtool
    final DefaultExecutor executor = new DefaultExecutor();

    // Capture stdout/stderr
    final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null));

    // Fail if we get a non-zero exit code
    executor.setExitValue(0);

    // Fail if the process takes too long
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);

    // Export
    RrdXport rrdXport;
    try {
        LOG.debug("Executing: {}", cmdLine);
        executor.execute(cmdLine);

        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString())));
        final JAXBContext jc = JAXBContext.newInstance(RrdXport.class);
        final Unmarshaller u = jc.createUnmarshaller();
        rrdXport = (RrdXport) u.unmarshal(source);
    } catch (IOException e) {
        throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ")
                + "' with stderr: " + stderr.toString(), e);
    } catch (SAXException | JAXBException e) {
        throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e);
    }

    final int numRows = rrdXport.getRows().size();
    final int numColumns = rrdXport.getMeta().getLegends().size();
    final long xportStartInMs = rrdXport.getMeta().getStart() * 1000;
    final long xportStepInMs = rrdXport.getMeta().getStep() * 1000;

    final long timestamps[] = new long[numRows];
    final double values[][] = new double[numColumns][numRows];

    // Convert rows to columns
    int i = 0;
    for (final XRow row : rrdXport.getRows()) {
        // Derive the timestamp from the start and step since newer versions
        // of rrdtool no longer include it as part of the rows
        timestamps[i] = xportStartInMs + xportStepInMs * i;
        for (int j = 0; j < numColumns; j++) {
            if (row.getValues() == null) {
                // NMS-7710: Avoid NPEs, in certain cases the list of values may be null
                throw new RrdException(
                        "The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries.");
            }
            values[j][i] = row.getValues().get(j);
        }
        i++;
    }

    // Map the columns by label
    // The legend entries are in the same order as the column values
    final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns);
    i = 0;
    for (String label : rrdXport.getMeta().getLegends()) {
        columns.put(labelMap.get(label), values[i++]);
    }

    return new FetchResults(timestamps, columns, xportStepInMs, constants);
}

From source file:org.opennms.web.rest.measurements.fetch.RrdtoolXportFetchStrategy.java

/**
 * {@inheritDoc}/*from w  ww .ja v  a  2  s. c  om*/
 */
@Override
protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows,
        Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException {

    String rrdBinary = System.getProperty("rrd.binary");
    if (rrdBinary == null) {
        throw new RrdException("No RRD binary is set.");
    }

    final long startInSeconds = (long) Math.floor(start / 1000);
    final long endInSeconds = (long) Math.floor(end / 1000);

    long stepInSeconds = (long) Math.floor(step / 1000);
    // The step must be strictly positive
    if (stepInSeconds <= 0) {
        stepInSeconds = 1;
    }

    final CommandLine cmdLine = new CommandLine(rrdBinary);
    cmdLine.addArgument("xport");
    cmdLine.addArgument("--step");
    cmdLine.addArgument("" + stepInSeconds);
    cmdLine.addArgument("--start");
    cmdLine.addArgument("" + startInSeconds);
    cmdLine.addArgument("--end");
    cmdLine.addArgument("" + endInSeconds);
    if (maxrows > 0) {
        cmdLine.addArgument("--maxrows");
        cmdLine.addArgument("" + maxrows);
    }

    // Use labels without spaces when executing the xport command
    // These are mapped back to the requested labels in the response
    final Map<String, String> labelMap = Maps.newHashMap();

    int k = 0;
    for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) {
        final Source source = entry.getKey();
        final String rrdFile = entry.getValue();
        final String tempLabel = Integer.toString(++k);
        labelMap.put(tempLabel, source.getLabel());

        cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, rrdFile, source.getAttribute(),
                source.getAggregation()));
        cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel));
    }

    // Use commons-exec to execute rrdtool
    final DefaultExecutor executor = new DefaultExecutor();

    // Capture stdout/stderr
    final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null));

    // Fail if we get a non-zero exit code
    executor.setExitValue(0);

    // Fail if the process takes too long
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);

    // Export
    RrdXport rrdXport;
    try {
        executor.execute(cmdLine);

        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString())));
        final JAXBContext jc = JAXBContext.newInstance(RrdXport.class);
        final Unmarshaller u = jc.createUnmarshaller();
        rrdXport = (RrdXport) u.unmarshal(source);
    } catch (IOException e) {
        throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ")
                + "' with stderr: " + stderr.toString(), e);
    } catch (SAXException | JAXBException e) {
        throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e);
    }

    final int numRows = rrdXport.getRows().size();
    final int numColumns = rrdXport.getMeta().getLegends().size();

    final long timestamps[] = new long[numRows];
    final double values[][] = new double[numColumns][numRows];

    // Convert rows to columns
    int i = 0;
    for (final XRow row : rrdXport.getRows()) {
        timestamps[i] = row.getTimestamp() * 1000;
        for (int j = 0; j < numColumns; j++) {
            if (row.getValues() == null) {
                // NMS-7710: Avoid NPEs, in certain cases the list of values may be null
                throw new RrdException(
                        "The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries.");
            }
            values[j][i] = row.getValues().get(j);
        }
        i++;
    }

    // Map the columns by label
    // The legend entries are in the same order as the column values
    final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns);
    i = 0;
    for (String label : rrdXport.getMeta().getLegends()) {
        columns.put(labelMap.get(label), values[i++]);
    }

    return new FetchResults(timestamps, columns, rrdXport.getMeta().getStep() * 1000, constants);
}

From source file:org.openremote.controller.protocol.shellexe.ShellExeCommand.java

private String executeCommand() {
    logger.debug("Will start shell command: " + commandPath + " and use params: " + commandParams);
    String result = "";
    Process proc = null;//w  ww .jav  a 2 s. c  om

    try {
        // Use the commons-exec to parse correctly the arguments, respecting quotes and spaces to separate parameters
        final CommandLine cmdLine = new CommandLine(commandPath);
        if (commandParams != null) {
            cmdLine.addArguments(commandParams);
        }
        proc = Runtime.getRuntime().exec(cmdLine.toStrings());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        final StringBuffer resultBuffer = new StringBuffer();
        boolean first = true;
        for (String tmp = reader.readLine(); tmp != null; tmp = reader.readLine()) {
            if (!first)
                resultBuffer.append("\n");
            first = false;
            resultBuffer.append(tmp);
        }
        result = resultBuffer.toString();
    } catch (IOException e) {
        logger.error("Could not execute shell command: " + commandPath, e);
    } finally {
        if (proc != null)
            proc.destroy();
    }
    logger.debug("Shell command: " + commandPath + " returned: " + result);
    return result;
}

From source file:org.sikuli.natives.LinuxUtil.java

@Override
public void checkLibAvailability() {
    List<CommandLine> commands = Arrays.asList(CommandLine.parse("wmctrl -m"),
            CommandLine.parse("xdotool version"), CommandLine.parse("killall --version"));
    String msg = "";
    for (CommandLine cmd : commands) {
        try {/*from  w  w w  .  j a v  a 2  s .  com*/
            DefaultExecutor executor = new DefaultExecutor();
            executor.setExitValue(0);
            //suppress system output
            executor.setStreamHandler(new PumpStreamHandler(null));
            executor.execute(cmd);
        } catch (IOException e) {
            String executable = cmd.toStrings()[0];
            if (executable.equals("wmctrl")) {
                wmctrlAvail = false;
            }
            if (executable.equals("xdotool")) {
                xdoToolAvail = false;
            }
            msg += "command '" + executable + "' is not executable\n";
        }
    }
    if (!msg.isEmpty()) {
        msg += "Please check the availability - some features might not work without!";
        Debug.error(msg);
    }
}