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:cz.muni.fi.xklinec.zipstream.Mallory.java

/**
 * Simple helper for executing a command.
 * /*  w ww .  ja va 2  s . c  o m*/
 * @param command
 * @param outOpt
 * @param workingDir
 * @return
 * @throws IOException
 * @throws InterruptedException 
 */
public CmdExecutionResult execute(final String command, OutputOpt outOpt, File workingDir, OutputStream os)
        throws IOException, InterruptedException {
    CmdExecutionResult res = new CmdExecutionResult();

    // Execute motelist command
    Process p = workingDir == null ? Runtime.getRuntime().exec(command)
            : Runtime.getRuntime().exec(command, null, workingDir);

    // If interested only in stdErr, single thread is OK, otherwise 2 stream
    // reading threads are needed.
    if (outOpt == OutputOpt.EXECUTE_STDERR_ONLY || outOpt == OutputOpt.EXECUTE_STDOUT_ONLY) {
        StringBuilder sb = new StringBuilder();
        BufferedReader bri = new BufferedReader(new InputStreamReader(
                outOpt == OutputOpt.EXECUTE_STDERR_ONLY ? p.getErrorStream() : p.getInputStream()));

        String line;
        while ((line = bri.readLine()) != null) {
            sb.append(line).append("\n");
        }
        bri.close();

        if (outOpt == OutputOpt.EXECUTE_STDOUT_ONLY)
            res.stdOut = sb.toString();
        else if (outOpt == OutputOpt.EXECUTE_STDERR_ONLY)
            res.stdErr = sb.toString();

        // synchronous call, wait for command completion
        p.waitFor();
    } else if (outOpt == OutputOpt.EXECUTE_STD_COMBINE) {
        // Combine both streams together
        StreamMerger sm = new StreamMerger(p.getInputStream(), p.getErrorStream());
        if (os != null) {
            sm.setOutputStream(os);
        }

        sm.run();

        // synchronous call, wait for command completion
        p.waitFor();

        res.stdOut = sm.getOutput();
    } else {
        // Consume streams, older jvm's had a memory leak if streams were not read,
        // some other jvm+OS combinations may block unless streams are consumed.
        StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), true);
        StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), true);
        errorGobbler.start();
        outputGobbler.start();

        // synchronous call, wait for command completion
        p.waitFor();

        res.stdErr = errorGobbler.getOutput();
        res.stdOut = outputGobbler.getOutput();
    }

    res.exitValue = p.exitValue();
    return res;
}

From source file:la2launcher.MainFrame.java

private void extractArchive(String file) {
    try {/*from  www .  j av  a2 s .  com*/
        String parentPath = new File(file).getParent();
        Process proc = Runtime.getRuntime().exec("extract.cmd \"" + file + "\" \"" + parentPath + "\"");
        StringWriter writer = new StringWriter();
        IOUtils.copy(proc.getInputStream(), writer, "UTF-8");
        IOUtils.copy(proc.getErrorStream(), writer, "UTF-8");
        String theString = writer.toString();
        System.out.println(theString);
        proc.waitFor();
    } catch (IOException ex) {
        printMsg("? ?? ?  " + file);
    } catch (InterruptedException ex) {
        printMsg("? ?? ?  " + file);
    }
}

From source file:com.thoughtworks.cruise.util.command.CommandLine.java

public boolean runScript(Script script, long timeout, StreamConsumer buildOutputConsumer,
        EnvironmentVariableContext environmentVariableContext) throws CheckedCommandLineException {
    LOG.info("Running command: " + toStringForDisplay());

    StreamConsumer consumerForError = new SafeStreamConsumer(
            new CompositeConsumer(StreamLogger.getWarnLogger(LOG), buildOutputConsumer), getArguments());
    StreamConsumer consumerForOut = new SafeStreamConsumer(
            new CompositeConsumer(StreamLogger.getInfoLogger(LOG), buildOutputConsumer), getArguments());
    //TODO: The build output buffer doesn't take into account Cruise running in multi-threaded mode.

    Process p;
    int exitCode = -1;

    try {/*w  w  w.  ja  v  a2  s.c  o m*/
        ConsoleOutputStreamConsumer outputStreamConsumer = new ConsoleOutputStreamConsumer(buildOutputConsumer,
                buildOutputConsumer);
        p = startProcess(environmentVariableContext, outputStreamConsumer);
    } catch (CommandLineException e) {
        String msg = "Error happend while attempting to execute '" + toStringForDisplay()
                + "'. \nPlease make sure [" + getExecutable() + "] can be executed on this agent.\n";
        consumerForError.consumeLine(msg);
        throw new CheckedCommandLineException(msg, e);
    } catch (IOException e) {
        String msg = "Encountered an IO exception while attempting to execute '" + toStringForDisplay()
                + "'. Cruise cannot continue.\n";
        consumerForError.consumeLine(msg);
        throw new CheckedCommandLineException(msg, e);
    }

    StreamPumper errorPumper = new StreamPumper(p.getErrorStream(), consumerForError, "", encoding);
    StreamPumper outPumper = new StreamPumper(p.getInputStream(), consumerForOut, "", encoding);

    Thread stderr = new Thread(errorPumper);
    stderr.start();
    Thread stdout = new Thread(outPumper);
    stdout.start();
    AsyncKiller killer = new AsyncKiller(p, timeout);
    if (timeout > 0) {
        killer.start();
    }

    try {
        exitCode = p.waitFor();
        killer.interrupt();
        stderr.join();
        stdout.join();
    } catch (InterruptedException e) {
        LOG.info("Was interrupted while waiting for script to finish."
                + " Cruise will continue, assuming that it completed");
    } finally {
        IO.close(p);
    }

    script.setExitCode(exitCode);

    return !killer.processKilled();

}

From source file:mitm.common.util.ProcessRunner.java

public int run(List<String> cmd) throws IOException {
    if (cmd == null || cmd.size() == 0) {
        throw new IllegalArgumentException("cmd is invalid.");
    }/*  w  ww. jav  a  2 s  .  co  m*/

    /*
     * Used to show which command was executed
     */
    String cmdLine = logArguments ? StringUtils.join(cmd, ",") : cmd.get(0);

    logger.debug("Starting application. cmdLine: " + cmdLine);

    /*
     * Watchdog that will be used to destroy the process on a timeout
     */
    TaskScheduler watchdog = new TaskScheduler(ProcessRunner.class.getCanonicalName() + "#" + cmdLine);

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);

        Process process = processBuilder.start();

        if (timeout > 0) {
            /*
             * Task that will destroy the process on a timeout
             */
            Task processWatchdogTask = new DestroyProcessTimeoutTask(process, watchdog.getName());

            watchdog.addTask(processWatchdogTask, timeout);

            /*
             * Task that will interrupt the current thread on a timeout
             */
            Task threadInterruptTimeoutTask = new ThreadInterruptTimeoutTask(Thread.currentThread(),
                    watchdog.getName());

            watchdog.addTask(threadInterruptTimeoutTask, timeout);
        }

        Thread inputThread = null;
        Thread outputThread = null;
        Thread errorThread = null;

        if (input != null) {
            inputThread = new StreamCopier(input, process.getOutputStream(), "input", false, true);
            inputThread.start();
        }

        if (output != null) {
            outputThread = new StreamCopier(process.getInputStream(), output, "output", true, false);
            outputThread.start();
        }

        if (error != null) {
            errorThread = new StreamCopier(process.getErrorStream(), error, "error", true, false);
            errorThread.start();
        }

        try {
            exitCode = process.waitFor();

            /*
             * We need to wait for the threads to finish because otherwise there is
             * a chance we will start using the output before all the output has been
             * written/read.
             */
            if (inputThread != null) {
                inputThread.join();
            }

            if (outputThread != null) {
                outputThread.join();
            }

            if (errorThread != null) {
                errorThread.join();
            }

            /*
             * We MUST close the standard streams otherwise some "FIFO pipes" won't be closed until
             * the garbage collector is run. If there are too many open "FIFO pipes", the following
             * exception might occur:
             * 
             * java.io.IOException: error=24, Too many open files
             * 
             * Closing the standard streams makes sure that the pipes are closed.
             * 
             * Note: The Javadoc for Process does not mention that you should close the standard streams
             * even if not used. Perhaps they rely on the GC?
             * 
             * Note2: The number of FIFI pipes can be counted with:
             * 
             * lsof | grep java | grep pipe | wc -l
             */
            IOUtils.closeQuietly(process.getInputStream());
            IOUtils.closeQuietly(process.getOutputStream());
            IOUtils.closeQuietly(process.getErrorStream());
        } catch (InterruptedException e) {
            throw new IOException("Error running [" + cmdLine + "]", e);
        }

        if (exitCode != successExitCode) {
            throw new ProcessException("Error running [" + cmdLine + "]. exit value: " + exitCode, exitCode);
        }
    } finally {
        logger.debug("Application finished. cmdLine: " + cmdLine);

        /*
         * Need to cancel any pending watchdog tasks
         */
        watchdog.cancel();
    }

    return exitCode;
}

From source file:com.actuate.development.tool.task.InstallBRDPro.java

private void interruptAntTaskErrorMessage(final Process process, final StringBuffer buffer) {
    Thread errThread = new Thread("Monitor Ant Task") {

        public void run() {
            try {
                BufferedReader input = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String line;//from  w  w w . ja  v  a  2  s  .  c  om
                while ((line = input.readLine()) != null) {
                    if (buffer != null)
                        buffer.append(line).append("\r\n");
                }
                input.close();
            } catch (Exception e) {
            }
        }
    };
    errThread.setDaemon(true);
    errThread.start();
}

From source file:com.samsung.sjs.SJSTest.java

public void assertSameProcessOutput(Process a, Process b) throws IOException, InterruptedException {
    a.waitFor();//from www .ja  va 2  s  .c om
    b.waitFor();
    System.out.println("result of process a: " + a.exitValue());
    System.out.println("result of process b: " + b.exitValue());
    //assertTrue(a.exitValue() == b.exitValue());
    // Requiring the same exit value and output is usually too strong when we're testing error/exception
    // code.  Both node and our compiled code will return 0 when everything is okay, and should
    // then produce the same output.  But when there's an assertion failure or exception,
    // the C standard library semantics and node's semantics differ, in both return code and
    // process output.  So we enforce a more relaxed check here:
    // - If both processes return 0, assert both output streams match for the two processses
    // - Otherwise, assert both processes are non-zero exits (both failed), and ignore the stream contents.
    // This leaves open the possibility that a test will pass when the processes fail for
    // different reasons.
    int exita = a.exitValue();
    int exitb = b.exitValue();
    StringWriter a_stdout = new StringWriter(), b_stdout = new StringWriter(), a_stderr = new StringWriter(),
            b_stderr = new StringWriter();
    IOUtils.copy(a.getInputStream(), a_stdout, Charset.defaultCharset());
    IOUtils.copy(b.getInputStream(), b_stdout, Charset.defaultCharset());
    IOUtils.copy(a.getErrorStream(), a_stderr, Charset.defaultCharset());
    IOUtils.copy(b.getErrorStream(), b_stderr, Charset.defaultCharset());
    // Trim trailing newlines from output
    String a_stdout_str = a_stdout.toString().trim();
    String b_stdout_str = b_stdout.toString().trim();
    String a_stderr_str = a_stderr.toString().trim();
    String b_stderr_str = b_stderr.toString().trim();
    // HACK get rid of GC warning message from SJS stderr
    b_stderr_str = b_stderr_str.replaceAll(
            "GC Warning: Repeated allocation of very large block \\(appr\\. size .*\\):\\n\\tMay lead to memory leak and poor performance.",
            "");
    boolean same_stdout = a_stdout_str.equals(b_stdout_str);
    boolean same_stderr = a_stderr_str.equals(b_stderr_str);
    if (0 == exita && 0 == exitb) {
        if (!same_stdout) {
            System.err.println("FAILURE: stdout mismatch");
            System.err.println("left stdout: [" + a_stdout_str + "]");
            System.err.println("right stdout: [" + b_stdout_str + "]");
        }
        assertTrue(same_stdout);
        if (!same_stderr) {
            System.err.println("FAILURE: stderr mismatch");
            System.err.println("left stderr: [" + a_stderr_str + "]");
            System.err.println("right stderr: [" + b_stderr_str + "]");
        }
        assertTrue(same_stderr);
    } else {
        if (exita == 0 || exitb == 0) {
            System.err.println("FAILURE: Process A returned " + exita + ", Process B returned " + exitb);
            System.err.println("left stdout: [" + a_stdout_str + "]");
            System.err.println("right stdout: [" + b_stdout_str + "]");
            System.err.println("left stderr: [" + a_stderr_str + "]");
            System.err.println("right stderr: [" + b_stderr_str + "]");
        }
        assertTrue(exita != 0 && exitb != 0);
    }
}

From source file:hu.sztaki.lpds.pgportal.portlets.asm.SymbolMap.java

@SuppressWarnings("empty-statement")
private ArrayList<String> getOutputfiles(String resultzipPath, String userId, String outputfileMask) {
    String temp_output = resultzipPath;
    String temp_filename = "wf_autodock_" + userId + "_out.zip";
    String temp_user_dir = "wf_autodock_" + userId + "_dir";
    String output_filename = outputfileMask;
    //"best.pdbqt";
    String string_error = "";
    ArrayList<String> resultPaths = new ArrayList<String>(1);
    try {/*from   w  ww. ja  v  a2s  . c  o  m*/
        runSystemcmd("rm -rf  " + temp_dir + "/" + temp_user_dir);
        runSystemcmd("mkdir -p " + temp_dir + "/" + temp_user_dir);
        runSystemcmd("cp " + temp_output + " " + temp_dir + "/" + temp_filename);
        runSystemcmd("unzip -o " + temp_dir + "/" + temp_filename + " -d " + temp_dir + "/" + temp_user_dir);
        // MODIFIED TO SIMULATE MULTIPLE OUTPUT
        Process pr = Runtime.getRuntime()
                .exec(new String[] { "find", temp_dir + "/" + temp_user_dir, "-name", output_filename });

        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        BufferedReader error = new BufferedReader(new InputStreamReader(pr.getErrorStream()));

        String line = null;

        while ((line = input.readLine()) != null) {
            resultPaths.add(line);
        }

        string_error = error.readLine();
        throwError(Thread.currentThread().getStackTrace()[1].getMethodName() + " " + string_error, 10);

    } catch (Exception ex) {
        throwError(Thread.currentThread().getStackTrace()[1].getMethodName() + " # " + ex.getMessage(), 0);
        string_error = ex.getMessage();
        //throw new Exception("Grr");
    }
    return resultPaths;
}

From source file:configuration.Util.java

/**
 * From : http://www.jeffreythompson.org/blog/2012/05/29/easy-processing-illustrator-export-bonus-svg-export/
 * Small function to execute external code
 * @param commandToRun//from w  w  w .  j  a va 2  s.  c o  m
 * @param dir
 */
public static ArrayList<String> runUnixCommand(String commandToRun, String dir) {
    ArrayList<String> str = new ArrayList<String>();
    File workingDir = new File(""); // where to do it - should be full path
    String returnedValues; // value to return any results

    // run the command!
    try {
        System.out.println(commandToRun);
        String[] cmd = new String[10];
        for (int i = 0; i < 10; i++)
            cmd[i] = "";
        cmd[0] = commandToRun;

        Process p = Runtime.getRuntime().exec(commandToRun, null);
        int i = p.waitFor();
        if (i == 0) {
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((returnedValues = stdInput.readLine()) != null) {
                str.add(returnedValues);
                //println(returnedValues);
            }
        } else {
            BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((returnedValues = stdErr.readLine()) != null) {
                str.add(returnedValues);
                //--Error to stdout
                System.out.println(returnedValues);
            }
        }
    } catch (Exception e) {
        System.out.println("Error running command!");
        System.out.println(e);
    }
    return str;
}

From source file:configuration.Util.java

/**
 * From : http://www.jeffreythompson.org/blog/2012/05/29/easy-processing-illustrator-export-bonus-svg-export/
 * Small function to execute external code
 * @param commandToRun/*  w ww . ja v a2  s  .  c o m*/
 * @param dir
 */
public static ArrayList<String> runSilentUnixCommand(String commandToRun, String dir) {
    ArrayList<String> str = new ArrayList<String>();
    File workingDir = new File(""); // where to do it - should be full path
    String returnedValues; // value to return any results

    // run the command!
    try {
        String[] cmd = new String[10];
        for (int i = 0; i < 10; i++)
            cmd[i] = "";
        cmd[0] = commandToRun;

        Process p = Runtime.getRuntime().exec(commandToRun, null);
        int i = p.waitFor();
        if (i == 0) {
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((returnedValues = stdInput.readLine()) != null) {
                str.add(returnedValues);
                //Util.pl(returnedValues);
            }
        } else {
            BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((returnedValues = stdErr.readLine()) != null) {
                str.add(returnedValues);
                //--Error to stdout
                System.out.println(commandToRun);
                System.out.println(returnedValues);
            }
        }
    } catch (Exception e) {
        System.out.println(commandToRun);
        System.out.println("Error running command!");
        System.out.println(e);
    }
    return str;
}

From source file:hu.sztaki.lpds.pgportal.portlets.asm.SymbolMap.java

private String runSystemcmd(String[] cmd) {
    String string_error = "";
    try {/*from  w  w  w  . j a  va2  s  .co  m*/
        Process pr;
        if (cmd.length == 1) {
            String command = cmd[0];
            pr = Runtime.getRuntime().exec(command);
        } else {
            pr = Runtime.getRuntime().exec(cmd);
        }
        //pr=null;
        throwMessage("systemCmd:" + cmd[0], 10);
        BufferedReader error = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        pr.waitFor();
        string_error = error.readLine();
        throwMessage("systemCmd error:" + string_error, 5);
    } catch (Exception e) {
        throwError("CRITICAL " + Thread.currentThread().getStackTrace()[1].getMethodName() + " #" + cmd[0]
                + "  " + e.getMessage(), 0);
        string_error = e.getMessage();
    }
    return string_error;

}