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.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java

private static List<String> system(String... command) {
    try {//from   ww w  .  j  ava  2  s  .c  o  m
        final Process process = new ProcessBuilder(command).start();
        Preconditions.checkState(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command),
                IOUtils.toString(process.getErrorStream()));
        try (InputStream stream = process.getInputStream()) {
            return IOUtils.readLines(stream);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.qq.tars.tools.SystemUtils.java

public static Pair<Integer, Pair<String, String>> exec(String command) {
    log.info("start to exec shell, command={}", command);

    try {//from  ww w  . j a v  a 2s  .c  om
        Process process = Runtime.getRuntime().exec("/bin/sh");

        OutputStream os = process.getOutputStream();
        os.write(command.getBytes());
        os.close();

        final StringBuilder stdout = new StringBuilder(1024);
        final StringBuilder stderr = new StringBuilder(1024);
        final BufferedReader stdoutReader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), "GBK"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(process.getErrorStream(), "GBK"));

        new Thread(() -> {
            String line;
            try {
                while (null != (line = stdoutReader.readLine())) {
                    stdout.append(line).append("\n");
                }
            } catch (IOException e) {
                log.error("read stdout error", e);
            }
        }).start();

        new Thread(() -> {
            String line;
            try {
                while (null != (line = stderrReader.readLine())) {
                    stderr.append(line).append("\n");
                }
            } catch (IOException e) {
                log.error("read stderr error", e);
            }
        }).start();

        int ret = process.waitFor();

        stdoutReader.close();
        stderrReader.close();

        Pair<String, String> output = Pair.of(stdout.toString(), stderr.toString());
        return Pair.of(ret, output);
    } catch (Exception e) {
        return Pair.of(-1, Pair.of("", ExceptionUtils.getStackTrace(e)));
    }
}

From source file:ExifUtils.ExifReadWrite.java

private static ArrayList<String> exifTool_builder(String[] parameters, File directory) {
    //        final String command[] = "exiftool " + parameters;
    ArrayList<String> lines = new ArrayList<>();
    try {//from   w w  w  .j  a v a  2s.  com
        ProcessBuilder processBuilder = new ProcessBuilder(parameters).directory(directory);
        Process p = processBuilder.start();
        final BufferedReader stdinReader = new BufferedReader(
                new InputStreamReader(p.getInputStream(), "ISO-8859-1"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(p.getErrorStream(), "ISO-8859-1"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stdinReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stderrReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        int returnVal = p.waitFor();
    } catch (Exception e) {
        errorOut("xmp", e);
    }
    return lines;
}

From source file:TestFuseDFS.java

/**
 * Run a fuse-dfs process to mount the given DFS
 *//*  w w w.j a  v  a  2 s  . c  o  m*/
private static Process establishMount(URI uri) throws IOException {
    Runtime r = Runtime.getRuntime();
    String cp = System.getProperty("java.class.path");

    String buildTestDir = System.getProperty("build.test");
    String fuseCmd = buildTestDir + "/../fuse_dfs";
    String libHdfs = buildTestDir + "/../../../c++/lib";

    String arch = System.getProperty("os.arch");
    String jvm = System.getProperty("java.home") + "/lib/" + arch + "/server";
    String lp = System.getProperty("LD_LIBRARY_PATH") + ":" + libHdfs + ":" + jvm;
    LOG.debug("LD_LIBRARY_PATH=" + lp);

    String nameNode = "dfs://" + uri.getHost() + ":" + String.valueOf(uri.getPort());

    // NB: We're mounting via an unprivileged user, therefore
    // user_allow_other needs to be set in /etc/fuse.conf, which also
    // needs to be world readable.
    String mountCmd[] = { fuseCmd, nameNode, mountPoint,
            // "-odebug",              // Don't daemonize
            "-obig_writes", // Allow >4kb writes
            "-oentry_timeout=0.1", // Don't cache dents long
            "-oattribute_timeout=0.1", // Don't cache attributes long
            "-ononempty", // Don't complain about junk in mount point
            "-f", // Don't background the process
            "-ordbuffer=32768", // Read buffer size in kb
            "rw" };

    String[] env = { "CLASSPATH=" + cp, "LD_LIBRARY_PATH=" + lp, "PATH=/usr/bin:/bin" };

    execWaitRet("fusermount -u " + mountPoint);
    execAssertSucceeds("rm -rf " + mountPoint);
    execAssertSucceeds("mkdir -p " + mountPoint);

    // Mount the mini cluster
    String cmdStr = "";
    for (String c : mountCmd) {
        cmdStr += (" " + c);
    }
    LOG.info("now mounting with:" + cmdStr);
    Process fuseProcess = r.exec(mountCmd, env);
    RedirectToStdoutThread stdoutThread = new RedirectToStdoutThread(fuseProcess.getInputStream());
    RedirectToStdoutThread stderrThread = new RedirectToStdoutThread(fuseProcess.getErrorStream());
    stdoutThread.start();
    stderrThread.start();
    // Wait for fusermount to start up, so that we know we're operating on the
    // FUSE FS when we run the tests.
    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
    }
    return fuseProcess;
}

From source file:ExifUtils.ExifReadWrite.java

public static ArrayList<String> exifTool(String[] parameters, File directory) {
    //        final String command[] = "exiftool " + parameters;
    ArrayList<String> lines = new ArrayList<>();
    try {//from w  ww  . j  a v  a 2  s. c om
        Runtime runtime = Runtime.getRuntime();
        Process p = runtime.exec(parameters, null, directory);
        final BufferedReader stdinReader = new BufferedReader(
                new InputStreamReader(p.getInputStream(), "ISO-8859-1"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(p.getErrorStream(), "ISO-8859-1"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stdinReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stderrReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        int returnVal = p.waitFor();
    } catch (Exception e) {
        errorOut("xmp", e);
    }
    return lines;
}

From source file:net.mybox.mybox.Common.java

/**
 * Run a system command on the local machine
 * @param command/*from  w w w .  j  a v  a  2 s  .c  o m*/
 * @return
 */
public static SysResult syscommand(String[] command) {
    Runtime r = Runtime.getRuntime();

    SysResult result = new SysResult();

    System.out.println("syscommand array: " + StringUtils.join(command, " "));

    try {

        Process p = r.exec(command);
        // should use a thread so it can be killed if it has not finished and another one needs to be started
        InputStream in = p.getInputStream();

        InputStream stderr = p.getErrorStream();
        InputStreamReader inreadErr = new InputStreamReader(stderr);
        BufferedReader brErr = new BufferedReader(inreadErr);

        BufferedInputStream buf = new BufferedInputStream(in);
        InputStreamReader inread = new InputStreamReader(buf);
        BufferedReader bufferedreader = new BufferedReader(inread);

        // Read the ls output
        String line;
        while ((line = bufferedreader.readLine()) != null) {
            result.output += line + "\n";
            System.err.print("  output> " + result.output);
            // should check for last line "Contacting server..." after 3 seconds, to restart unison command X times
        }

        result.worked = true;

        // Check for failure
        try {
            if (p.waitFor() != 0) {
                System.err.println("exit value = " + p.exitValue());
                System.err.println("command> " + command);
                System.err.println("output> " + result.output);
                System.err.print("error> ");

                while ((line = brErr.readLine()) != null)
                    System.err.println(line);

                result.worked = false;
            }
            result.returnCode = p.waitFor();
        } catch (InterruptedException e) {
            System.err.println(e);
            result.worked = false;
        } finally {
            // Close the InputStream
            bufferedreader.close();
            inread.close();
            buf.close();
            in.close();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        result.worked = false;
    }

    result.output = result.output.trim();

    return result;
}

From source file:net.floodlightcontroller.queuepusher.QueuePusherSwitchMapper.java

/**
 * Runs the given command/*w ww . ja  v a 2 s .  c  o  m*/
 * 
 * @param cmd Command to execute
 * @return 0: (int)exit code 1: (string)stdout 2: (string)stderr
 */

private static Object[] eval(String cmd) {

    Object[] rsp = new Object[3];
    Runtime rt = Runtime.getRuntime();
    Process proc = null;

    try {
        proc = rt.exec(cmd);
        proc.waitFor();
        rsp[0] = proc.exitValue();
    } catch (InterruptedException e) {
        rsp[0] = 1;
    } catch (IOException e) {
        rsp[0] = 1;
    } finally {
        if (proc == null) {
            rsp[0] = 1;
        } else {

            try {

                BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

                String temp;
                StringBuilder sb = new StringBuilder();
                while ((temp = stdout.readLine()) != null) {
                    sb.append(temp);
                }

                rsp[1] = sb.toString();
                sb = new StringBuilder();
                while ((temp = stderr.readLine()) != null) {
                    sb.append(temp);
                }

                rsp[2] = sb.toString();

            } catch (IOException e) {
                rsp[0] = 1;
            }

        }
    }

    return rsp;

}

From source file:net.sf.sahi.util.Utils.java

public static String executeCommand(String[] command) throws Exception {
    StringBuffer sb = new StringBuffer();
    Process p = Runtime.getRuntime().exec(command);
    InputStream stdInput = p.getInputStream();
    InputStream stdError = p.getErrorStream();
    StringBuffer inBuffer = new StringBuffer();
    StringBuffer errBuffer = new StringBuffer();
    Thread inThread = new Thread(new StreamReader(stdInput, inBuffer));
    inThread.start();/*from www.j a  v  a2  s.  co  m*/
    Thread errThread = new Thread(new StreamReader(stdError, errBuffer));
    errThread.start();
    p.waitFor();
    inThread.join();
    errThread.join();
    sb.append(inBuffer);
    sb.append(errBuffer);
    return sb.toString();
}

From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProvider.java

private static File detectHadoopConfigurationDirectory(File command, File temporary, Map<String, String> envp)
        throws IOException {
    assert command != null;
    assert temporary != null;
    assert envp != null;

    prepareClasspath(temporary, ConfigurationDetecter.class);
    File resultOutput = new File(temporary, PATH_SUBPROC_OUTPUT);

    List<String> arguments = new ArrayList<>();
    arguments.add(command.getAbsolutePath());
    arguments.add(ConfigurationDetecter.class.getName());
    arguments.add(resultOutput.getAbsolutePath());

    ProcessBuilder processBuilder = new ProcessBuilder(arguments);
    processBuilder.environment().clear();
    processBuilder.environment().putAll(envp);
    processBuilder.environment().put(ENV_HADOOP_CLASSPATH, temporary.getPath());

    Process process = processBuilder.start();
    try {//w  ww  .  jav a  2s  .c  o  m
        Thread redirectOut = redirect(process.getInputStream(), System.out);
        Thread redirectErr = redirect(process.getErrorStream(), System.err);
        try {
            int exit = process.waitFor();
            redirectOut.join();
            redirectErr.join();
            if (exit != 0) {
                throw new IOException(
                        MessageFormat.format("Failed to execute Hadoop command (exitcode={1}): {0}", arguments,
                                String.valueOf(exit)));
            }
        } catch (InterruptedException e) {
            throw (IOException) new InterruptedIOException(
                    MessageFormat.format("Failed to execute Hadoop command (interrupted): {0}", arguments))
                            .initCause(e);
        }
    } finally {
        process.destroy();
    }
    if (resultOutput.isFile() == false) {
        throw new IOException(
                MessageFormat.format("Failed to restore Hadoop configuration path: {0}", resultOutput));
    }
    File path = ConfigurationDetecter.read(resultOutput);
    return path;
}

From source file:de.uni.bremen.monty.moco.Main.java

private static File buildExecutable(String outputFileName, String inputFileName, boolean compileOnly,
        String llvmCode) throws IOException, InterruptedException {
    File outputFile = null;//from w w  w.ja  v  a 2s.c o m
    if (outputFileName != null) {
        outputFile = new File(outputFileName);
    } else if (inputFileName != null) {
        outputFile = new File(FilenameUtils.removeExtension(inputFileName));
    } else if (compileOnly) {
        outputFile = File.createTempFile("output", null, null);
        outputFile.deleteOnExit();
    } else {
        outputFile = new File("output");
    }

    ProcessBuilder llcProcessBuilder = new ProcessBuilder("llc", "-O=2");
    Process llcProcess = llcProcessBuilder.start();
    PrintStream llcInput = new PrintStream(llcProcess.getOutputStream());
    llcInput.print(llvmCode);
    llcInput.close();

    ProcessBuilder ccProcessBuilder = new ProcessBuilder("cc", "-x", "assembler", "-o",
            outputFile.getAbsolutePath(), "-");
    Process ccProcess = ccProcessBuilder.start();
    IOUtils.copy(llcProcess.getInputStream(), ccProcess.getOutputStream());
    ccProcess.getOutputStream().close();

    System.err.print(IOUtils.toString(llcProcess.getErrorStream()));
    System.err.print(IOUtils.toString(ccProcess.getErrorStream()));
    return outputFile;
}