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:eu.vital.vitalcep.cep.CepProcess.java

public void startCEP() throws FileNotFoundException, IOException {

    this.fileName = RandomStringUtils.randomAlphanumeric(8);

    try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(cepFolder//+"/"+dolceFile
            + "/" + fileName + "_dolce"), "utf-8"))) {
        writer.write(dolce);/*w  ww . ja  v  a2  s .c om*/
        writer.close();

        String cmd = cepFolder + "/bcep -d " + cepFolder + "/" + fileName + "_dolce -mi " + mqin + " -mo "
                + mqout + " -f " + cepFolder + "/" + confFile + " &>/dev/null &";

        logger.debug("starting bCEP with command: " + cmd);
        try {

            Process pr = Runtime.getRuntime().exec(cmd);

            is = pr.getInputStream();
            es = pr.getErrorStream();

            be = new Buffer_eraser();
            be.start();

            PID = getPid(pr);

            if (PID == -1) {
                java.util.logging.Logger.getLogger(CepProcess.class.getName()).log(Level.SEVERE,
                        "couldn't create the process");
                isUp = false;
            } else {
                isUp = true;
                logger.debug("new bCEP created: " + PID);
                logger.debug("mqin: " + mqin);
                logger.debug("mqout: " + mqout);
            }
        } catch (IOException e) {
            java.util.logging.Logger.getLogger(CepProcess.class.getName()).log(Level.SEVERE, e.getMessage());
            PID = -3;
            isUp = false;

        }
    } catch (IOException ex) {
        PID = -2;
        isUp = false;
        this.fileName = "";
        java.util.logging.Logger.getLogger(CepProcess.class.getName()).log(Level.SEVERE, ex.getMessage());
    }

}

From source file:edu.harvard.mcz.imagecapture.TesseractOCR.java

@Override
public String getOCRText() throws OCRReadException {
    StringBuffer result = new StringBuffer();
    BufferedReader resultReader = null;
    try {/*  w  w  w .ja  va 2s.c o  m*/
        Runtime r = Runtime.getRuntime();

        // Run tesseract to OCR the target file.
        String runCommand = Singleton.getSingletonInstance().getProperties().getProperties().getProperty(
                ImageCaptureProperties.KEY_TESSERACT_EXECUTABLE) + target + " " + tempFileBase + " " + language;
        Process proc = r.exec(runCommand);
        System.out.println(runCommand);

        // Create and start a reader for the error stream
        StreamReader errorReader = new StreamReader(proc.getErrorStream(), "ERROR");
        errorReader.run();

        // run the process and wait for the exit value
        int exitVal = proc.waitFor();

        System.out.println("Tesseract Exit Value: " + exitVal);

        if (exitVal == 0) {
            resultReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(tempFileBase + ".txt"), "UTF-8"));
            String s;
            while ((s = resultReader.readLine()) != null) {
                result.append(s);
                result.append("\n");
            }
            resultReader.close();
        } else {
            throw new OCRReadException("OCR process failed (exit value>0).");
        }

        if (result.length() > 0) {
            String resString = result.toString();
            // $ is returned by tesseract to indicate italics
            // @ is returned by tesseract to indicate bold
            // | and _ are common interpretations of QR barcode blocks
            result = new StringBuffer();
            result.append(resString.replaceAll("[|@\\$_]", ""));
        }

    } catch (IOException eio) {
        log.error(eio);
        throw new OCRReadException("OCR process failed with IO Exception.");
    } catch (InterruptedException ei) {
        log.error(ei);
        throw new OCRReadException("OCR process failed with Interrupted Exception.");
    } finally {
        if (resultReader != null) {
            try {
                resultReader.close();
            } catch (IOException e) {
                log.debug(e);
            }
        }
    }

    log.debug(result.toString());
    return result.toString();
}

From source file:cu.uci.uengine.runner.impl.FileRunner.java

@Override
public RunnerResult run(Runnable runnable, RunnerContext runnerContext)
        throws IOException, InterruptedException {

    String command = buildCommand(runnable.getLanguageName(), runnable.getRunnableFile().getAbsolutePath(),
            runnerContext.getTemporaryDirectory().getAbsolutePath());

    log.debug("Running dataset " + runnerContext.getInputFile().getName());

    String name = FilenameUtils.getBaseName(runnerContext.getInputFile().getName());

    File outFile = new File(runnerContext.getTemporaryDirectory(), name + ".out");
    File errFile = new File(runnerContext.getTemporaryDirectory(), name + ".err");

    ProcessBuilder pb = buildProcessBuilder(runnable.getLimits(), runnable.getLanguageName(),
            runnerContext.getInputFile().getAbsolutePath(), outFile, errFile, command,
            String.valueOf(runnable.getId()), runnable.isTrusted());

    Process process = pb.start();

    process.waitFor();//  w w  w . j a v a 2s .  c  o m

    if (process.exitValue() != 0) {
        byte[] processError = new byte[process.getErrorStream().available()];
        process.getErrorStream().read(processError);
        return new RunnerResult(RunnerResult.Result.IE,
                FileUtils.readFileToString(errFile) + new String(processError));
    }
    // result,usertime,cputime,memory
    String[] results = IOUtils.toString(process.getInputStream()).split(",");

    // el resultado OK significa que no dio problema ejecutar
    // con libsandbox. Los demas resultados son errores internos
    // o resultados que no precisan que se siga ejecutando (TLE,
    // MLE, etc.)
    // En OK se debe seguir con el proximo juego de datos, los
    // demas resultados ya detienen la ejecucion.
    RunnerResult result = null;

    String resultCode = results[SandboxResults.RESULT];

    switch (resultCode) {
    case "OK":
        result = new RunnerResult(RunnerResult.Result.OK, name, Long.valueOf(results[SandboxResults.USER_TIME]),
                Long.valueOf(results[SandboxResults.CPU_TIME]),
                Long.valueOf(results[SandboxResults.MEMORY]) * 1024);
        break;
    case "AT":
        result = new RunnerResult(RunnerResult.Result.RT);
        result.messageConcat(FileUtils.readFileToString(errFile));
        break;
    case "TL":
        result = new RunnerResult(RunnerResult.Result.CTL);
        break;
    case "RF":
    case "ML":
    case "OL":
    case "RT":
    case "IE":
    case "BP":
    case "PD":
        result = new RunnerResult(RunnerResult.Result.valueOf(resultCode));
        result.messageConcat(FileUtils.readFileToString(errFile));
        break;
    }

    if (outFile.length() > runnable.getLimits().getMaxOutput()) {
        result = new RunnerResult(RunnerResult.Result.OL);
    }

    return result;
}

From source file:drm.taskworker.workers.OptimusWorker.java

private TaskResult start(File workdir, Task task) throws IOException, ParameterFoundException {
    String obj = (String) task.getParam(PRM_START_FILE);
    // FIXME only works with the adapted taskworker-client script (not committed)
    byte[] file = Base64.decodeBase64(obj);

    String method = (String) task.getParam(PRM_START_METHOD);

    File f = new File(workdir, "input.zip");
    OutputStream out = new FileOutputStream(f);
    out.write(file);// ww  w.j  a  v  a  2 s.  c om
    out.close();

    ProcessBuilder pb = new ProcessBuilder("python", task.getJobOption("optimus.exe"), "input.zip", method);
    pb.directory(workdir);

    Process handle = pb.start();

    (new VoidStreamPump(handle.getInputStream())).start();
    (new VoidStreamPump(handle.getErrorStream())).start();

    handles.put(task.getJobId(), handle);

    // start looking for flag file
    File goFile = new File(workdir, task.getJobOption("optimus.flagfile.go"));
    while (!goFile.exists()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new Error("should not occur", e);
        }
    }
    goFile.delete();
    return split(workdir, task);
}

From source file:cc.arduino.packages.Uploader.java

protected boolean executeUploadCommand(String command[]) throws Exception {
    // Skip empty commands
    if (command == null || command.length == 0)
        return true;

    notFoundError = false;//from  w w  w  .j  a  v a  2s  .  c om
    int result = -1;

    try {
        if (verbose) {
            for (String c : command)
                System.out.print(c + " ");
            System.out.println();
        }
        Process process = ProcessUtils.exec(command);
        programmerPid = process;
        new MessageSiphon(process.getInputStream(), this, 100);
        new MessageSiphon(process.getErrorStream(), this, 100);

        // wait for the process to finish, but not forever
        // kill the flasher process after 5 minutes to avoid 100% cpu spinning
        if (!process.waitFor(5, TimeUnit.MINUTES)) {
            process.destroyForcibly();
        }
        if (!process.isAlive()) {
            result = process.exitValue();
        } else {
            result = 0;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result == 0;
}

From source file:cleaner.ExternalHtmlCleaner.java

@Override
public String CleanText(String html, String encoding) {
    try {//from  ww w  .  ja va 2 s  . com
        File tempIn = File.createTempFile("ExternalParserInput", ".tmp");
        String tempInName = tempIn.getCanonicalPath();
        File tempOut = File.createTempFile("ExternalParserOutput", ".tmp");
        String tempOutName = tempOut.getCanonicalPath();

        FileUtils.writeStringToFile(tempIn, html, encoding);

        String cmd = extScript + " " + tempInName + " " + tempOutName;
        System.out.println("Executing: " + cmd);
        Process proc = Runtime.getRuntime().exec(cmd);

        if (proc == null) {
            System.err.println("Cannot execute command: " + extScript);
            return null;
        }

        StringWriter err = new StringWriter();
        IOUtils.copy(proc.getErrorStream(), err, encoding);

        String ErrStr = err.toString();

        if (!ErrStr.isEmpty()) {
            System.err.println("External script " + extScript + " returned errors:");
            System.err.println(ErrStr);

            throw new Exception("External script " + extScript + " returned errors");
        }

        String out = FileUtils.readFileToString(tempOut);

        tempIn.delete();
        tempOut.delete();

        return LeoCleanerUtil.CollapseSpaces(out);
    } catch (Exception e) {
        System.err.println("Failed to run the script " + extScript + " Error: " + e);
        System.exit(1);
    }
    return null;
}

From source file:org.shept.util.CommandShellExecute.java

/**
 * Run the command shell// ww w . j a  v  a2s . c  om
 */
public void run() {
    String[] cmd = new String[3];

    Assert.notNull(cmdString);

    try {
        isRunning = true;
        exitVal = -1; // noit yet started
        String osName = System.getProperty("os.name");
        if (osName.equals("Windows 95")) {
            cmd[0] = "command.com";
            cmd[1] = "/C";
            cmd[2] = cmdString;
        } else if (osName.startsWith("Windows")) {
            cmd[0] = "cmd.exe";
            cmd[1] = "/C";
            cmd[2] = cmdString;
        } else if (osName.startsWith("Linux")) {
            cmd[0] = "/bin/bash";
            cmd[1] = "-c";
            cmd[2] = cmdString;
        } else {
            log.error("Unsupported operating system " + osName + " for command processing:  " + cmdString);
        }

        Runtime rt = Runtime.getRuntime();
        log.info("Executing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);

        Process proc = rt.exec(cmd, envp, workingDirectory);

        // any error message?
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), true);

        // any output?
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), false);

        // kick them off
        errorGobbler.start();
        outputGobbler.start();

        exitVal = proc.waitFor();
        log.info("Result: " + exitVal.toString());

    } catch (Throwable t) {
        log.error("Execution Error: " + cmd[0] + " " + cmd[1] + " " + cmd[2], t);
    } finally {
        isRunning = false;
    }
    return;
}

From source file:io.fabric8.kit.common.ExternalCommand.java

public void execute(String processInput) throws IOException {
    final Process process = startProcess();
    start();/*  ww  w .  j  av  a2s.c om*/
    try {
        inputStreamPump(process.getOutputStream(), processInput);

        Future<IOException> stderrFuture = startStreamPump(process.getErrorStream());
        outputStreamPump(process.getInputStream());

        stopStreamPump(stderrFuture);
        checkProcessExit(process);
    } catch (IOException e) {
        process.destroy();
        throw e;
    } finally {
        end();
    }
    if (statusCode != 0) {
        throw new IOException(
                String.format("Process '%s' exited with status %d", getCommandAsString(), statusCode));
    }

}

From source file:edu.kit.dama.ui.simon.impl.ShellScriptProbe.java

@Override
public boolean checkProbe() {
    BufferedReader brStdOut = null;
    BufferedReader brStdErr = null;
    try {// www .  j a v a 2  s . c  o  m
        String line;
        Process p = Runtime.getRuntime().exec("sh " + script + ((arguments != null) ? " " + arguments : ""));
        brStdOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
        brStdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((line = brStdOut.readLine()) != null) {
            LOGGER.debug("{}", line);
        }
        brStdOut.close();
        while ((line = brStdErr.readLine()) != null) {
            LOGGER.warn("{}", line);
        }
        brStdErr.close();
        return p.waitFor() == 0;
    } catch (IOException err) {
        LOGGER.error("Script execution failed", err);
        return false;
    } catch (InterruptedException err) {
        LOGGER.error("Script execution might have failed", err);
        return false;
    } finally {
        if (brStdErr != null) {
            try {
                brStdErr.close();
            } catch (IOException ex) {
            }
        }
        if (brStdOut != null) {
            try {
                brStdOut.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:lohbihler.process.epoll.ProcessMonitor.java

public ProcessMonitor(final Process process, final ExecutorService executorService, final long timeout)
        throws InterruptedException {
    final InputReader out = new InputReader(process.getInputStream());
    final InputReader err = new InputReader(process.getErrorStream());

    executorService.execute(out);/* ww  w  .  j av  a 2s . co  m*/
    executorService.execute(err);

    ProcessTimeout processTimeout = null;
    if (timeout > 0) {
        processTimeout = new ProcessTimeout(process, timeout);
        executorService.execute(processTimeout);
    }

    process.waitFor();
    out.join();
    err.join();
    process.destroy();

    // If we've made it this far, the process exited properly, so kill the
    // timeout thread if it exists.
    if (processTimeout != null)
        processTimeout.interrupt();

    this.out = out.getInput();
    this.err = err.getInput();
}