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.flipkart.flux.examples.WorkflowExecutionDemo.java

/**
 * Helper method to execute a shell command
 * @param command shell command to run/*  w  ww . j ava 2  s .  c o  m*/
 * @return shell command's output
 */
private static String executeCommand(String command) throws IOException, InterruptedException {

    StringBuilder output = new StringBuilder();

    Process p;

    p = Runtime.getRuntime().exec(command);
    p.waitFor();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    //prints the output of the process
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line).append("\n");
    }

    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    //prints the error stream of the process
    String errorLine = "";
    while ((errorLine = stdError.readLine()) != null) {
        System.out.println(errorLine);
    }

    return output.toString();

}

From source file:com.unresyst.DealRecommender.java

private static String runCommand(String... commands) throws IOException, InterruptedException {
    // generate a script file containg the command to run
    final File scriptFile = new File("/tmp/runcommand.sh");
    PrintWriter w = new PrintWriter(scriptFile);
    w.println("#!/bin/sh");
    for (String command : commands) {
        w.println(command);//from  w  ww.j ava2 s. c o  m
    }
    w.close();

    // make the script executable
    //System.out.println("absolute path: " + scriptFile.getAbsolutePath());
    Process p = Runtime.getRuntime().exec("chmod +x " + scriptFile.getAbsolutePath());
    p.waitFor();

    // execute the script
    p = Runtime.getRuntime().exec(scriptFile.getAbsolutePath());
    p.waitFor();
    BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    String toReturn = "";
    String line = "";
    while ((line = stdin.readLine()) != null) {
        toReturn += line + "\n";
    }
    while ((line = stderr.readLine()) != null) {
        toReturn += "err: " + line + "\n";
    }

    scriptFile.delete();
    return toReturn;
}

From source file:minij.assembler.Assembler.java

public static void assemble(Configuration config, String assembly) throws AssemblerException {

    try {/*from ww  w  .  j  a va 2 s  . c  o m*/
        new File(FilenameUtils.getPath(config.outputFile)).mkdirs();

        // -xc specifies the input language as C and is required for GCC to read from stdin
        ProcessBuilder processBuilder = new ProcessBuilder("gcc", "-o", config.outputFile, "-m32", "-xc",
                MiniJCompiler.RUNTIME_DIRECTORY.toString() + File.separator + "runtime_32.c", "-m32",
                "-xassembler", "-");
        Process gccCall = processBuilder.start();
        // Write C code to stdin of C Compiler
        OutputStream stdin = gccCall.getOutputStream();
        stdin.write(assembly.getBytes());
        stdin.close();

        gccCall.waitFor();

        // Print error messages of GCC
        if (gccCall.exitValue() != 0) {

            StringBuilder errOutput = new StringBuilder();
            InputStream stderr = gccCall.getErrorStream();
            String line;
            BufferedReader bufferedStderr = new BufferedReader(new InputStreamReader(stderr));
            while ((line = bufferedStderr.readLine()) != null) {
                errOutput.append(line + System.lineSeparator());
            }
            bufferedStderr.close();
            stderr.close();

            throw new AssemblerException(
                    "Failed to compile assembly:" + System.lineSeparator() + errOutput.toString());
        }

        Logger.logVerbosely("Successfully compiled assembly");
    } catch (IOException e) {
        throw new AssemblerException("Failed to transfer assembly to gcc", e);
    } catch (InterruptedException e) {
        throw new AssemblerException("Failed to invoke gcc", e);
    }

}

From source file:org.opencastproject.util.IoSupport.java

/**
 * Closes the processes input, output and error streams.
 *
 * @param process/*from   w  w  w. j av a2s  . c  om*/
 *         the process
 * @return <code>true</code> if the streams were closed
 */
public static boolean closeQuietly(final Process process) {
    if (process != null) {
        try {
            if (process.getErrorStream() != null)
                process.getErrorStream().close();
            if (process.getInputStream() != null)
                process.getInputStream().close();
            if (process.getOutputStream() != null)
                process.getOutputStream().close();
            return true;
        } catch (Throwable t) {
            logger.trace("Error closing process streams: " + t.getMessage());
        }
    }
    return false;
}

From source file:brooklyn.util.io.FileUtil.java

private static int exec(List<String> cmds, OutputStream out, OutputStream err) {
    StreamGobbler errgobbler = null;// w ww.j  a  v  a 2 s. c  o  m
    StreamGobbler outgobbler = null;

    ProcessBuilder pb = new ProcessBuilder(cmds);

    try {
        Process p = pb.start();

        if (out != null) {
            InputStream outstream = p.getInputStream();
            outgobbler = new StreamGobbler(outstream, out, (Logger) null);
            outgobbler.start();
        }
        if (err != null) {
            InputStream errstream = p.getErrorStream();
            errgobbler = new StreamGobbler(errstream, err, (Logger) null);
            errgobbler.start();
        }

        int result = p.waitFor();

        if (outgobbler != null)
            outgobbler.blockUntilFinished();
        if (errgobbler != null)
            errgobbler.blockUntilFinished();

        return result;
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    } finally {
        Streams.closeQuietly(outgobbler);
        Streams.closeQuietly(errgobbler);
    }
}

From source file:at.alladin.rmbt.android.impl.TracerouteAndroidImpl.java

public static String readFromProcess(Process proc) throws PingException {
    BufferedReader brErr = null;/*  www .  j  av  a  2 s  .c o m*/
    BufferedReader br = null;
    StringBuilder sbErr = new StringBuilder();
    StringBuilder sb = new StringBuilder();

    try {
        brErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String currInputLine = null;

        while ((currInputLine = brErr.readLine()) != null) {
            sbErr.append(currInputLine);
            sbErr.append("\n");
        }

        if (sbErr.length() > 0) {
            throw new PingException(sbErr.toString());
        }

        br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        currInputLine = null;

        while ((currInputLine = br.readLine()) != null) {
            sb.append(currInputLine);
            sb.append("\n");
        }
    } catch (PingException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
        }
        try {
            if (brErr != null) {
                brErr.close();
            }
        } catch (IOException e) {
        }
    }

    return sb.toString();
}

From source file:azkaban.utils.FileIOUtils.java

/**
 * Run a unix command that will symlink files, and recurse into directories.
 *//*from  ww  w .j  a  v  a 2s.  c o  m*/
public static void createDeepSymlink(File sourceDir, File destDir) throws IOException {
    if (!sourceDir.exists()) {
        throw new IOException("Source directory " + sourceDir.getPath() + " doesn't exist");
    } else if (!destDir.exists()) {
        throw new IOException("Destination directory " + destDir.getPath() + " doesn't exist");
    } else if (sourceDir.isFile() && destDir.isFile()) {
        throw new IOException("Source or Destination is not a directory.");
    }

    Set<String> paths = new HashSet<String>();
    createDirsFindFiles(sourceDir, sourceDir, destDir, paths);

    StringBuffer buffer = new StringBuffer();
    for (String path : paths) {
        File sourceLink = new File(sourceDir, path);
        path = "." + path;

        buffer.append("ln -s ").append(sourceLink.getAbsolutePath()).append("/*").append(" ").append(path)
                .append(";");
    }

    String command = buffer.toString();
    ProcessBuilder builder = new ProcessBuilder().command("sh", "-c", command);
    builder.directory(destDir);

    // XXX what about stopping threads ??
    Process process = builder.start();
    try {
        NullLogger errorLogger = new NullLogger(process.getErrorStream());
        NullLogger inputLogger = new NullLogger(process.getInputStream());
        errorLogger.start();
        inputLogger.start();

        try {
            if (process.waitFor() < 0) {
                // Assume that the error will be in standard out. Otherwise it'll be
                // in standard in.
                String errorMessage = errorLogger.getLastMessages();
                if (errorMessage.isEmpty()) {
                    errorMessage = inputLogger.getLastMessages();
                }

                throw new IOException(errorMessage);
            }

            // System.out.println(errorLogger.getLastMessages());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } finally {
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
    }
}

From source file:Main.java

public static boolean symlink(File inFile, File outFile) {
    int exitCode = -1;
    try {//w  w  w.  j  a v a2  s  .  com
        Process sh = Runtime.getRuntime().exec("sh");
        OutputStream out = sh.getOutputStream();
        String command = "/system/bin/ln -s " + inFile + " " + outFile + "\nexit\n";
        out.write(command.getBytes("ASCII"));

        final char buf[] = new char[40];
        InputStreamReader reader = new InputStreamReader(sh.getInputStream());
        while (reader.read(buf) != -1)
            throw new IOException("stdout: " + new String(buf));
        reader = new InputStreamReader(sh.getErrorStream());
        while (reader.read(buf) != -1)
            throw new IOException("stderr: " + new String(buf));

        exitCode = sh.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    }
    return exitCode == 0;
}

From source file:com.diffplug.gradle.CmdLine.java

/** Runs the given command in the given directory with the given echo setting. */
public static Result runCmd(File directory, String cmd, boolean echoCmd, boolean echoOutput)
        throws IOException {
    // set the cmds
    List<String> cmds = getPlatformCmds(cmd);
    ProcessBuilder builder = new ProcessBuilder(cmds);

    // set the working directory
    builder.directory(directory);//from w ww. ja v a 2 s  .com

    // execute the command
    Process process = builder.start();

    // wrap the process' input and output
    try (BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
            BufferedReader stdError = new BufferedReader(
                    new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));) {

        if (echoCmd) {
            System.out.println("cmd>" + cmd);
        }

        // dump the output
        ImmutableList.Builder<String> output = ImmutableList.builder();
        ImmutableList.Builder<String> error = ImmutableList.builder();

        String line = null;
        while ((line = stdInput.readLine()) != null) {
            output.add(line);
            if (echoOutput) {
                System.out.println(line);
            }
        }

        // dump the input
        while ((line = stdError.readLine()) != null) {
            error.add(line);
            if (echoOutput) {
                System.err.println(line);
            }
        }

        // check that the process exited correctly
        int exitValue = process.waitFor();
        if (exitValue != EXIT_VALUE_SUCCESS) {
            throw new RuntimeException("'" + cmd + "' exited with " + exitValue);
        }

        // returns the result of this successful execution
        return new Result(directory, cmd, output.build(), error.build());
    } catch (InterruptedException e) {
        // this isn't expected, but it's possible
        throw new RuntimeException(e);
    }
}

From source file:net.morimekta.idltool.IdlUtils.java

public static Git getCacheRepository(File cacheDir, String repository) throws IOException, GitAPIException {
    File repoCache = getCacheDirectory(cacheDir, repository);

    Runtime runtime = Runtime.getRuntime();
    if (!repoCache.exists()) {
        Process p = runtime
                .exec(new String[] { "git", "clone", repository, repoCache.getAbsoluteFile().toString() });
        try {//from   w  w w .  j a  va  2 s.  c o  m
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    } else {
        Process p = runtime.exec(new String[] { "git", "fetch", "origin", "-p" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "add", "-A" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "reset", "origin/master", "--hard" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
    return Git.open(repoCache);
}