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:de.rinderle.softvis3d.layout.dot.ExecuteCommand.java

public String executeCommandReadErrorStream(final String command) throws DotExecutorException {
    final StringBuilder output = new StringBuilder();

    final Process p;
    try {//from   w ww.  j  a  v  a2  s .c o m
        p = Runtime.getRuntime().exec(command);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line);
            output.append("\n");
        }

        reader.close();
    } catch (final IOException e) {
        throw new DotExecutorException(e.getMessage(), e);
    }

    return output.toString();
}

From source file:CustomSubmitter.java

/**
 * Submits the specified PBS job to the PBS queue using the {@code qsub}
 * program./* w w w  .j av  a 2s  .co  m*/
 * 
 * @param job the PBS job to be submitted
 * @throws IOException if an error occurred while invoking {@code qsub}
 */
public void submit(PBSJob job) throws IOException {
    Process process = new ProcessBuilder("qsub").start();

    RedirectStream.redirect(process.getInputStream(), System.out);
    RedirectStream.redirect(process.getErrorStream(), System.err);

    String script = toPBSScript(job);
    System.out.println(script);

    PrintStream ps = new PrintStream(process.getOutputStream());
    ps.print(script);
    ps.close();

    try {
        int exitStatus = process.waitFor();

        if (exitStatus != 0) {
            throw new IOException("qsub terminated with exit status " + exitStatus);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

From source file:it.polimi.modaclouds.qos.linebenchmark.solver.SolutionEvaluator.java

private void runWithLQNS() {
    StopWatch timer = new StopWatch();
    String solverProgram = "lqns";

    String command = solverProgram + " " + filePath + " -f"; //using the fast option
    logger.info("Launch: " + command);
    //String command = solverProgram+" "+filePath; //without using the fast option
    try {/*from  w w  w.ja  v  a  2 s .co m*/
        ProcessBuilder pb = new ProcessBuilder(splitToCommandArray(command));

        //start counting
        timer.start();
        Process proc = pb.start();
        readStream(proc.getInputStream(), false);
        readStream(proc.getErrorStream(), true);
        int exitVal = proc.waitFor();
        //stop counting
        timer.stop();
        proc.destroy();

        //evaluation error messages
        if (exitVal == LQNS_RETURN_SUCCESS)
            ;
        else if (exitVal == LQNS_RETURN_MODEL_FAILED_TO_CONVERGE) {
            System.err.println(Main.LQNS_SOLVER + " exited with " + exitVal
                    + ": The model failed to converge. Results are most likely inaccurate. ");
            System.err.println("Analysis Result has been written to: " + resultfilePath);
        } else {
            String message = "";
            if (exitVal == LQNS_RETURN_INVALID_INPUT) {
                message = solverProgram + " exited with " + exitVal + ": Invalid Input.";
            } else if (exitVal == LQNS_RETURN_FATAL_ERROR) {
                message = solverProgram + " exited with " + exitVal + ": Fatal error";
            } else {
                message = solverProgram + " returned an unrecognised exit value " + exitVal
                        + ". Key: 0 on success, 1 if the model failed to meet the convergence criteria, 2 if the input was invalid, 4 if a command line argument was incorrect, 8 for file read/write problems and -1 for fatal errors. If multiple input files are being processed, the exit code is the bit-wise OR of the above conditions.";
            }
            System.err.println(message);
        }
    } catch (IOException | InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //tell listeners that the evaluation has been performed
    EvaluationCompletedEvent evaluationCompleted = new EvaluationCompletedEvent(this, 0, null);
    evaluationCompleted.setEvaluationTime(timer.getTime());
    evaluationCompleted.setSolverName(solver);
    evaluationCompleted.setModelPath(filePath.getFileName());
    for (ActionListener l : listeners)
        l.actionPerformed(evaluationCompleted);
}

From source file:com.torodb.integration.mongo.v3m0.jstests.AbstractIntegrationTest.java

protected ByteArrayOutputStream readOutput(int result, Process mongoProcess) throws IOException {
    InputStream inputStream = mongoProcess.getInputStream();
    InputStream erroStream = mongoProcess.getErrorStream();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    if (result != 0) {
        int read;

        while ((read = inputStream.read()) != -1) {
            byteArrayOutputStream.write(read);
        }/* ww w.ja v  a 2s  .  co  m*/

        while ((read = erroStream.read()) != -1) {
            byteArrayOutputStream.write(read);
        }
    }
    return byteArrayOutputStream;
}

From source file:gsu.ugahacksproject.tagg.java

public void dispute(String filePath, String actualResult, String expectedResult) {
    try {/*from   w w w .  ja  va  2s.  c  o  m*/
        //            System.out.println(fileContent);
        // Runtime rt = Runtime.getRuntime();
        Process p = Runtime.getRuntime().exec("python " + commandPath + "/trainNew.py " + filePath + " "
                + actualResult + " bad " + expectedResult);
        BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String line = null;
        while ((line = error.readLine()) != null) {
            System.out.println("Python error: " + line);
        }
        int exitVal = p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.thoughtworks.go.task.rpmbuild.RPMBuildTask.java

@Override
public TaskExecutor executor() {
    return new TaskExecutor() {
        @Override//from  w w w  . j  av  a2  s . c o m
        public ExecutionResult execute(TaskConfig taskConfig, TaskExecutionContext taskExecutionContext) {
            String targetArch = taskConfig.getValue(TARGET_ARCH);
            String specFilePath = taskConfig.getValue(SPEC_FILE);
            List<String> command = Arrays.asList("rpmbuild", "--target", targetArch, "-bb", "-v", "--clean",
                    specFilePath);
            try {
                taskExecutionContext.console().printLine("[exec] " + StringUtils.join(command, " "));
                Process process = runProcess(taskExecutionContext, command);
                taskExecutionContext.console().readOutputOf(process.getInputStream());
                taskExecutionContext.console().readErrorOf(process.getErrorStream());
                try {
                    process.waitFor();
                } catch (InterruptedException e) {
                    // continue
                }
                int exitValue = process.exitValue();
                if (exitValue != 0) {
                    return ExecutionResult.failure("[exec] FAILED with return code " + exitValue);
                }
            } catch (IOException e) {
                return ExecutionResult.failure("[exec] Exception: " + e.getMessage(), e);
            }
            return ExecutionResult.success(
                    String.format("[exec] Successfully executed command [%s]", StringUtils.join(command, " ")));
        }
    };
}

From source file:functionalTests.annotations.AptTest.java

private Result runApt() throws CompilationExecutionException {
    try {/*from   www .  j ava 2 s. c om*/
        ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(_aptCommand));
        Map<String, String> env = processBuilder.environment();
        env.put("CLASSPATH", _classpath);

        Process aptProcess = processBuilder.start();

        BufferedReader stderr = new BufferedReader(new InputStreamReader(aptProcess.getErrorStream()));
        //flushOutput(stderr);

        return getResults(stderr);
    } catch (IOException ioExcp) {
        String msg = "Cannot execute the command " + compressCommand(_aptCommand) + ".reason:"
                + ioExcp.getMessage();
        logger.error(msg, ioExcp);
        throw new CompilationExecutionException(msg, ioExcp);
    } catch (SecurityException secExcp) {
        String msg = "Cannot execute the command " + compressCommand(_aptCommand)
                + "; security access violation.";
        logger.error(msg, secExcp);
        throw new CompilationExecutionException(msg, secExcp);
    }
}

From source file:com.netxforge.oss2.core.utils.ProcessExec.java

/**
 * <p>exec</p>/* ww w  .j  av a2 s  .  co m*/
 *
 * @param cmd an array of {@link java.lang.String} objects.
 * @return a int.
 * @throws java.io.IOException if any.
 * @throws java.lang.InterruptedException if any.
 */
public int exec(String[] cmd) throws IOException, InterruptedException {
    Process p = Runtime.getRuntime().exec(cmd);

    p.getOutputStream().close();
    PrintInputStream out = new PrintInputStream(p.getInputStream(), m_out);
    PrintInputStream err = new PrintInputStream(p.getErrorStream(), m_err);

    Thread t1 = new Thread(out, this.getClass().getSimpleName() + "-stdout");
    Thread t2 = new Thread(err, this.getClass().getSimpleName() + "-stderr");
    t1.start();
    t2.start();

    int exitVal = p.waitFor();

    t1.join();
    t2.join();

    return exitVal;
}

From source file:net.sf.jabref.external.push.PushToVim.java

@Override
public void pushEntries(BibDatabase database, List<BibEntry> entries, String keys, MetaData metaData) {

    couldNotConnect = false;//from w w w.ja  v a  2 s  .c  o m
    couldNotCall = false;
    notDefined = false;

    initParameters();
    commandPath = Globals.prefs.get(commandPathPreferenceKey);

    if ((commandPath == null) || commandPath.trim().isEmpty()) {
        notDefined = true;
        return;
    }

    try {
        String[] com = new String[] { commandPath, "--servername",
                Globals.prefs.get(JabRefPreferences.VIM_SERVER), "--remote-send",
                "<C-\\><C-N>a" + getCiteCommand() + "{" + keys + "}" };

        final Process p = Runtime.getRuntime().exec(com);

        JabRefExecutorService.INSTANCE.executeAndWait(() -> {
            try (InputStream out = p.getErrorStream()) {
                int c;
                StringBuilder sb = new StringBuilder();
                try {
                    while ((c = out.read()) != -1) {
                        sb.append((char) c);
                    }
                } catch (IOException e) {
                    LOGGER.warn("Could not read from stderr.", e);
                }
                // Error stream has been closed. See if there were any errors:
                if (!sb.toString().trim().isEmpty()) {
                    LOGGER.warn("Push to Vim error: " + sb);
                    couldNotConnect = true;
                }
            } catch (IOException e) {
                LOGGER.warn("File problem.", e);
            }
        });
    } catch (IOException excep) {
        couldNotCall = true;
        LOGGER.warn("Problem pushing to Vim.", excep);
    }

}

From source file:de.fau.cs.osr.hddiff.perfsuite.RunXyDiff.java

private String runXyDiff(File fileA, File fileB, File fileDiff) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(new String[] { xyDiffBin, "-o", fileDiff.getAbsolutePath(),
            fileA.getAbsolutePath(), fileB.getAbsolutePath() });

    try (StringWriter w = new StringWriter()) {
        Process p = pb.start();
        new ThreadedStreamReader(p.getErrorStream(), "ERROR", w);
        new ThreadedStreamReader(p.getInputStream(), "OUTPUT", w);

        try {//from  www.  j av a2s .c o m
            TimeoutProcess.waitFor(p, 2000);
        } catch (Exception e) {
            throw new XyDiffException(e);
        }

        if (p.exitValue() == 0)
            return w.toString();
        else
            throw new XyDiffException(w.toString());
    }
}