Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

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

Prototype

File directory

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

Click Source Link

Usage

From source file:com.cloud.utils.script.Script.java

public String execute(OutputInterpreter interpreter) {
    String[] command = _command.toArray(new String[_command.size()]);

    if (_logger.isDebugEnabled()) {
        _logger.debug("Executing: " + buildCommandLine(command));
    }/* www  . ja  va 2s.  com*/

    try {
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        if (_workDir != null)
            pb.directory(new File(_workDir));

        _process = pb.start();
        if (_process == null) {
            _logger.warn("Unable to execute: " + buildCommandLine(command));
            return "Unable to execute the command: " + command[0];
        }

        BufferedReader ir = new BufferedReader(new InputStreamReader(_process.getInputStream()));

        _thread = Thread.currentThread();
        ScheduledFuture<String> future = null;
        if (_timeout > 0) {
            future = s_executors.schedule(this, _timeout, TimeUnit.MILLISECONDS);
        }

        Task task = null;
        if (interpreter != null && interpreter.drain()) {
            task = new Task(interpreter, ir);
            s_executors.execute(task);
        }

        while (true) {
            try {
                if (_process.waitFor() == 0) {
                    _logger.debug("Execution is successful.");
                    if (interpreter != null) {
                        return interpreter.drain() ? task.getResult() : interpreter.interpret(ir);
                    } else {
                        // null return exitValue apparently
                        return String.valueOf(_process.exitValue());
                    }
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                if (!_isTimeOut) {
                    /*
                     * This is not timeout, we are interrupted by others,
                     * continue
                     */
                    _logger.debug("We are interrupted but it's not a timeout, just continue");
                    continue;
                }

                TimedOutLogger log = new TimedOutLogger(_process);
                Task timedoutTask = new Task(log, ir);

                timedoutTask.run();
                if (!_passwordCommand) {
                    _logger.warn("Timed out: " + buildCommandLine(command) + ".  Output is: "
                            + timedoutTask.getResult());
                } else {
                    _logger.warn("Timed out: " + buildCommandLine(command));
                }

                return ERR_TIMEOUT;
            } finally {
                if (future != null) {
                    future.cancel(false);
                }
                Thread.interrupted();
            }
        }

        _logger.debug("Exit value is " + _process.exitValue());

        BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128);

        String error;
        if (interpreter != null) {
            error = interpreter.processError(reader);
        } else {
            error = String.valueOf(_process.exitValue());
        }

        if (_logger.isDebugEnabled()) {
            _logger.debug(error);
        }
        return error;
    } catch (SecurityException ex) {
        _logger.warn("Security Exception....not running as root?", ex);
        return stackTraceAsString(ex);
    } catch (Exception ex) {
        _logger.warn("Exception: " + buildCommandLine(command), ex);
        return stackTraceAsString(ex);
    } finally {
        if (_process != null) {
            IOUtils.closeQuietly(_process.getErrorStream());
            IOUtils.closeQuietly(_process.getOutputStream());
            IOUtils.closeQuietly(_process.getInputStream());
            _process.destroy();
        }
    }
}

From source file:hydrograph.ui.graph.utility.JobScpAndProcessUtility.java

/**
 * /*from w  w  w  .j  a va  2 s  . co m*/
 * Create process builder as per operating system.
 * @param project
 * @param gradleCommand
 * @return process builder
 */
public ProcessBuilder getProcess(IProject project, String gradleCommand) {
    String[] runCommand = new String[3];
    if (OSValidator.isWindows()) {
        String[] command = { Messages.CMD, "/c", gradleCommand };
        runCommand = command;

    } else if (OSValidator.isMac()) {
        String[] command = { Messages.SHELL, "-c", gradleCommand };
        runCommand = command;
    }

    ProcessBuilder processBuilder = new ProcessBuilder(runCommand);
    processBuilder.directory(new File(project.getLocation().toOSString()));
    processBuilder.redirectErrorStream(true);
    return processBuilder;

}

From source file:edu.stanford.epad.epadws.processing.pipeline.task.DicomHeadersTask.java

@Override
public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Let interactive thread run sooner
    FileWriter tagFileWriter = null;
    InputStream is = null;/* w  ww  . j  a  va 2s .  c o m*/
    InputStreamReader isr = null;
    BufferedReader br = null;
    Process process = null;

    try {
        String[] command = { "./dcm2txt", "-w", "250", "-l", "250", dicomInputFile.getAbsolutePath() };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomBinDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomBinDir, "dcm2txt");
        if (!script.exists())
            dicomBinDir = EPADConfig.getEPADWebServerDICOMBinDir();
        script = new File(dicomBinDir, "dcm2txt");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);

        processBuilder.directory(new File(dicomBinDir));
        process = processBuilder.start();
        process.getOutputStream();

        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        StringBuilder log = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.append("./dcm2txt: " + line).append("\n");
        }

        try {
            process.waitFor();
        } catch (InterruptedException e) {
            logger.info(log.toString());
            logger.warning("Couldn't get tags for series " + seriesUID + "; dicom="
                    + dicomInputFile.getAbsolutePath() + " tagFile:" + outputFile.getAbsolutePath(), e);
        }

        EPADFileUtils.createDirsAndFile(outputFile);
        File tagFile = outputFile;
        tagFileWriter = new FileWriter(tagFile);
        tagFileWriter.write(sb.toString());
    } catch (Exception e) {
        logger.warning("DicomHeadersTask failed to create DICOM tags for series " + seriesUID + " dicom FIle:"
                + dicomInputFile.getAbsolutePath() + " : " + outputFile.getAbsolutePath(), e);
    } catch (OutOfMemoryError oome) {
        logger.warning("DicomHeadersTask for series " + seriesUID + " out of memory: ", oome);
    } finally {
        IOUtils.closeQuietly(tagFileWriter);
        IOUtils.closeQuietly(br);

        if (process != null)
            process.destroy();
    }
}

From source file:tachyon.java.manager.JavaFxManager.java

private void buildFat(ProcessItem pro) {
    if (!pro.isCancelled()) {
        ProcessBuilder pb;
        if (OS.contains("win")) {
            pb = getWindowsFatJarString();
        } else {/*  w ww  .j ava 2s  . c o  m*/
            pb = getMacFatJarString();
        }
        pb.directory(getProject().getRootDirectory().toFile());
        try {
            Process start = pb.start();
            pro.setName("Combining All Existing Jars for Project " + getProject().getProjectName());
            pro.setProcess(start);
            ProcessPool.getPool().addItem(pro);
            (new Thread(new Project.OutputReader(start.getInputStream(), pro.getConsole()))).start();
            (new Thread(new Project.ErrorReader(start.getErrorStream(), pro.getConsole()))).start();
            int waitFor = start.waitFor();
            System.out.println(waitFor);
        } catch (IOException | InterruptedException e) {
        }
    }
}

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

@Override
public File call() throws Exception {
    getProgressHandle().setDisplayName("Running Maltcms...");
    getProgressHandle().start();/*from  w  w  w  .j a v  a2s . c om*/
    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;
}

From source file:tachyon.java.manager.JavaFxManager.java

@Override
public void build(ProcessItem pro) {
    compile(pro);//from w w  w.j ava 2 s.  c  o m
    if (!pro.isCancelled()) {
        ProcessBuilder pb;
        if (OS.contains("win")) {
            pb = getWindowsBuildString();
        } else {
            pb = getMacBuildString();
        }
        pb.directory(getProject().getRootDirectory().toFile());

        try {
            Process start = pb.start();
            pro.setName("Build Jar File for Project " + getProject().getProjectName());
            pro.setProcess(start);
            ProcessPool.getPool().addItem(pro);
            (new Thread(new Project.OutputReader(start.getInputStream(), pro.getConsole()))).start();
            (new Thread(new Project.ErrorReader(start.getErrorStream(), pro.getConsole()))).start();
            int waitFor = start.waitFor();
            System.out.println(waitFor);
        } catch (IOException | InterruptedException e) {
        }
    }
}

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);
    }// w  w  w  .j a  v  a  2s  .co  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:tachyon.java.manager.JavaFxManager.java

@Override
public void debugProject(ProcessItem pro, DebuggerController controller) {
    compile(pro);//from   w  w  w .ja  v a 2  s. c om
    if (!pro.isCancelled()) {
        ProcessBuilder pb;
        if (OS.contains("win")) {
            pb = getWindowsDebuggerString();
        } else {
            pb = getMacDebuggerString();
        }
        pb.directory(getProject().getBuild().toFile());
        try {
            Process start = pb.start();
            pro.setName("Debug Project " + getProject().getRootDirectory().getFileName().toString());
            pro.setProcess(start);
            ProcessPool.getPool().addItem(pro);
            (new Thread(new Project.OutputReader(start.getInputStream(), pro.getConsole()))).start();
            (new Thread(new Project.ErrorReader(start.getErrorStream(), pro.getConsole()))).start();
            controller.setOutputStream(start.getOutputStream());
            int waitFor = start.waitFor();
            controller.finished();
        } catch (IOException | InterruptedException ex) {
        }
    }
}

From source file:com.ikanow.infinit.e.application.handlers.polls.LogstashTestRequestPollHandler.java

@Override
public void performPoll() {

    if (null == LOGSTASH_DIRECTORY) { // (static memory not yet initialized)
        try {//from   ww w.j  av a 2  s. co m
            Thread.sleep(1000); // (extend the sleep time a bit)
        } catch (Exception e) {
        }
        return;
    }

    // 1] Check - does logstash exist on this server:

    File logstashBinary = new File(LOGSTASH_BINARY);
    if (!logstashBinary.canExecute()) {
        try {
            Thread.sleep(10000); // (extend the sleep time a bit)
        } catch (Exception e) {
        }
        return;
    }

    // 2] (Unlike harvester, _don't_ grab an application token, you can run this on as many servers as you want)

    // 3] Setup

    if (null == _logHarvesterQ) {
        _logHarvesterQ = new MongoQueue(DbManager.getIngest().getLogHarvesterQ().getDB().getName(),
                DbManager.getIngest().getLogHarvesterQ().getName());
    }
    if (null == _testOutputTemplate) {
        try {
            File testOutputTemplate = new File(LOGSTASH_TEST_OUTPUT_TEMPLATE);
            InputStream inStream = null;
            try {
                inStream = new FileInputStream(testOutputTemplate);
                _testOutputTemplate = IOUtils.toString(inStream);
            } catch (Exception e) {// abandon ship!
                return;
            } finally {
                inStream.close();
            }
        } catch (Exception e) {// abandon ship!

            //DEBUG
            //e.printStackTrace();

            return;
        }
    } //TESTED

    // 4] Check if any new requests have been made:

    BasicDBObject queueQuery = new BasicDBObject("logstash", new BasicDBObject(DbManager.exists_, true));
    DBObject nextElement = _logHarvesterQ.pop(queueQuery);
    while (nextElement != null) {
        //DEBUG
        //System.out.println("FOUND: " + nextElement.toString());

        TestLogstashExtractorPojo testInfo = TestLogstashExtractorPojo.fromDb(nextElement,
                TestLogstashExtractorPojo.class);
        if ((null == testInfo.maxDocs) || (null == testInfo.logstash.config) || (null == testInfo.isAdmin)
                || (null == testInfo.sourceKey)) {
            TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo();
            testErr._id = testInfo._id;
            testErr.error = "Internal Logic Error. Missing one of: maxDocs, isAdmin, sourceKey, logstash.config";
            _logHarvesterQ.push(testErr.toDb());

            return;
        } //TESTED

        // Validate/tranform the configuration:
        StringBuffer errMessage = new StringBuffer();
        String logstashConfig = LogstashConfigUtils.validateLogstashInput(testInfo.sourceKey,
                testInfo.logstash.config, errMessage, testInfo.isAdmin);
        if (null == logstashConfig) { // Validation error...
            TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo();
            testErr._id = testInfo._id;
            testErr.error = "Validation error: " + errMessage.toString();
            _logHarvesterQ.push(testErr.toDb());

            return;
        } //TESTED

        // Replacement for #LOGSTASH{host} - currently only replacement supported (+ #IKANOW{} in main code)
        try {
            logstashConfig = logstashConfig.replace("#LOGSTASH{host}",
                    java.net.InetAddress.getLocalHost().getHostName());
        } catch (Exception e) {
            logstashConfig = logstashConfig.replace("#LOGSTASH{host}", "localhost.localdomain");
        }
        //TESTED

        String outputConf = _testOutputTemplate.replace("_XXX_COLLECTION_XXX_", testInfo._id.toString()); //TESTED
        String sinceDbPath = LOGSTASH_WD + ".sincedb_" + testInfo._id.toString();
        String conf = logstashConfig.replace("_XXX_DOTSINCEDB_XXX_", sinceDbPath)
                + outputConf.replace("_XXX_SOURCEKEY_XXX_", testInfo.sourceKey);

        boolean allWorked = false;
        Process logstashProcess = null;
        try {
            // 1] Create the process

            ArrayList<String> args = new ArrayList<String>(4);
            args.addAll(Arrays.asList(LOGSTASH_BINARY, "-e", conf));
            if (0 == testInfo.maxDocs) {
                args.add("-t"); // test mode, must faster
            } //TESTED

            if ((null != testInfo.logstash.testDebugOutput) && testInfo.logstash.testDebugOutput) {
                args.add("--debug");
            } else {
                args.add("--verbose");
            }
            ProcessBuilder logstashProcessBuilder = new ProcessBuilder(args);
            logstashProcessBuilder = logstashProcessBuilder.directory(new File(LOGSTASH_WD))
                    .redirectErrorStream(true);
            logstashProcessBuilder.environment().put("JAVA_OPTS", "");

            //DEBUG
            //System.out.println("STARTING: " + ArrayUtils.toString(logstashProcessBuilder.command().toArray()));

            // 2] Kick off the process
            logstashProcess = logstashProcessBuilder.start();
            StringWriter outputAndError = new StringWriter();
            OutputCollector outAndErrorStream = new OutputCollector(logstashProcess.getInputStream(),
                    new PrintWriter(outputAndError));
            outAndErrorStream.start();
            final int toWait_s = 240;

            boolean exited = false;

            // 3] Check the output collection for records

            int errorVal = 0;
            long priorCount = 0L;
            int priorLogCount = 0;

            int timeOfLastLoggingChange = 0;
            int timeOfLastDocCountChange = 0;

            String reasonForExit = "";

            int inactivityTimeout_s = 10; // (default)
            if (null != testInfo.logstash.testInactivityTimeout_secs) {
                inactivityTimeout_s = testInfo.logstash.testInactivityTimeout_secs;
            }
            for (int i = 0; i < toWait_s; i += 5) {
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                }

                long count = DbManager.getCollection("ingest", testInfo._id.toString()).count();

                // 3.1] Do we have all the records (or is the number staying static)

                //DEBUG
                //System.out.println("FOUND: " + count + " VS " + priorCount + " , " + priorPriorCount);

                // 3.1a] All done?

                if ((count >= testInfo.maxDocs) && (count > 0)) {
                    allWorked = true;
                    break;
                } //TESTED               

                // 3.1b] If not, has anything changes?

                if (priorCount != count) {
                    timeOfLastDocCountChange = i;
                }
                if (priorLogCount != outAndErrorStream.getLines()) {
                    timeOfLastLoggingChange = i;
                }

                // 3.1c] Check for inactivity 

                if ((timeOfLastDocCountChange > 0) && (i - timeOfLastDocCountChange) >= inactivityTimeout_s) {
                    // Delay between events: treat as success
                    allWorked = true;
                    break;
                } //TESTED

                if ((0 == count) && outAndErrorStream.getPipelineStarted() && ((timeOfLastLoggingChange > 0)
                        && (i - timeOfLastLoggingChange) >= inactivityTimeout_s)) {
                    // Delay between log messages after pipeline started, no documents, treat as failure

                    //DEBUG
                    //System.out.println("LOG LINES! " + i + " NUM = " + outAndErrorStream.getLines());

                    errorVal = 1;
                    reasonForExit = "No records received and logging inactive.\n";
                    break;
                } //TESTED               

                // 3.2] Has the process exited unexpectedly?

                try {
                    errorVal = logstashProcess.exitValue();
                    reasonForExit = "Logstash process exited with error: " + errorVal + ".\n";
                    exited = true;

                    //DEBUG
                    //System.out.println("GOT EXIT VALUE: " + errorVal);
                    break;

                } //TESTED
                catch (Exception e) {
                } // that's OK we're just still going is all...

                priorCount = count;
                priorLogCount = outAndErrorStream.getLines();

            } //(end loop while waiting for job to complete)            

            // 4] If the process is still running then kill it

            if (!exited) {
                //DEBUG
                //System.out.println("EXITED WITHOUT FINISHING");

                logstashProcess.destroy();
            } //TESTED

            // 5] Things to do when the job is done: (worked or not)
            //    Send a message to the harvester

            outAndErrorStream.join(); // (if we're here then must have closed the process, wait for it to die)

            TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo();
            testErr._id = testInfo._id;
            if ((testInfo.maxDocs > 0) || (0 != errorVal)) {
                testErr.error = reasonForExit + outputAndError.toString();
                // (note this is capped at well below the BSON limit in the thread below)
            } else { // maxDocs==0 (ie pre-publish test) AND no error returned
                testErr.error = null;
            }
            _logHarvesterQ.push(testErr.toDb());
            //TESTED            
        } catch (Exception e) {
            //DEBUG
            //e.printStackTrace();            

            TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo();
            testErr._id = testInfo._id;
            testErr.error = "Internal Logic Error: " + e.getMessage();
            _logHarvesterQ.push(testErr.toDb());

        } //TOTEST
        finally {
            // If we created a sincedb path then remove it:
            try {
                new File(sinceDbPath).delete();
            } catch (Exception e) {
            } // (don't care if it fails)

            if (!allWorked) { // (otherwise up to the harvester to remove these)
                try {
                    DbManager.getCollection("ingest", testInfo._id.toString()).drop();
                } catch (Exception e) {
                } // doesn't matter if this errors
            }
            try {
                // Really really want to make sure the process isn't running
                if (null != logstashProcess) {
                    logstashProcess.destroy();
                }
            } catch (Exception e) {
            } catch (Error ee) {
            }
        } //TESTED

        // (If we actually processed an element, then try again immediate)
        nextElement = _logHarvesterQ.pop(queueQuery);
    }
}

From source file:tachyon.java.manager.JavaFxManager.java

@Override
public void nativeExecutable(ProcessItem pro) {
    build(pro);/* ww  w.jav  a  2s .c o m*/
    if (!pro.isCancelled()) {
        ProcessBuilder pb;
        if (OS.contains("win")) {
            pb = getWindowsExecutableString();
        } else {
            pb = getMacExecutableString();
        }
        pb.directory(getProject().getDist().toFile());
        try {
            Process start = pb.start();
            pro.setName(
                    "Compile Native for Project " + getProject().getRootDirectory().getFileName().toString());
            pro.setProcess(start);
            ProcessPool.getPool().addItem(pro);
            (new Thread(new Project.OutputReader(start.getInputStream(), pro.getConsole()))).start();
            (new Thread(new Project.ErrorReader(start.getErrorStream(), pro.getConsole()))).start();
            int waitFor = start.waitFor();
        } catch (IOException | InterruptedException ex) {
        }
    }
}