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:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramCompileManagerImpl.java

private void generateMigClass(File headerFile, String messageType, File directory) throws IOException {

    ProcessBuilder processBuilder;

    log.info("Generating MIG classes from header file: " + headerFile.getAbsolutePath() + " for messageType: "
            + messageType + " to directory " + directory.getAbsolutePath());

    processBuilder = new ProcessBuilder(MIG, "java", "-java-classname=" + messageType,
            headerFile.getAbsolutePath(), messageType, "-o",
            directory.getAbsolutePath() + "/" + messageType + ".java");

    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

    try {/*from ww  w  .j a va2s.c  o m*/
        process.waitFor();
        int exitValue = process.exitValue();

        if (exitValue != 0) {
            log.error("MIG Failed with exit code:  " + exitValue);
            throw new IOException("MIG Failed with exit code " + exitValue);
        }
    } catch (InterruptedException ex) {
        log.warn("MIG interrupted");
    }
}

From source file:monasca.api.integration.docker.ITInfluxDBTest.java

private void runAPI() throws Exception {

    if (!isPortFree(8070)) {
        throw new Exception("port 8070 is not free. Unable to start instance" + " of monasca api");
    }//from   w ww .  java  2s . c o m

    String latestShadedJarFileName = getLatestShadedJarFileName();
    System.out.println("Running " + latestShadedJarFileName);

    ProcessBuilder pb = new ProcessBuilder("java", "-cp", "./target/" + latestShadedJarFileName,
            "monasca.api.MonApiApplication", "server", "src/test/resources/mon-api-config.yml");
    File log = new File("mon-api-integration-test.log");
    pb.redirectErrorStream(true);
    pb.redirectOutput(ProcessBuilder.Redirect.appendTo(log));
    apiProcess = pb.start();

    System.out.println("Started " + latestShadedJarFileName);

    waitForPortReady("localhost", 8070);
}

From source file:eu.numberfour.n4js.npmexporter.ui.NpmExportWizard.java

@Override
public boolean performFinish() {

    String destination = exportPage.getDestinationValue();
    List<IProject> toExport = exportPage.getChosenProjects();
    boolean shouldPackAsTarball = exportPage.getShouldPackAsTarball();

    File folder = new File(destination);

    // remap all IProjects
    List<? extends IN4JSProject> toExportIN4JSProjects = mapToIN4JSProjects(toExport);

    if (runTools() && toolRunnerPage.isToolrunRequested()) {
        // bring to front.
        ((WizardDialog) getContainer()).showPage(toolRunnerPage);
    }/* www . j  av a  2 s. c o  m*/

    try {

        npmExporter.export(toExportIN4JSProjects, folder);

        if (shouldPackAsTarball) {
            npmExporter.tarAndZip(toExportIN4JSProjects, folder);
        }

        boolean runIt = runTools() && toolRunnerPage.queryRunTool();
        if (runIt) {
            final List<String> toolCommand = toolRunnerPage.getCommand();

            getContainer().run(true, true, new IRunnableWithProgress() {
                @Override
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    try {

                        List<String> cmds = newArrayList();
                        // cmds.add("echo"); // prepend with echo for debug TODO remove
                        // cmds.addAll(toolCommand);
                        cmds.add("bash");
                        cmds.add("-login");
                        cmds.add("-c");
                        // cmds.addAll(toolCommand);
                        cmds.add(Joiner.on(" ").join(toolCommand));

                        System.out.println("Comman will be: " + Joiner.on(" :: ").join(cmds));

                        for (IN4JSProject p : toExportIN4JSProjects) {

                            String info = "Processing " + p.toString() + "\n";
                            System.out.println(info);
                            toolRunnerPage.appendText(info);

                            File dir = npmExporter.exportDestination(p, folder);

                            ProcessBuilder pb = new ProcessBuilder();
                            pb.directory(dir);
                            pb.command(cmds);
                            pb.redirectErrorStream(true);
                            Process proc = pb.start();

                            // handle each of proc's streams in a separate thread
                            ExecutorService handlerThreadPool = Executors.newFixedThreadPool(3);

                            // handlerThreadPool.submit(new Runnable() {
                            // @Override
                            // public void run() {
                            // // we want to write to the stdin of the process
                            // BufferedWriter stdin = new BufferedWriter(
                            // new OutputStreamWriter(proc.getOutputStream()));
                            //
                            // // read from our own stdin so we can write it to proc's stdin
                            // BufferedReader myStdin =
                            // new BufferedReader(new InputStreamReader(System.in));
                            // String line = null;
                            // try {
                            // do {
                            // line = myStdin.readLine();
                            // stdin.write(String.format("%s%n", line));
                            // stdin.flush();
                            // } while(! "exit".equalsIgnoreCase(line));
                            // } catch(IOException e) {
                            // e.printStackTrace();
                            // }
                            // }
                            // });

                            handlerThreadPool.submit(new Runnable() {
                                @Override
                                public void run() {
                                    // we want to read the stdout of the process
                                    BufferedReader stdout = new BufferedReader(
                                            new InputStreamReader(proc.getInputStream()));
                                    String line;
                                    try {
                                        while (null != (line = stdout.readLine())) {
                                            System.err.printf("[stderr] %s%n", line);
                                            toolRunnerPage.appendConsoleOut(line);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                            handlerThreadPool.submit(new Runnable() {
                                @Override
                                public void run() {
                                    // we want to read the stderr of the process
                                    BufferedReader stderr = new BufferedReader(
                                            new InputStreamReader(proc.getErrorStream()));
                                    String line;
                                    try {
                                        while (null != (line = stderr.readLine())) {
                                            System.err.printf("[stderr] %s%n", line);
                                            toolRunnerPage.appendConsoleErr(line);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                            // wait for the process to terminate
                            int exitCode = proc.waitFor();
                            System.out.printf("Process terminated with exit code %d%n", exitCode);
                            handlerThreadPool.shutdown();

                        }

                        // done with all projects.
                        // wait for close.

                        toolRunnerPage.queryCloseDialog();

                    } catch (Exception e) {
                        throw new InvocationTargetException(e);
                    }
                }
            });
        }

    } catch (IOException | ArchiveException | CompressorException e) {

        e.printStackTrace();

        Status s = new Status(ERROR, NpmExporterActivator.PLUGIN_ID, "Error occured during export.", e);
        N4JSActivator.getInstance().getLog().log(s);

        return false;
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // successfully done, then store relevant history:
    exportPage.finish();
    if (runTools()) {
        toolRunnerPage.finish();
    }

    return true;
}

From source file:com.pinterest.deployservice.scm.PhabricatorManager.java

private Map<String, Object> queryCLI(String input) throws Exception {
    ProcessBuilder builder;
    if (StringUtils.isEmpty(arcrcLocation)) {
        builder = new ProcessBuilder(arcLocation, "call-conduit", String.format("--conduit-uri=%s", urlPrefix),
                "diffusion.historyquery");
    } else {/*from   w  w  w .  ja  va 2s.  c  o m*/
        builder = new ProcessBuilder(arcLocation, "call-conduit", String.format("--conduit-uri=%s", urlPrefix),
                "diffusion.historyquery", "--arcrc-file", arcrcLocation);
    }
    LOG.debug("Execute arc command: \n{}", builder.command());

    // Redirects error stream to output stream, so have only one input stream to read from
    builder.redirectErrorStream(true);

    // Run command
    Process process = builder.start();

    // Feed the input parameters
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    writer.write(input);
    writer.flush();
    writer.close();

    InputStream stdout = process.getInputStream();
    String line;
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));

    // Read response
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    reader.close();

    // We will remove "Waiting for JSON parameters on stdin..." from the output if exists
    String output = sb.toString();
    if (output.startsWith(ARC_OUTPUT_NOTICE)) {
        output = output.substring(ARC_OUTPUT_NOTICE_LEN);
    }
    LOG.debug("arc command output is: \n{}", output);

    GsonBuilder gson = new GsonBuilder();
    return gson.create().fromJson(output, new TypeToken<HashMap<String, Object>>() {
    }.getType());
}

From source file:org.lab41.graphlab.twill.GraphLabRunnable.java

private void runProcess(int instanceCount) throws ExecutionException, InterruptedException, IOException {
    FileSystem fileSystem = FileSystem.get(new Configuration());

    File graphLabPath = arguments.getGraphLabPath();
    Preconditions.checkNotNull(graphLabPath, "graphlab path is null");
    Preconditions.checkArgument(graphLabPath.exists(), "graphlab path does not exist");

    Path inputPath = arguments.getInputPath();
    Preconditions.checkNotNull(inputPath, "input path is null");
    Preconditions.checkNotNull(fileSystem.exists(inputPath), "input path does not exist");

    String inputFormat = arguments.getInputFormat();
    Preconditions.checkNotNull(inputFormat, "input format is null");

    Path outputPath = arguments.getOutputPath();
    Preconditions.checkNotNull(outputPath, "output path is null");

    String zkStr = System.getenv("TWILL_ZK_CONNECT");
    Preconditions.checkNotNull(zkStr);//w  w  w. j a  v  a  2  s .co m

    // Start building up the command line.
    List<String> args = new ArrayList<>();
    args.add(graphLabPath.toString());
    args.add("--graph");
    args.add(inputPath.toString());
    args.add("--format");
    args.add(inputFormat);

    // We need to treat some algorithms specially.
    String commandName = graphLabPath.getName();

    switch (commandName) {
    case "simple_coloring":
        args.add("--output");
        args.add(outputPath.toString());
        break;
    case "TSC":
        // do nothing. TSC outputs to stdout, so we'll have to capture it ourselves.
        break;
    default:
        args.add("--saveprefix");
        args.add(outputPath.toString());
        break;
    }

    ProcessBuilder processBuilder = new ProcessBuilder(args);

    Map<String, String> env = processBuilder.environment();

    env.clear();
    env.put("CLASSPATH", getHadoopClassPath());
    env.put("ZK_SERVERS", zkStr);
    env.put("ZK_JOBNAME", "graphLab-workers");
    env.put("ZK_NUMNODES", Integer.toString(instanceCount));

    if (!commandName.equals("TSC")) {
        processBuilder.redirectErrorStream(true);
    }

    LOG.info("executing: " + args);

    Process process = processBuilder.start();

    ExecutorService executor = Executors.newFixedThreadPool(2);

    try {
        Future<Void> stdoutFuture;

        if (commandName.equals("TSC")) {
            // The TSC outputs to stdout, so capture and redirect it to our file.
            stdoutFuture = executor
                    .submit(captureInputStream(fileSystem, process.getInputStream(), outputPath));
        } else {
            // Otherwise, write the output to the log file.
            stdoutFuture = executor.submit(logInputStream(process.getInputStream()));
        }

        // Also write the stderr to the log file.
        Future<Void> stderrFuture = executor.submit(logInputStream(process.getErrorStream()));

        // Ignore errors for now.
        int exitCode = process.waitFor();

        LOG.info("process exited with " + exitCode);

        stdoutFuture.get();
        stderrFuture.get();
    } finally {
        executor.shutdown();
    }
}

From source file:org.broadinstitute.sting.utils.runtime.ProcessController.java

/**
 * Executes a command line program with the settings and waits for it to return,
 * processing the output on a background thread.
 *
 * @param settings Settings to be run.//  www.  j a v  a 2 s .  c o m
 * @return The output of the command.
 */
public ProcessOutput exec(ProcessSettings settings) {
    if (destroyed)
        throw new IllegalStateException("This controller was destroyed");

    ProcessBuilder builder = new ProcessBuilder(settings.getCommand());
    builder.directory(settings.getDirectory());

    Map<String, String> settingsEnvironment = settings.getEnvironment();
    if (settingsEnvironment != null) {
        Map<String, String> builderEnvironment = builder.environment();
        builderEnvironment.clear();
        builderEnvironment.putAll(settingsEnvironment);
    }

    builder.redirectErrorStream(settings.isRedirectErrorStream());

    StreamOutput stdout = null;
    StreamOutput stderr = null;

    // Start the process running.

    try {
        synchronized (toCapture) {
            process = builder.start();
        }
        running.add(this);
    } catch (IOException e) {
        throw new ReviewedStingException(
                "Unable to start command: " + StringUtils.join(builder.command(), " "));
    }

    int exitCode;

    try {
        // Notify the background threads to start capturing.
        synchronized (toCapture) {
            toCapture.put(ProcessStream.Stdout, new CapturedStreamOutput(settings.getStdoutSettings(),
                    process.getInputStream(), System.out));
            toCapture.put(ProcessStream.Stderr, new CapturedStreamOutput(settings.getStderrSettings(),
                    process.getErrorStream(), System.err));
            toCapture.notifyAll();
        }

        // Write stdin content
        InputStreamSettings stdinSettings = settings.getStdinSettings();
        Set<StreamLocation> streamLocations = stdinSettings.getStreamLocations();
        if (!streamLocations.isEmpty()) {
            try {
                OutputStream stdinStream = process.getOutputStream();
                for (StreamLocation location : streamLocations) {
                    InputStream inputStream;
                    switch (location) {
                    case Buffer:
                        inputStream = new ByteArrayInputStream(stdinSettings.getInputBuffer());
                        break;
                    case File:
                        try {
                            inputStream = FileUtils.openInputStream(stdinSettings.getInputFile());
                        } catch (IOException e) {
                            throw new UserException.BadInput(e.getMessage());
                        }
                        break;
                    case Standard:
                        inputStream = System.in;
                        break;
                    default:
                        throw new ReviewedStingException("Unexpected stream location: " + location);
                    }
                    try {
                        IOUtils.copy(inputStream, stdinStream);
                    } finally {
                        if (location != StreamLocation.Standard)
                            IOUtils.closeQuietly(inputStream);
                    }
                }
                stdinStream.flush();
            } catch (IOException e) {
                throw new ReviewedStingException(
                        "Error writing to stdin on command: " + StringUtils.join(builder.command(), " "), e);
            }
        }

        // Wait for the process to complete.
        try {
            process.getOutputStream().close();
            process.waitFor();
        } catch (IOException e) {
            throw new ReviewedStingException(
                    "Unable to close stdin on command: " + StringUtils.join(builder.command(), " "), e);
        } catch (InterruptedException e) {
            throw new ReviewedStingException("Process interrupted", e);
        } finally {
            while (!destroyed && stdout == null || stderr == null) {
                synchronized (fromCapture) {
                    if (fromCapture.containsKey(ProcessStream.Stdout))
                        stdout = fromCapture.remove(ProcessStream.Stdout);
                    if (fromCapture.containsKey(ProcessStream.Stderr))
                        stderr = fromCapture.remove(ProcessStream.Stderr);
                    try {
                        if (stdout == null || stderr == null)
                            fromCapture.wait();
                    } catch (InterruptedException e) {
                        // Log the error, ignore the interrupt and wait patiently
                        // for the OutputCaptures to (via finally) return their
                        // stdout and stderr.
                        logger.error(e);
                    }
                }
            }

            if (destroyed) {
                if (stdout == null)
                    stdout = StreamOutput.EMPTY;
                if (stderr == null)
                    stderr = StreamOutput.EMPTY;
            }
        }
    } finally {
        synchronized (toCapture) {
            exitCode = process.exitValue();
            process = null;
        }
        running.remove(this);
    }

    return new ProcessOutput(exitCode, stdout, stderr);
}

From source file:com.anthemengineering.mojo.infer.InferMojo.java

/**
 * Executes infer once for each source file and writes the output to {@code inferOutputDir}.
 *
 * @param classpath classpath used as an argument to the javac command given to Infer.
 * @param inferOutputDir directory where Infer will write its output
 * @param sourceFiles collection of files for Infer to analyze
 * @param numSourceFiles number of source files to analyze; used to make sure every Infer execution finishes
 * before moving on./*w  ww.  ja  va2  s.c  o  m*/
 */
private void completeInferExecutions(final String classpath, final File inferOutputDir,
        Collection<File> sourceFiles, int numSourceFiles) throws MojoExecutionException {
    // temporary directory for storing .class files created by {@code javac}; placed in build directory
    final File buildTmpDir = new File(project.getBuild().getDirectory(), JAVAC_OUTPUT_DIRECTORY_NAME);
    try {
        FileUtils.forceMkdir(buildTmpDir);
    } catch (final IOException e) {
        final String errMsg = String.format("Unable to make temp directory %s!", buildTmpDir.getAbsolutePath());
        getLog().error(errMsg, e);
        throw new MojoExecutionException(errMsg, e);
    }
    buildTmpDir.deleteOnExit();

    // used to wait for all processes running infer to complete
    final CountDownLatch doneSignal = new CountDownLatch(numSourceFiles);

    // TODO: optionally allow debugging info? Output directory?

    // TODO: a better way to do this may be to determine if there is an entry point that takes a set of source
    //  files and the classpath and use this. @See mvn, inferj and inferlib in the infer repository.

    ExecutorService pool = null;
    try {
        pool = Executors.newFixedThreadPool(4);

        for (final File sourceFile : sourceFiles) {
            final Runnable r = new Runnable() {
                @Override
                public void run() {
                    Process proc = null;

                    try {
                        // infer
                        final List<String> command = new ArrayList<String>();
                        command.add(inferPath);
                        command.add("-i");
                        command.add("-o");
                        command.add(inferOutputDir.getAbsolutePath());

                        command.add("--");

                        // javac
                        command.add("javac");
                        command.add(sourceFile.getAbsolutePath());
                        command.add("-d");
                        command.add(buildTmpDir.getAbsolutePath());
                        command.add("-classpath");
                        command.add(classpath);

                        final ProcessBuilder builder = new ProcessBuilder(command);
                        builder.environment().putAll(System.getenv());

                        if (consoleOut) {
                            builder.redirectErrorStream(true);
                            proc = builder.start();

                            InputStreamReader isr = null;
                            BufferedReader br = null;
                            InputStream pis = null;

                            try {
                                pis = proc.getInputStream();

                                isr = new InputStreamReader(pis);
                                br = new BufferedReader(isr);
                                String line = null;
                                while ((line = br.readLine()) != null) {
                                    getLog().info(line);
                                }
                            } catch (final IOException e) {
                                getLog().error(String.format("Error writing process output for file: %s.",
                                        sourceFile.getAbsolutePath()), e);
                            } finally {
                                if (isr != null) {
                                    isr.close();
                                }

                                if (br != null) {
                                    br.close();
                                }

                                if (pis != null) {
                                    pis.close();
                                }
                            }
                        } else {
                            // no logging.
                            proc = builder.start();
                        }

                        // NOTE: most/all executions end in failure during analysis, however,
                        // supported java bugs are still reported
                        proc.waitFor();
                    } catch (final IOException e) {
                        getLog().error(
                                "Exception occurred while trying to perform Infer execution; output not complete"
                                        + "",
                                e);
                    } catch (final InterruptedException e) {
                        getLog().error(EARLY_EXECUTION_TERMINATION_EXCEPTION_MSG, e);
                    } finally {
                        try {
                            // currently they all fail, although java bugs are still reported
                            if (proc != null && proc.exitValue() != 0) {
                                FAILED_CHECKS.put(sourceFile, proc.exitValue());
                            }
                        } catch (final Exception e) {
                            FAILED_CHECKS.put(sourceFile, -1);
                        }
                        doneSignal.countDown();
                    }
                }
            };

            pool.submit(r);
        }
    } finally {
        if (pool != null) {
            pool.shutdown();
        }
    }
    try {
        doneSignal.await();
    } catch (final InterruptedException e) {
        getLog().error(EARLY_EXECUTION_TERMINATION_EXCEPTION_MSG, e);
    }
}

From source file:org.broadinstitute.gatk.utils.runtime.ProcessController.java

/**
 * Executes a command line program with the settings and waits for it to return,
 * processing the output on a background thread.
 *
 * @param settings Settings to be run.//w ww .ja va 2 s.c  o m
 * @return The output of the command.
 */
public ProcessOutput exec(ProcessSettings settings) {
    if (destroyed)
        throw new IllegalStateException("This controller was destroyed");

    ProcessBuilder builder = new ProcessBuilder(settings.getCommand());
    builder.directory(settings.getDirectory());

    Map<String, String> settingsEnvironment = settings.getEnvironment();
    if (settingsEnvironment != null) {
        Map<String, String> builderEnvironment = builder.environment();
        builderEnvironment.clear();
        builderEnvironment.putAll(settingsEnvironment);
    }

    builder.redirectErrorStream(settings.isRedirectErrorStream());

    StreamOutput stdout = null;
    StreamOutput stderr = null;

    // Start the process running.

    try {
        synchronized (toCapture) {
            process = builder.start();
        }
        running.add(this);
    } catch (IOException e) {
        String message = String.format("Unable to start command: %s\nReason: %s",
                StringUtils.join(builder.command(), " "), e.getMessage());
        throw new ReviewedGATKException(message);
    }

    int exitCode;

    try {
        // Notify the background threads to start capturing.
        synchronized (toCapture) {
            toCapture.put(ProcessStream.Stdout, new CapturedStreamOutput(settings.getStdoutSettings(),
                    process.getInputStream(), System.out));
            toCapture.put(ProcessStream.Stderr, new CapturedStreamOutput(settings.getStderrSettings(),
                    process.getErrorStream(), System.err));
            toCapture.notifyAll();
        }

        // Write stdin content
        InputStreamSettings stdinSettings = settings.getStdinSettings();
        Set<StreamLocation> streamLocations = stdinSettings.getStreamLocations();
        if (!streamLocations.isEmpty()) {
            try {
                OutputStream stdinStream = process.getOutputStream();
                for (StreamLocation location : streamLocations) {
                    InputStream inputStream;
                    switch (location) {
                    case Buffer:
                        inputStream = new ByteArrayInputStream(stdinSettings.getInputBuffer());
                        break;
                    case File:
                        try {
                            inputStream = FileUtils.openInputStream(stdinSettings.getInputFile());
                        } catch (IOException e) {
                            throw new UserException.BadInput(e.getMessage());
                        }
                        break;
                    case Standard:
                        inputStream = System.in;
                        break;
                    default:
                        throw new ReviewedGATKException("Unexpected stream location: " + location);
                    }
                    try {
                        IOUtils.copy(inputStream, stdinStream);
                    } finally {
                        if (location != StreamLocation.Standard)
                            IOUtils.closeQuietly(inputStream);
                    }
                }
                stdinStream.flush();
            } catch (IOException e) {
                throw new ReviewedGATKException(
                        "Error writing to stdin on command: " + StringUtils.join(builder.command(), " "), e);
            }
        }

        // Wait for the process to complete.
        try {
            process.getOutputStream().close();
            process.waitFor();
        } catch (IOException e) {
            throw new ReviewedGATKException(
                    "Unable to close stdin on command: " + StringUtils.join(builder.command(), " "), e);
        } catch (InterruptedException e) {
            throw new ReviewedGATKException("Process interrupted", e);
        } finally {
            while (!destroyed && stdout == null || stderr == null) {
                synchronized (fromCapture) {
                    if (fromCapture.containsKey(ProcessStream.Stdout))
                        stdout = fromCapture.remove(ProcessStream.Stdout);
                    if (fromCapture.containsKey(ProcessStream.Stderr))
                        stderr = fromCapture.remove(ProcessStream.Stderr);
                    try {
                        if (stdout == null || stderr == null)
                            fromCapture.wait();
                    } catch (InterruptedException e) {
                        // Log the error, ignore the interrupt and wait patiently
                        // for the OutputCaptures to (via finally) return their
                        // stdout and stderr.
                        logger.error(e);
                    }
                }
            }

            if (destroyed) {
                if (stdout == null)
                    stdout = StreamOutput.EMPTY;
                if (stderr == null)
                    stderr = StreamOutput.EMPTY;
            }
        }
    } finally {
        synchronized (toCapture) {
            exitCode = process.exitValue();
            process = null;
        }
        running.remove(this);
    }

    return new ProcessOutput(exitCode, stdout, stderr);
}

From source file:org.apache.geode.internal.cache.partitioned.PersistentPartitionedRegionTestBase.java

private void execute(File script) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(script.getAbsolutePath());
    pb.redirectErrorStream(true);
    Process process = pb.start();

    InputStream is = process.getInputStream();
    byte[] buffer = new byte[1024];
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;//from w  ww.ja  v a2s . c  o  m
    while ((line = br.readLine()) != null) {
        LogWriterUtils.getLogWriter().fine("OUTPUT:" + line);
        // TODO validate output
    }
    ;

    assertEquals(0, process.waitFor());

}

From source file:maltcms.ui.nb.pipelineRunner.ui.MaltcmsLocalHostExecution.java

@Override
public File call() throws Exception {
    getProgressHandle().setDisplayName("Running Maltcms...");
    getProgressHandle().start();//ww w  .  j a v  a 2s  .  c o m
    outputDir = createOutputDirectory();
    final ProcessBuilder pb = new ProcessBuilder(buildCommandLine());
    String location = NbPreferences.forModule(PipelineRunnerTopComponent.class).get("maltcmsInstallationPath",
            "NA");
    if (location.equals("NA")) {
        throw new IllegalArgumentException("Please set maltcms location under settings!");
    }
    File f = new File(location);
    pb.directory(f);
    Logger.getLogger(MaltcmsLocalHostExecution.class.getName()).log(Level.FINE,
            "Process: {0} workingDirectory: {1}", new Object[] { pb.command(), pb.directory() });
    pb.redirectErrorStream(true);
    InputOutput io = IOProvider.getDefault().getIO("Running Maltcms in " + outputDir.getName(), false);
    //                io.setOutputVisible(true);
    FileObject outDir = FileUtil.toFileObject(outputDir);
    io.select();
    final OutputWriter writer = io.getOut();
    writer.reset();
    try {
        p = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            writer.println(line);
        }
        int ecode = p.waitFor();
        Logger.getLogger(MaltcmsLocalHostExecution.class.getName()).log(Level.WARNING,
                "Maltcms exited with code: {0}", ecode);
        if (ecode == 0) {
            //                File workflow = new File(outputDir, "workflow.xml");
            Collection<File> files = FileUtils.listFiles(outputDir, new String[] { "xml" }, true);
            if (files.isEmpty()) {
                getProgressHandle().finish();
                throw new IOException("Could not locate workflow.xml in " + outputDir);
            } else {
                File resultFile = null;
                for (File file : files) {
                    if (file.getName().equals("workflow.xml")) {
                        if (resultFile != null) {
                            throw new IllegalArgumentException(
                                    "Found more than one workflow.xml files below " + outputDir + "!");
                        }
                        resultFile = file;
                    }
                }
                if (resultFile != null) {
                    Logger.getLogger(MaltcmsLocalHostExecution.class.getName()).log(Level.FINE,
                            "Found result file: {0}", resultFile);
                    final File resFile = resultFile;
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            Project project;
                            try {
                                project = ProjectManager.getDefault()
                                        .findProject(FileUtil.toFileObject(resFile.getParentFile()));
                                if (project != null) {
                                    OpenProjects.getDefault().open(new Project[] { project }, false, true);
                                    TopComponent projWindow = WindowManager.getDefault()
                                            .findTopComponent("projectTabLogical_tc");
                                    projWindow.requestActive();
                                }
                            } catch (IOException | IllegalArgumentException ex) {
                                Exceptions.printStackTrace(ex);
                            }

                        }
                    };
                    SwingUtilities.invokeLater(r);
                    return resultFile;
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        if (getProgressHandle() != null) {
            getProgressHandle().finish();
        }
    }
    return null;
}