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:Main.java

public static String executeCommand(String[] args) {
    String result = new String();
    ProcessBuilder processBuilder = new ProcessBuilder(args);
    Process process = null;
    InputStream errIs = null;//from   ww  w.j a va  2  s  .co m
    InputStream inIs = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int read = -1;
        process = processBuilder.start();
        errIs = process.getErrorStream();
        while ((read = errIs.read()) != -1) {
            baos.write(read);
        }
        baos.write('\n');
        inIs = process.getInputStream();
        while ((read = inIs.read()) != -1) {
            baos.write(read);
        }
        byte[] data = baos.toByteArray();
        result = new String(data);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
    } finally {
        try {
            if (errIs != null) {
                errIs.close();
            }
            if (inIs != null) {
                inIs.close();
            }
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        if (process != null) {
            process.destroy();
        }
    }
    return result;
}

From source file:com.yahoo.storm.yarn.TestIntegration.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static int execute(List<String> cmd) throws InterruptedException, IOException {
    LOG.info(Joiner.on(" ").join(cmd));
    ProcessBuilder pb = new ProcessBuilder(cmd);
    Map env = pb.environment();//from   w w w  .ja  v a2 s . c o  m
    env.putAll(System.getenv());
    env.put(Environment.PATH.name(),
            "bin:" + storm_home + File.separator + "bin:" + env.get(Environment.PATH.name()));
    String yarn_conf_dir = yarn_site_xml.getParent().toString();
    env.put("STORM_YARN_CONF_DIR", yarn_conf_dir);
    List<URL> logback_xmls = Utils.findResources("logback.xml");
    if (logback_xmls != null && logback_xmls.size() >= 1) {
        String logback_xml = logback_xmls.get(0).getFile();
        LOG.debug("logback_xml:" + yarn_conf_dir + File.separator + "logback.xml");
        FileUtils.copyFile(new File(logback_xml), new File(yarn_conf_dir + File.separator + "logback.xml"));
    }
    List<URL> log4j_properties = Utils.findResources("log4j.properties");
    if (log4j_properties != null && log4j_properties.size() >= 1) {
        String log4j_properties_file = log4j_properties.get(0).getFile();
        LOG.debug("log4j_properties_file:" + yarn_conf_dir + File.separator + "log4j.properties");
        FileUtils.copyFile(new File(log4j_properties_file),
                new File(yarn_conf_dir + File.separator + "log4j.properties"));
    }

    Process proc = pb.start();
    Util.redirectStreamAsync(proc.getInputStream(), System.out);
    Util.redirectStreamAsync(proc.getErrorStream(), System.err);
    int status = proc.waitFor();
    return status;
}

From source file:com.dtolabs.rundeck.core.utils.ScriptExecUtil.java

/**
 * Run a command with environment variables in a working dir, and copy the streams
 *
 * @param command      the command array to run
 * @param envMap       the environment variables to pass in
 * @param workingdir   optional working dir location (or null)
 * @param outputStream stream for stdout
 * @param errorStream  stream for stderr
 *
 * @return the exit code of the command/*from  w  w w  . jav a2  s .co m*/
 *
 * @throws IOException          if any IO exception occurs
 * @throws InterruptedException if interrupted while waiting for the command to finish
 */
public static int runLocalCommand(final String[] command, final Map<String, String> envMap,
        final File workingdir, final OutputStream outputStream, final OutputStream errorStream)
        throws IOException, InterruptedException {
    final String[] envarr = createEnvironmentArray(envMap);

    final Runtime runtime = Runtime.getRuntime();
    final Process exec = runtime.exec(command, envarr, workingdir);
    final Streams.StreamCopyThread errthread = Streams.copyStreamThread(exec.getErrorStream(), errorStream);
    final Streams.StreamCopyThread outthread = Streams.copyStreamThread(exec.getInputStream(), outputStream);
    errthread.start();
    outthread.start();
    exec.getOutputStream().close();
    final int result = exec.waitFor();
    errthread.join();
    outthread.join();
    if (null != outthread.getException()) {
        throw outthread.getException();
    }
    if (null != errthread.getException()) {
        throw errthread.getException();
    }
    return result;
}

From source file:com.mewmew.fairy.v1.book.Xargs.java

public static void exec(Map<String, String> env, String cmd[], boolean redirectError, Output<String> output)
        throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    if (env != null) {
        pb.environment().putAll(env);/*from w w  w . j  a v a2  s.  co  m*/
    }
    if (redirectError) {
        pb.redirectErrorStream(true);
    }
    final Process p = pb.start();
    if (!redirectError) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    LineIterator err = new LineIterator(new InputStreamReader(p.getErrorStream()));
                    while (err.hasNext()) {
                        err.next();
                    }
                } finally {
                }
            }
        }).start();
    }
    LineIterator out = new LineIterator(new InputStreamReader(p.getInputStream()));
    while (out.hasNext()) {
        output.output(out.nextLine());
    }
    int code = p.waitFor();
    if (code != 0) {
        throw new RuntimeException(String.format("return != 0, code = %d", code));
    }
}

From source file:acoli.controller.Controller.java

private static BufferedReader getError(Process p) {
    return new BufferedReader(new InputStreamReader(p.getErrorStream()));
}

From source file:org.spring.data.gemfire.AbstractGemFireIntegrationTest.java

protected static OutputStream startSpringGemFireServer(final long waitTimeout,
        final String... springConfigLocations) throws IOException {
    String serverId = DATE_FORMAT.format(Calendar.getInstance().getTime());

    File serverWorkingDirectory = FileSystemUtils.createFile("server-".concat(serverId));

    Assert.isTrue(FileSystemUtils.createDirectory(serverWorkingDirectory), String.format(
            "Failed to create working directory (%1$s) in which the Spring-based GemFire Server will run!",
            serverWorkingDirectory));//from  www . j  a  v  a 2  s  .c  o  m

    String[] serverCommandLine = buildServerCommandLine(springConfigLocations);

    System.out.printf("Starting Spring GemFire Server in (%1$s)...%n", serverWorkingDirectory);

    Process serverProcess = ProcessUtils.startProcess(serverCommandLine, serverWorkingDirectory);

    readProcessStream(serverId, "ERROR", serverProcess.getErrorStream());
    readProcessStream(serverId, "OUT", serverProcess.getInputStream());
    ProcessUtils.registerProcessShutdownHook(serverProcess, "Spring GemFire Server", serverWorkingDirectory);
    waitOnServer(waitTimeout, serverProcess, serverWorkingDirectory);

    return serverProcess.getOutputStream();
}

From source file:edu.tum.cs.ias.knowrob.utils.ResourceRetriever.java

/**
 * Tries to find the specified ros package by calling 'rospack find'.
 * //from ww w. j  ava 2  s. c o  m
 * @param pkgname
 *            Package to search for
 * @return Absolute path to the package or null if not found
 */
public static String findPackage(String pkgname) {

    try {
        String line;
        String cmd = "rospack find " + pkgname;
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader errReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((line = errReader.readLine()) != null) {
            System.err.println(line);
        }
        BufferedReader pathreader = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8"));
        if ((line = pathreader.readLine()) != null) {
            return line;
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return null;
}

From source file:ca.uqac.dim.net.verify.NetworkChecker.java

/**
 * Runs the NuSMV program as a spawned command-line process, and passes the
 * file to process through that process' standard input
 * @param file_contents A String containing the NuSMV model to process
 *///from ww w  . j  a v a  2 s  . com
private static RuntimeInfos runNuSMV(String file_contents) throws IOException, InterruptedException {
    StringBuilder sb = new StringBuilder();
    Runtime rt = Runtime.getRuntime();
    long time_start = 0, time_end = 0;
    // Start NuSMV, and feed the model through its standard input
    time_start = System.currentTimeMillis();
    Process p = rt.exec(NUSMV_EXEC);
    OutputStream o = p.getOutputStream();
    InputStream i = p.getInputStream();
    InputStream e = p.getErrorStream();
    Writer w = new PrintWriter(o);
    w.write(file_contents);
    w.close(); // Close stdin so NuSMV can start processing it
    // Wait for NuSMV to be done, then collect its standard output
    int exitVal = p.waitFor();
    if (exitVal != 0)
        throw new IOException("NuSMV's return value indicates an error in processing its input");
    BufferedReader br = new BufferedReader(new InputStreamReader(i));
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line).append("\n");
    }
    time_end = System.currentTimeMillis();
    i.close(); // Close stdout
    e.close(); // Close stderr
    return new RuntimeInfos(sb.toString(), time_end - time_start);
}

From source file:com.cloudera.sqoop.util.Executor.java

/**
 * Run a command via Runtime.exec(), with its stdout and stderr streams
 * directed to be handled by threads generated by AsyncSinks.
 * Block until the child process terminates. Allows the programmer to
 * specify an environment for the child program.
 *
 * @return the exit status of the ran program
 *//*from w w w.ja v a  2s  .  c o m*/
public static int exec(String[] args, String[] envp, AsyncSink outSink, AsyncSink errSink) throws IOException {

    // launch the process.
    Process p = Runtime.getRuntime().exec(args, envp);

    // dispatch its stdout and stderr to stream sinks if available.
    if (null != outSink) {
        outSink.processStream(p.getInputStream());
    }

    if (null != errSink) {
        errSink.processStream(p.getErrorStream());
    }

    // wait for the return value.
    while (true) {
        try {
            int ret = p.waitFor();
            return ret;
        } catch (InterruptedException ie) {
            continue;
        }
    }
}

From source file:com.baifendian.swordfish.execserver.common.FunctionUtil.java

/**
 *  udf jar/* w w w.j  a  v  a 2s .  co  m*/
 */
private static void uploadUdfJars(Set<String> resources, String tarDir, String srcDir, Logger logger)
        throws IOException, InterruptedException {
    HdfsClient hdfsClient = HdfsClient.getInstance();

    if (!hdfsClient.exists(tarDir)) {
        hdfsClient.mkdir(tarDir);
    }

    for (String res : resources) {
        // ?, ?
        if (!hdfsClient.exists(String.format("%s/%s", tarDir, res))) {
            String cmd = String.format("hdfs dfs -put %s/%s %s", srcDir, res, tarDir);

            logger.debug("cmd:{}", cmd);

            Process process = Runtime.getRuntime().exec(cmd);
            int ret = process.waitFor();
            if (ret != 0) {
                logger.error("run cmd:" + cmd + " error");

                String msg = IOUtils.toString(process.getErrorStream(), Charset.forName("UTF-8"));

                logger.error(msg);

                throw new ExecException(msg);
            }
        }
    }
}