Example usage for java.lang Process getErrorStream

List of usage examples for java.lang Process getErrorStream

Introduction

In this page you can find the example usage for java.lang Process getErrorStream.

Prototype

public abstract InputStream getErrorStream();

Source Link

Document

Returns the input stream connected to the error output of the process.

Usage

From source file:com.tc.process.Exec.java

@SuppressWarnings("resource")
public static Result execute(final Process process, String cmd[], String outputLog, byte[] input,
        File workingDir, final long timeout) throws Exception {
    final AtomicBoolean processFinished = new AtomicBoolean();
    if (timeout > 0) {
        Thread timeoutThread = new Thread() {
            @Override//from w  ww .  java 2 s . co  m
            public void run() {
                ThreadUtil.reallySleep(timeout);
                if (!processFinished.get()) {
                    process.destroy();
                }
            }
        };
        timeoutThread.start();
    }

    Thread inputThread = new InputPumper(input == null ? new byte[] {} : input, process.getOutputStream());

    StreamCollector stderr = null;
    StreamCollector stdout = null;

    FileOutputStream fileOutput = null;
    StreamAppender outputLogger = null;

    String errString = null;
    String outString = null;

    try {
        if (outputLog != null) {
            errString = "stderr output redirected to file " + outputLog;
            outString = "stdout output redirected to file " + outputLog;
            fileOutput = new FileOutputStream(outputLog);
            outputLogger = new StreamAppender(fileOutput);
            outputLogger.writeInput(process.getErrorStream(), process.getInputStream());
        } else {
            stderr = new StreamCollector(process.getErrorStream());
            stdout = new StreamCollector(process.getInputStream());
            stderr.start();
            stdout.start();
        }

        inputThread.start();

        final int exitCode = process.waitFor();
        processFinished.set(true);

        inputThread.join();

        if (outputLogger != null) {
            outputLogger.finish();
        }

        if (stderr != null) {
            stderr.join();
            errString = stderr.toString();
        }

        if (stdout != null) {
            stdout.join();
            outString = stdout.toString();
        }

        return new Result(cmd, outString, errString, exitCode);
    } finally {
        closeQuietly(fileOutput);
    }
}

From source file:com.twosigma.beaker.kdb.KdbProcess.java

private void runImpl() throws Exception {
    // Guess at QLIC if it's not set.
    String qlic = System.getenv(QLIC);
    if (qlic == null) {
        qlic = qhome + File.separator + "k4.lic";
    }//from w  ww .j  a  v  a  2  s .c o m

    // Start kdb.
    Process kdbProcess = Runtime.getRuntime().exec(new String[] { qbin, "-p", Integer.toString(kdbPort) },
            new String[] { QHOME + "=" + qhome, QLIC + "=" + qlic,
                    BEAKER_CORE_PASSWORD + "=" + System.getenv(BEAKER_CORE_PASSWORD),
                    BEAKER_CORE_PORT + "=" + System.getenv(BEAKER_CORE_PORT), SESSION_ID + "=" + sessionId });

    errorGobbler = new ErrorGobbler(kdbProcess.getErrorStream());
    errorGobbler.start();

    outputHandler = new KdbOutputHandler(kdbProcess.getInputStream());
    outputHandler.start();

    // Wait until kdb exits or we're interrupted.
    while (true) {
        try {
            // Wait for kdb to exit.
            kdbProcess.waitFor();
            break;
        } catch (InterruptedException e) {
            // Interrupted - destroy the process.
            kdbProcess.destroy();
        }
    }
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public void addElement(String key, String type) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("Plist file '" + plist + "' not found.");
    }//from   w  w w .  jav a 2 s.co  m
    try {
        String command = "/usr/libexec/PlistBuddy -x -c \"Add :" + key + " " + type + "  " + "\" \""
                + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.unibremen.informatik.tdki.combo.rewriting.FilterRewriterDB2.java

private void printOutput(Process p) throws IOException {
    atomicPrintOutput(new BufferedReader(new InputStreamReader(p.getInputStream())), false);
    atomicPrintOutput(new BufferedReader(new InputStreamReader(p.getErrorStream())), true);
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public void updateStringValue(String key, String value) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("Plist file '" + plist + "' not found.");
    }//from   w  ww .  j  a  v a 2s.c om

    try {
        String command = "/usr/libexec/PlistBuddy -x -c \"Set :" + key + " " + value + "\" \""
                + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Set command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public void addStringValue(String key, String value) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("Plist file '" + plist + "' not found.");
    }//from   www  .  ja  v a 2 s .com

    try {
        String command = "/usr/libexec/PlistBuddy -x -c \"Add :" + key + " string " + value + "\" \""
                + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public void addStringValueToDict(String key, String value, String dictKey) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("Plist file '" + plist + "' not found.");
    }//from ww  w .  j a  v  a 2s. co  m

    try {
        String command = "/usr/libexec/PlistBuddy -x -c \"Add :" + dictKey + ":" + key + " string " + value
                + "\" \"" + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public void addDictToArray(String dict, String array) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("Plist file '" + plist + "' not found.");
    }//from w w w .j  av  a  2  s  . co  m

    try {
        String command = "/usr/libexec/PlistBuddy -x -c \"Add :" + array + ":" + dict + " dict " + "\" \""
                + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.stallion.utils.ProcessHelper.java

public CommandResult run() {

    String cmdString = String.join(" ", args);
    System.out.printf("----- Execute command: %s ----\n", cmdString);
    ProcessBuilder pb = new ProcessBuilder(args);
    if (!empty(directory)) {
        pb.directory(new File(directory));
    }/*from  ww w .ja  v  a 2 s  .  c  om*/
    Map<String, String> env = pb.environment();
    CommandResult commandResult = new CommandResult();
    Process p = null;
    try {
        if (showDotsWhileWaiting == null) {
            showDotsWhileWaiting = !inheritIO;
        }

        if (inheritIO) {
            p = pb.inheritIO().start();
        } else {
            p = pb.start();
        }

        BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));

        if (!empty(input)) {
            Log.info("Writing input to pipe {0}", input);
            IOUtils.write(input, p.getOutputStream(), UTF8);
            p.getOutputStream().flush();
        }

        while (p.isAlive()) {
            p.waitFor(1000, TimeUnit.MILLISECONDS);
            if (showDotsWhileWaiting == true) {
                System.out.printf(".");
            }
        }

        commandResult.setErr(IOUtils.toString(err));
        commandResult.setOut(IOUtils.toString(out));
        commandResult.setCode(p.exitValue());

        if (commandResult.succeeded()) {
            info("\n---- Command execution completed ----\n");
        } else {
            Log.warn("Command failed with error code: " + commandResult.getCode());
        }

    } catch (IOException e) {
        Log.exception(e, "Error running command: " + cmdString);
        commandResult.setCode(999);
        commandResult.setEx(e);
    } catch (InterruptedException e) {
        Log.exception(e, "Error running command: " + cmdString);
        commandResult.setCode(998);
        commandResult.setEx(e);
    }
    Log.fine(
            "\n\n----Start shell command result----:\nCommand:  {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n",
            cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr());
    return commandResult;
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public void createPlist() throws IOException {

    try {//w w w . j a v  a  2 s .  c o  m
        String command = "/usr/libexec/PlistBuddy -x -c \"Save \" \"" + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };

        Process p = Runtime.getRuntime().exec(args);

        p.waitFor();

        int exitValue = p.exitValue();

        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}