Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

In this page you can find the example usage for java.lang ProcessBuilder redirectErrorStream.

Prototype

boolean redirectErrorStream

To view the source code for java.lang ProcessBuilder redirectErrorStream.

Click Source Link

Usage

From source file:org.mashupmedia.encode.ProcessManager.java

public void startProcess(ProcessQueueItem processQueueItem) throws IOException {

    try {//from  w ww.j av a  2s.  co  m
        logger.info("Starting process...");
        List<String> commands = processQueueItem.getCommands();

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();

        // The started on date should have already been set
        Date startedOn = processQueueItem.getProcessStartedOn();
        if (startedOn == null) {
            processQueueItem.setProcessStartedOn(new Date());
        }

        processQueueItem.setProcess(process);

        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            logger.info(line);
        }
        IOUtils.closeQuietly(inputStream);

        try {
            int waitForValue = process.waitFor();
            logger.info("Process waitFor value = " + waitForValue);
        } catch (InterruptedException e) {
            logger.error("Error waiting for waitFor.", e);
        }

        int exitValue = process.exitValue();
        logger.info("Process exit value = " + exitValue);

    } finally {
        processQueueItems.remove(processQueueItem);
        encodeMediaItemTaskManager.processQueue();
    }

}

From source file:org.obiba.opal.server.UpgradeCommand.java

private ProcessBuilder getOpalMigratorProcessBuilder(String... args) {
    String dist = System.getenv("OPAL_DIST");
    if (Strings.isNullOrEmpty(dist))
        throw new RuntimeException("Cannot locate opal tools directory: OPAL_DIST is not defined.");

    File toolsDir = Paths.get(dist, "tools", "lib").toFile();
    if (!toolsDir.exists() || !toolsDir.isDirectory())
        throw new RuntimeException("No such directory: " + toolsDir.getAbsolutePath());

    File[] jars = toolsDir.listFiles(new FilenameFilter() {
        @Override//from   w  w  w . j  av a 2  s .co m
        public boolean accept(File dir, String name) {
            return name.startsWith("opal-config-migrator-") && name.endsWith("-cli.jar");
        }
    });
    if (jars == null || jars.length == 0)
        throw new RuntimeException(String.format("Cannot find any opal-config-migrator-*-cli.jar file in '%s'",
                toolsDir.getAbsolutePath()));

    List<String> processArgs = Lists.newArrayList("java", "-jar", jars[0].getName());
    processArgs.addAll(Arrays.asList(args));

    log.info("Running Opal config migrator command: {}", Joiner.on(" ").join(processArgs));

    ProcessBuilder pb = new ProcessBuilder(processArgs);
    pb.redirectErrorStream(true);
    pb.directory(toolsDir);

    return pb;
}

From source file:zipkin.execjar.ExecJarRule.java

@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {
        public void evaluate() throws Throwable {
            try {
                ProcessBuilder bootBuilder = new ProcessBuilder("java", "-jar", execJar);
                bootBuilder.environment().put("SERVER_PORT", String.valueOf(port()));
                bootBuilder.environment().putAll(environment);
                bootBuilder.redirectErrorStream(true);
                bootApp = bootBuilder.start();

                CountDownLatch startedOrCrashed = new CountDownLatch(1);
                Thread consoleReader = new Thread(() -> {
                    boolean foundStartMessage = false;
                    try (BufferedReader reader = new BufferedReader(
                            new InputStreamReader(bootApp.getInputStream()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.indexOf("JVM running for") != -1) {
                                foundStartMessage = true;
                                startedOrCrashed.countDown();
                            }/*w  ww.j av a 2 s . c om*/
                            console.add(line);
                        }
                    } catch (Exception e) {
                    } finally {
                        if (!foundStartMessage)
                            startedOrCrashed.countDown();
                    }
                });
                consoleReader.setDaemon(true);
                consoleReader.start();

                if (!startedOrCrashed.await(10, TimeUnit.SECONDS)) {
                    throw new AssumptionViolatedException("Took too long to start or crash");
                }

                base.evaluate();
            } finally {
                bootApp.destroy();
            }
        }
    };
}

From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java

public void execute(MediaRecord record, File directory) throws EncoderException {

    LOGGER.info(" ffmpeg ?  video ...  Ffmpeg  ===>>> " + args);

    final ProcessBuilder pb = new ProcessBuilder().directory(directory);
    pb.redirectErrorStream(true);
    if (null != directory) {
        LOGGER.info("ffmpeg ??==========>>>" + directory.toString());
    }/*  w w  w  .  jav  a2  s. c  om*/

    pb.command(args);

    try {
        final Process process = pb.start();
        inputStream = process.getInputStream();

        MediaInputStreamParser.parseMediaRecord(inputStream, record);

        outputStream = process.getOutputStream();
        errorStream = process.getErrorStream();
        // ???????.
        //         BufferedInputStream in = new BufferedInputStream(inputStream);
        //         BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
        //         String lineStr;
        //         while ((lineStr = inBr.readLine()) != null)
        //            LOGGER.info("process.getInputStream() ===>>> " + lineStr);

        int waitfor = process.waitFor();
        if (waitfor != 0) {
            //p.exitValue()==0?1??
            if (process.exitValue() == 1) {
                LOGGER.info("===>>> ffmpeg ? Failed!");
                throw new EncoderException("ffmpeg ? Failed!");
            } else {
                LOGGER.info("==========>>> ffmpeg ??.");
            }
        } else {
            LOGGER.info("==========>>> ffmpeg ??.");
        }

    } catch (IOException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
    } catch (InterruptedException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        destroy();
    }
}

From source file:org.opencb.cellbase.app.cli.CommandExecutor.java

private ProcessBuilder getProcessBuilder(File workingDirectory, String binPath, List<String> args,
        String logFilePath) {/*from  www.j a  va2  s . co m*/
    List<String> commandArgs = new ArrayList<>();
    commandArgs.add(binPath);
    commandArgs.addAll(args);
    ProcessBuilder builder = new ProcessBuilder(commandArgs);

    // working directoy and error and output log outputs
    if (workingDirectory != null) {
        builder.directory(workingDirectory);
    }
    builder.redirectErrorStream(true);
    if (logFilePath != null) {
        builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
    }

    return builder;
}

From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java

public void executeAll() throws IOException, InterruptedException {

    File target = new File("target");
    target.mkdir();//  ww w  .j av  a 2 s  .c o m

    ProcessBuilder pb = new ProcessBuilder("/usr/bin/make", "clean");
    Map<String, String> env = pb.environment();
    pb.directory(new File(homeDir, "linux"));
    File logFile = new File("log");
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    Process p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/bin/make");
    pb.directory(new File(homeDir, "linux"));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/local/bin/protoc", "-I/usr/include", "--proto_path=src/main/protobuf",
            "src/main/protobuf/sample.proto",
            "--plugin=" + this.homeDir.getAbsolutePath() + "/linux/protoc-gen-docbook", "--docbook_out=target");
    pb.directory(new File("."));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/bin/fop", "-xml", "target/docbook_out.xml", "-xsl",
            "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl", "-pdf", "target/docbook_out.pdf",
            "-param", "page.orientation", "landscape", "-param", "paper.type", "USletter");
    pb.directory(new File("."));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = br.readLine()) != null) {
        if (this.log.isInfoEnabled())
            this.log.info(line);
    }
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.externals.helpers.ExternalProcessExecutor.java

public ExternalProcessExecutorResult run(String[] command, String workingDir, Map<String, String> properties) {

    String lineToRun = Arrays.asList(command).stream().collect(Collectors.joining(" "));

    LOGGER.info("===================");
    LOGGER.info("Command to invoke: {}", lineToRun);

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    updateEnvOfProcessBuilder(processBuilder.environment(), properties);

    if (workingDir != null) {
        processBuilder.directory(new File(workingDir));
    }//from w w w .  j a v  a  2 s.  c  om
    processBuilder.redirectErrorStream(true);

    StringBuilder processOutput = new StringBuilder();
    Process process;
    BufferedReader stdout = null;

    try {
        process = processBuilder.start();
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while ((line = stdout.readLine()) != null) {
            LOGGER.debug(":::::: " + line);
            processOutput.append(line);
            processOutput.append('\n');
        }

        try {
            process.waitFor();
        } catch (InterruptedException e) {
            LOGGER.error("Command '" + lineToRun + "' interrupted.", e);
        }
    } catch (IOException e) {
        LOGGER.error("Problem executing external process.", e);
        return new ExternalProcessExecutorResult(Integer.MIN_VALUE, "", e);
    } finally {
        closeReader(stdout);
    }

    ExternalProcessExecutorResult result = new ExternalProcessExecutorResult(process.exitValue(),
            processOutput.toString(), null);

    LOGGER.info("Exit value: {}", result.getExitCode());
    LOGGER.info("===================");
    return result;
}

From source file:org.zgis.wps.swat.AnnotatedSwatRunnerAlgorithm.java

@Execute
public void runSwatProcess() throws IOException {
    logger.info("Trying to run SWAT model");

    //TODO make a list of needed directories and create in loop
    String tempDirStr = ExecutionContextFactory.getContext().getTempDirectoryPath();
    File tempDir = new File(tempDirStr + System.getProperty("file.separator"));
    File swatModelDir = new File(tempDirStr + System.getProperty("file.separator") + "swatmodel"
            + System.getProperty("file.separator"));

    logger.info("Temp dir is: " + tempDirStr);
    logger.info("Temp file is: " + tempDir.getAbsolutePath());

    try {/*w  ww.j av a  2 s . co  m*/
        if (!tempDir.isDirectory() && !tempDir.mkdirs()) {
            throw new IOException("Could not create temp dir " + tempDir);
        }
        if (!swatModelDir.isDirectory() && !swatModelDir.mkdirs()) {
            throw new IOException("Could not create swatmodel dir " + tempDir);
        }

        //unpack swat model
        if (swatInputZip == null) {
            logger.info("SwatInputZip was NULL");
        } else if (swatInputZip.size() != 1) {
            logger.info("SwatInputZip size != 1 - " + swatInputZip.size());
        } else {
            logger.info("Unpacking swatInputZip " + swatInputZip.get(0).getBaseFile(false).getAbsolutePath()
                    + " to " + swatModelDir.getAbsolutePath());
            net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile(
                    swatInputZip.get(0).getBaseFile(false));
            zipFile.extractAll(swatModelDir.getAbsolutePath());
        }

        URI jarUri = this.getJarURI();
        logger.debug("Jar-File URI " + jarUri);

        //FIXME this is bullshit, make own jar for every OS and provide executable this way.
        String exeFilename = "swat/swat_rel64";
        if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
            exeFilename = exeFilename.concat("_win.exe");
        } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {
            exeFilename = exeFilename.concat("_osx");
        } else if (System.getProperty("os.name").toLowerCase().startsWith("linux")) {
            exeFilename = exeFilename.concat("_linux");
        } else {
            logger.warn("Could not determine OS, trying generic executable name");
        }

        URI exeFile = getFile(jarUri, exeFilename);
        new File(exeFile).setExecutable(true);

        ProcessBuilder pb = new ProcessBuilder(new File(exeFile).toString());
        pb.redirectErrorStream(true);
        pb.directory(swatModelDir);
        Process process = pb.start();
        InputStream stdOutStream = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdOutStream);
        BufferedReader br = new BufferedReader(isr);
        String line;
        logger.info(String.format("Output of running %s is:\n", Arrays.toString(pb.command().toArray())));
        while ((line = br.readLine()) != null) {
            logger.info(line);
            this.swatConsoleOutput = this.swatConsoleOutput.concat(line).concat("\n");
        }

        int exitValue = process.waitFor();
        if (exitValue != 0) {
            throw new IOException("SWAT didn't complete successfully");
        }

        Collection<File> outFiles = FileUtils.listFiles(swatModelDir, new WildcardFileFilter("output.*"),
                TrueFileFilter.TRUE);
        File outFilesZippend = org.n52.wps.io.IOUtils.zip(outFiles.toArray(new File[outFiles.size()]));
        this.swatOutputZipped = new GenericFileData(outFilesZippend, "application/zip");
    } catch (URISyntaxException e) {
        logger.error("Could not determine uri of jar. ", e);
        throw new IOException("Could not determine uri of jar. ", e);
    } catch (InterruptedException e) {
        logger.error("Exception on running SWAT process.", e);
        throw new IOException("Exception on running SWAT process.", e);
    } catch (net.lingala.zip4j.exception.ZipException e) {
        logger.error("Could not extract swat input model.", e);
        throw new IOException("Could not extract swat input model.", e);
    } finally {
        //TODO FIXME is that really necessary? The Execution context should delete this?
        /*
                    if (tempDir.isDirectory()) {
        FileUtils.deleteDirectory(tempDir);
                    }
        */
    }
}

From source file:org.kududb.client.MiniKuduCluster.java

/**
 * Starts a process using the provided command and configures it to be daemon,
 * redirects the stderr to stdout, and starts a thread that will read from the process' input
 * stream and redirect that to LOG.// w w  w . j  a va 2s  . c  o  m
 * @param command Process and options
 * @return The started process
 * @throws Exception Exception if an error prevents us from starting the process,
 * or if we were able to start the process but noticed that it was then killed (in which case
 * we'll log the exit value).
 */
private Process configureAndStartProcess(String[] command) throws Exception {
    LOG.info("Starting process: {}", Joiner.on(" ").join(command));
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    Process proc = processBuilder.start();
    ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable(
            proc.getInputStream());
    Thread thread = new Thread(printer);
    thread.setDaemon(true);
    thread.setName(command[0]);
    PROCESS_INPUT_PRINTERS.add(thread);
    thread.start();

    Thread.sleep(300);
    try {
        int ev = proc.exitValue();
        throw new Exception(
                "We tried starting a process (" + command[0] + ") but it exited with " + "value=" + ev);
    } catch (IllegalThreadStateException ex) {
        // This means the process is still alive, it's like reverse psychology.
    }
    return proc;
}

From source file:org.zaproxy.zap.extension.invoke.InvokeAppWorker.java

@Override
protected Void doInBackground() throws Exception {

    String url = ""; // Full URL
    String host = ""; // Just the server name, e.g. localhost
    String port = ""; // the port
    String site = ""; // e.g. http://localhost:8080/
    String postdata = ""; // only present in POST ops
    String cookie = ""; // from the request header
    HistoryReference historyRef = msg.getHistoryRef();
    int msgid = -1;

    if (historyRef != null) {
        msgid = historyRef.getHistoryId();
    }/*from w  w w. j  a  v  a  2s  .  c  o  m*/

    URI uri = msg.getRequestHeader().getURI();
    url = uri.toString();
    host = uri.getHost();
    site = uri.getScheme() + "://" + uri.getHost();
    if (uri.getPort() > 0) {
        port = String.valueOf(uri.getPort());
        site = site + ":" + port + "/";
    } else {
        if (uri.getScheme().equalsIgnoreCase("http")) {
            port = "80";
        } else if (uri.getScheme().equalsIgnoreCase("https")) {
            port = "443";
        }
        site = site + "/";
    }
    if (msg.getRequestBody() != null) {
        postdata = msg.getRequestBody().toString();
        postdata = postdata.replaceAll("\n", "\\n");
    }
    Vector<String> cookies = msg.getRequestHeader().getHeaders(HttpHeader.COOKIE);
    if (cookies != null && cookies.size() > 0) {
        cookie = cookies.get(0);
    }

    List<String> cmd = new ArrayList<>();
    cmd.add(command);
    if (parameters != null) {
        for (String parameter : parameters.split(" ")) {
            // Replace all of the tags
            String finalParameter = parameter.replace("%url%", url).replace("%host%", host)
                    .replace("%port%", port).replace("%site%", site).replace("%cookie%", cookie)
                    .replace("%postdata%", postdata).replace("%msgid%", String.valueOf(msgid));

            // Replace header tags
            Matcher headers = Pattern.compile("%header-([A-z0-9_-]+)%").matcher(finalParameter);
            while (headers.find()) {
                String headerValue = msg.getRequestHeader().getHeader(headers.group(1));
                if (headerValue == null) {
                    headerValue = "";
                }
                finalParameter = finalParameter.replace(headers.group(0), headerValue);
            }

            cmd.add(finalParameter);
        }
    }

    logger.debug("Invoking: " + cmd.toString());
    View.getSingleton().getOutputPanel().append("\n" + cmd.toString() + "\n");
    ProcessBuilder pb = new ProcessBuilder(cmd);
    if (workingDir != null) {
        pb.directory(workingDir);
    }
    pb.redirectErrorStream(true);
    Process proc;
    try {
        proc = pb.start();
    } catch (final Exception e) {
        View.getSingleton().getOutputPanel()
                .append(Constant.messages.getString("invoke.error") + e.getLocalizedMessage() + "\n");
        logger.warn("Failed to start the process: " + e.getMessage(), e);
        return null;
    }

    if (captureOutput) {
        try (BufferedReader brOut = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
            String line;
            boolean isOutput = false;
            StringBuilder sb = new StringBuilder();
            if (msg.getNote() != null) {
                sb.append(msg.getNote());
                sb.append('\n');
            }

            // Show any stdout/error messages
            while ((line = brOut.readLine()) != null) {
                View.getSingleton().getOutputPanel().append(line + "\n");
                sb.append(line);
                sb.append('\n');
                isOutput = true;
            }
            if (isOutput) {
                // Somethings been written, switch to the Output tab
                View.getSingleton().getOutputPanel().setTabFocus();
            }

            if (outputNote) {
                HistoryReference hr = msg.getHistoryRef();
                if (hr != null) {
                    hr.setNote(sb.toString());
                }
            }
        }
    }

    return null;
}