Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

In this page you can find the example usage for java.lang ProcessBuilder redirectErrorStream.

Prototype

boolean redirectErrorStream

To view the source code for java.lang ProcessBuilder redirectErrorStream.

Click Source Link

Usage

From source file:org.jenkinsci.plugins.proccleaner.PsBasedUnixProcessTree.java

@Override
public PsBasedProcessTree createProcessTreeFor(String user) throws InterruptedException, IOException {
    String[] cmd = { "ps", "-u", user, "-o", "pid,ppid,args" };
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.redirectErrorStream(true);
    final Process proc = pb.start();
    final StringWriter writer = new StringWriter();

    try {//from   ww w . j a  v  a 2 s  . co m
        IOUtils.copy(proc.getInputStream(), writer);
    } catch (IOException e) {
        LOGGER.warning("'ps' command invocation IOException occurred!");
    }

    BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
    if (proc.waitFor() != 0) {
        LOGGER.warning("'ps' command invocation " + ArrayUtils.toString(cmd) + " failed! Return code: "
                + proc.exitValue());
        LOGGER.fine("Received output from 'ps' command invocation follows:");

        if (getLog() != null) {
            getLog().println("WARNING: 'ps' command invocation " + ArrayUtils.toString(cmd)
                    + " failed! Return code: " + proc.exitValue());
            getLog().println("DEBUG: Received output from 'ps' command invocation follows:");
        }

        String line;
        while ((line = reader.readLine()) != null) {
            LOGGER.fine(line);
            if (getLog() != null)
                getLog().println("DEBUG: '" + line + "'");
        }
        return null;
    }

    String line = reader.readLine(); // first line should be "PID  PPID COMMAND" - skip it
    if (StringUtils.isEmpty(line)) {
        LOGGER.fine("Unrecognized output from 'ps' command invocation! Output is empty!");
        if (getLog() != null) {
            getLog().println("DEBUG: Unrecognized output from 'ps' command invocation! Output is empty!");
        }
        return null;

    }
    if (!line.matches("^\\s*PID\\s*PPID\\s*(COMMAND|ARGS)\\s*$")) {
        LOGGER.fine("Unrecognized first output line from 'ps' command invocation! Was: '" + line + "'");
        if (getLog() != null) {
            getLog().println(
                    "DEBUG: Unrecognized first output line from 'ps' command invocation! Was: '" + line + "'");
        }
        return null;
    }

    PsBasedProcessTree ptree = new PsBasedUnixProcessTree();
    while ((line = reader.readLine()) != null) {
        if (getLog() != null)
            getLog().println("DEBUG: '" + line + "'");
        ptree.addProcess(line);
    }
    ptree.setLog(getLog());
    return ptree;
}

From source file:ape.NetworkDropPacketsCommand.java

/**
 * This method implement the event by using the netem module
 * @param percent The percentage of packets that are to be dropped
 * @param period The duration that the packet loss should last
 * @return True if the execution was successful, false if an error occurred 
 * @throws IOException/*  w ww.  j ava  2s .  c om*/
 */
private boolean executecommand(double percent, double period) throws IOException {
    String cmd = "tc qdisc add dev eth0 root netem loss " + percent + "% && sleep " + period
            + " && tc qdisc del dev eth0 root netem";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        System.err.println(
                "Executing network connection simulation catches IOException, enter VERBOSE mode to see the Stack Trace");
        e.printStackTrace();
        return false;
    }

    try {
        if (p.waitFor() != 0) {
            System.err.println("Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");

            ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem");
            Process ptmp = tmp2.start();
            if (ptmp.waitFor() == 0)
                System.out.println("Connection resumed");
            else {
                System.out.println("Connection resumed failed");
                return false;
            }

            return false;
        }
    } catch (InterruptedException e1) {
        e1.printStackTrace();
        return false;
    }

    return true;
}

From source file:ca.canucksoftware.systoolsmgr.CommandLine.java

public boolean doCmd() {
    try {/*  w w  w. j a v a2 s  .c om*/
        response = null;
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(false);
        Process p = pb.start();
        String stdout = getTextFromStream(p.getInputStream());
        String stderr = getTextFromStream(p.getErrorStream());
        if (p.waitFor() != 0) {
            returnCode = p.exitValue();
        } else {
            returnCode = 0;
        }
        if (returnCode == 0) {
            response = stdout;
        } else {
            response = stderr;
        }
    } catch (Exception e) {
        response = e.getMessage();
        returnCode = -1;
    }
    return (returnCode == 0);
}

From source file:org.ostara.cmd.BaseCmdLineCmd.java

protected void executeCommand(ICmdResult result, List<String> cmd, String cmdExecDir, boolean wait) {
    Process p = null;/*from   www  . ja v a 2 s  .  c  om*/
    ProcessCall processCall = null;
    ProcessCallOutput output = null;

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

    // For windows system
    if (SystemUtils.IS_OS_WINDOWS) {
        cmdLine.add("cmd.exe");
        cmdLine.add("/C");
    }

    cmdLine.addAll(cmd);

    int retry = 0;
    Exception error = null;
    while (retry < 3) {
        try {

            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.redirectErrorStream(true);
            processBuilder.directory(new File(cmdExecDir));

            logger.info("Executing process: " + cmdLine);

            p = processBuilder.command(cmdLine).start();
            if (wait) {
                processCall = new ProcessCall(p);
                output = processCall.call();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            error = e;
            retry++;
            continue;
        }
        break;
    }

    if (output == null) {
        result.setException(error);
    } else if (output.exitValue != 0) {
        result.setException(new RuntimeException(
                "Failed to execute command(%" + getClass().getName() + "%), rtn value:" + output.exitValue));
    } else {
        result.setMessage(output.output);
    }
}

From source file:npm.modules.java

public void excutecmdwindow(String[] command) throws Exception {
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.redirectErrorStream(true);
    builder.start();/*  w  ww  . ja  va  2  s  .  c o  m*/
}

From source file:ome.formats.importer.transfers.AbstractExecFileTransfer.java

/**
 * Executes a local command and fails on non-0 return codes.
 *
 * @param file/*from w  ww .j  ava  2s.  co  m*/
 * @param location
 * @throws IOException
 */
protected void exec(File file, File location) throws IOException {
    ProcessBuilder pb = createProcessBuilder(file, location);
    pb.redirectErrorStream(true);
    Process process = pb.start();
    Integer rcode = null;
    while (rcode == null) {
        try {
            rcode = process.waitFor();
            break;
        } catch (InterruptedException e) {
            continue;
        }
    }
    if (rcode == null || rcode.intValue() != 0) {
        log.error("transfer process returned {}", rcode);
        throw new RuntimeException("transfer process returned " + rcode);
    }
}

From source file:ape.SuspendNodeCommand.java

public boolean runImpl(String[] args) throws IOException {
    String nodeType = null;//from  w w  w. ja  va  2s.com
    nodeType = args[0];

    if (Main.VERBOSE)
        System.out.println("Nodetype" + args[0]);

    Process p;

    if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker")
            || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) {
        System.out.println("Suspend is about to execute the following command:");
        String cmd = "echo \"kill -19 \\$(ps aux | grep -i " + nodeType
                + " | grep -v grep | grep -v ape | awk -F ' '  '{print \\$2}')\" > kill-node.sh && chmod +x kill-node.sh && ./kill-node.sh";
        System.out.println(cmd);
        /**
         * The above code block checks to see if a valid node type is passed.
         * If it is, then it sends a very ugly bash command to kill the corresponding process.
         * It gets a list of running processes, then greps it for the node type, then 
         * removes the result generated by running grep, then it gets the process ID of that line 
         * 
         */

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
        pb.redirectErrorStream(true);
        Process sh;
        try {
            sh = pb.start();
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            sh.waitFor();
        } catch (InterruptedException e) {
            System.out.println("The suspend node command caught an Interrupt...");
            e.printStackTrace();
            return false;
        }
        InputStream shIn = sh.getInputStream();
        int c;
        while ((c = shIn.read()) != -1) {
            System.out.write(c);
        }
        try {
            shIn.close();
        } catch (IOException e) {
            System.out.println("Could not close InputStream from the suspend process.");
            e.printStackTrace();
            return false;
        }
        return true;
    } else {
        System.err.println("Invalid node type.");
        return false;
    }
}

From source file:mitm.common.sms.transport.gnokii.Gnokii.java

/**
 * Sends the message to the number./*from  ww w .  j  a v  a  2s  .  c o m*/
 */
public String sendSMS(String phoneNumber, String message) throws GnokiiException {
    List<String> cmd = new LinkedList<String>();

    cmd.add(GNOKII_BIN);
    cmd.add("--sendsms");
    cmd.add(phoneNumber);

    if (maxMessageSize != DEFAULT_MAX_MESSAGE_SIZE) {
        cmd.add("-l");
        cmd.add(Integer.toString(maxMessageSize));
    }

    if (requestForDeliveryReport) {
        cmd.add("-r");
    }

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        byte[] bytes = MiscStringUtils.toAsciiBytes(message);

        IOUtils.write(bytes, process.getOutputStream());

        process.getOutputStream().close();

        String output = IOUtils.toString(process.getInputStream());

        int exitValue;

        try {
            exitValue = process.waitFor();
        } catch (InterruptedException e) {
            throw new GnokiiException("Error sending SMS. Output: " + output);
        }

        if (exitValue != 0) {
            throw new GnokiiException("Error sending SMS. Output: " + output);
        }

        return output;
    } catch (IOException e) {
        throw new GnokiiException(e);
    }
}

From source file:ape.KillNodeCommand.java

public boolean runImpl(String[] args) throws ParseException, IOException {
    if (Main.VERBOSE) {
        System.out.println("NodeType: " + args[0]);
    }/*from  w ww  .ja  v a 2s .  co m*/

    String nodeType = args[0];

    if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker")
            || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) {
        System.out.println("Kill is about to execute the following command:");

        /**
         * The line of code below sends a very ugly bash command to kill the corresponding process.
         * It gets a list of running processes, then greps it for the node type, then 
         * removes the result generated by running grep, then it gets the process ID of that line 
         * 
         */
        String cmd = "echo \"kill -9 \\$(ps -ef | grep -i " + nodeType
                + " | grep -v grep | grep -v ape | awk -F ' '  '{print \\$2}')\" > /tmp/kill-node.sh && chmod +x /tmp/kill-node.sh && /tmp/./kill-node.sh && rm /tmp/kill-node.sh";

        System.out.println(cmd);

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
        pb.redirectErrorStream(true);
        Process sh = pb.start();
        InputStream shIn = sh.getInputStream();
        try {
            if (sh.waitFor() != 0) {
                System.out.println("Executing Kill Command failed");
                return false;
            }
        } catch (InterruptedException e) {
            System.out.println(
                    "The kill command was killed before it could kill its target process.  Kind of ironic really...");
            e.printStackTrace();
            throw new RuntimeException();
        }
        int c;
        while ((c = shIn.read()) != -1) {
            System.out.write(c);
        }
        try {
            shIn.close();
        } catch (IOException e) {
            System.out.println("Could not close InputStream from the kill process.");
            e.printStackTrace();
            return false;
        }
    }

    else {
        System.out.println("Invalid node type: " + nodeType);
        System.out.println("Should be one of the following: DataNode, TaskTracker, NameNode, JobTracker.");
        return false;
    }
    return true;
}

From source file:org.apache.kylin.common.util.CliCommandExecutor.java

private Pair<Integer, String> runNativeCommand(String command, Logger logAppender) throws IOException {
    String[] cmd = new String[3];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {/*from   w w w  .  ja va 2s . c  om*/
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }
    cmd[2] = command;

    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process proc = builder.start();

    BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line;
    StringBuilder result = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        result.append(line).append('\n');
        if (logAppender != null) {
            logAppender.log(line);
        }
    }

    try {
        int exitCode = proc.waitFor();
        return Pair.newPair(exitCode, result.toString());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException(e);
    }
}