Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

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

Click Source Link

Usage

From source file:ca.weblite.jdeploy.JDeploy.java

private void init_old(String commandName) throws IOException {
    try {/*  w  w w.j a va  2s.  co m*/
        File packageJson = new File(directory, "package.json");
        if (!packageJson.exists()) {
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(npm, "init");
            pb.inheritIO();
            final Process p = pb.start();
            Timer t = new Timer();

            TimerTask tt = new TimerTask() {

                @Override
                public void run() {
                    if (packageJson.exists()) {
                        p.destroy();
                        cancel();
                    }
                }

            };
            t.schedule(tt, new Date(System.currentTimeMillis() + 1000), 1000);

            int code = p.waitFor();

            if (!packageJson.exists() && code != 0) {
                System.err.println("Stopped init because npm init failed");
                System.exit(code);
            }
        }

        String pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8");
        if (!pkgJsonStr.contains("shelljs")) {
            System.out.println("Installing shelljs");
            ProcessBuilder pb = new ProcessBuilder();
            pb.inheritIO();
            pb.command(npm, "install", "shelljs", "--save");
            Process p = pb.start();
            int result = p.waitFor();
            if (result != 0) {
                System.err.println("Failed to install shelljs");
                System.exit(result);
            }
        }

        // For some reason it never sticks in the package.json file the first time
        pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8");
        if (!pkgJsonStr.contains("shelljs")) {
            System.out.println("Installing shelljs");
            ProcessBuilder pb = new ProcessBuilder();
            pb.inheritIO();
            pb.command(npm, "install", "shelljs", "--save");
            Process p = pb.start();
            int result = p.waitFor();
            if (result != 0) {
                System.err.println("Failed to install shelljs");
                System.exit(result);
            }
        }

        JSONParser parser = new JSONParser();
        Map contents = parser.parseJSON(new StringReader(pkgJsonStr));
        if (commandName == null) {
            commandName = (String) contents.get("name");
        }

        if (!contents.containsKey("bin")) {
            contents.put("bin", new HashMap());
        }
        Map bins = (Map) contents.get("bin");

        if (!bins.values().contains(getBinDir() + "/jdeploy.js")) {
            contents.put("preferGlobal", true);
            bins.put(commandName, getBinDir() + "/jdeploy.js");
            Result res = Result.fromContent(contents);
            FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8");
        }

        if (!contents.containsKey("files")) {
            contents.put("files", new ArrayList());
        }
        List files = (List) contents.get("files");
        if (!files.contains(getBinDir())) {
            files.add(getBinDir());
            Result res = Result.fromContent(contents);
            FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8");
        }

    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:annis.visualizers.component.AbstractDotVisualizer.java

public void writeOutput(VisualizerInput input, OutputStream outstream) {

    StringBuilder dot = new StringBuilder();

    try {/*from   w  w w  .j a  v  a 2  s  . co m*/
        File tmpInput = File.createTempFile("annis-dot-input", ".dot");
        tmpInput.deleteOnExit();

        // write out input file
        StringBuilder dotContent = new StringBuilder();
        createDotContent(input, dotContent);
        FileUtils.writeStringToFile(tmpInput, dotContent.toString());

        // execute dot
        String dotPath = input.getMappings().getProperty("dotpath", "dot");
        ProcessBuilder pBuilder = new ProcessBuilder(dotPath, "-Tpng", tmpInput.getCanonicalPath());

        pBuilder.redirectErrorStream(false);
        Process process = pBuilder.start();

        InputStream inputFromProcess = process.getInputStream();
        for (int chr = inputFromProcess.read(); chr != -1; chr = inputFromProcess.read()) {
            outstream.write(chr);
        }

        inputFromProcess.close();

        int resultCode = process.waitFor();

        if (resultCode != 0) {
            InputStream stderr = process.getErrorStream();
            StringBuilder errorMessage = new StringBuilder();

            for (int chr = stderr.read(); chr != -1; chr = stderr.read()) {
                errorMessage.append((char) chr);
            }
            if (!"".equals(errorMessage.toString())) {
                log.error(
                        "Could not execute dot graph-layouter.\ncommand line:\n{}\n\nstderr:\n{}\n\nstdin:\n{}",
                        new Object[] { StringUtils.join(pBuilder.command(), " "), errorMessage.toString(),
                                dot.toString() });
            }
        }

        // cleanup
        if (!tmpInput.delete()) {
            log.warn("Cannot delete " + tmpInput.getAbsolutePath());
        }

    } catch (Exception ex) {
        log.error(null, ex);
    }
}

From source file:org.opencb.cellbase.app.transform.VariationParser.java

private void sortFileByNumericColumn(Path inputFile, Path outputFile, int columnIndex)
        throws InterruptedException, IOException {
    this.logger.info("Sorting file " + inputFile + " into " + outputFile + " ...");

    // increment column index by 1, beacause Java indexes are 0-based and 'sort' command uses 1-based indexes
    columnIndex++;/* w  w  w .j  a  v a  2 s  . c om*/
    ProcessBuilder pb = new ProcessBuilder("sort", "-t", "\t", "-k", Integer.toString(columnIndex), "-n",
            "--stable", inputFile.toAbsolutePath().toString(), "-T", variationDirectoryPath.toString(), "-o",
            outputFile.toAbsolutePath().toString()); // System.getProperty("java.io.tmpdir")
    this.logger.debug("Executing '" + StringUtils.join(pb.command(), " ") + "' ...");
    Stopwatch stopwatch = Stopwatch.createStarted();
    Process process = pb.start();
    process.waitFor();

    int returnedValue = process.exitValue();
    if (returnedValue != 0) {
        String errorMessage = IOUtils.toString(process.getErrorStream());
        logger.error("Error sorting " + inputFile);
        logger.error(errorMessage);
        throw new RuntimeException("Error sorting " + inputFile);
    }
    this.logger.info("Sorted");
    this.logger.debug("Elapsed time sorting file: " + stopwatch);
}

From source file:org.roqmessaging.management.HostConfigManager.java

/**
 * Start a new exchange process//from  ww w  . j a  va 2s .  c  o  m
 * <p>
 * 1. Check the number of local xChange present in the host 2. Start a new
 * xChange with port config + nchange
 * 
 * @param qName
 *            the name of the queue to create
 * @return true if the creation process worked well
 */
private boolean startNewExchangeProcess(String qName, String monitorAddress, String monitorStatAddress) {
    if (monitorAddress == null || monitorStatAddress == null) {
        logger.error("The monitor or the monitor stat server is null", new IllegalStateException());
        return false;
    }
    // 1. Get the number of installed queues on this host
    int number = 0;
    for (String q_i : this.qExchangeMap.keySet()) {
        List<String> xChanges = this.qExchangeMap.get(q_i);
        number += xChanges.size();
    }
    // 2. Assigns a front port and a back port
    logger.debug(" This host contains already " + number + " Exchanges");
    //x4 = Front, back, Shutdown, prod request
    int frontPort = this.properties.getExchangeFrontEndPort() + number * 4;
    // 3 because there is the front, back and the shut down
    int backPort = frontPort + 1;
    String ip = RoQUtils.getInstance().getLocalIP();

    int logPort = frontPort + 10000;
    seeds = seeds + ip + ":" + logPort + "#";
    globalConfigSocket.send(new Integer(RoQConstant.GET_SEEDS).toString() + ", asks for seeds");
    seeds = seeds + new String(globalConfigSocket.recv());
    //System.out.print(seeds+" "+useLog);

    if (this.properties.isExchangeInHcmVm()) {
        // We must start the thread in the same process
        Exchange exchange = new Exchange(frontPort, backPort, monitorAddress, monitorStatAddress,
                ip + ":" + logPort, seeds, propertyFile);
        // Launch the thread
        new Thread(exchange).start();
    } else {
        // We start the exchange in its own process
        // Launch script
        try {
            ProcessBuilder pb = new ProcessBuilder("java",
                    "-Djava.library.path=" + System.getProperty("java.library.path"), "-cp",
                    System.getProperty("java.class.path"), "-Xmx" + this.properties.getExchangeHeap() + "m",
                    "-XX:+UseConcMarkSweepGC", ExchangeLauncher.class.getCanonicalName(),
                    new Integer(frontPort).toString(), new Integer(backPort).toString(), monitorAddress,
                    monitorStatAddress, ip + ":" + logPort, seeds, propertyFile);
            logger.info("Starting: " + pb.command());
            final Process process = pb.start();
            pipe(process.getErrorStream(), System.err);
            pipe(process.getInputStream(), System.out);
            globalConfigSocket.send(new Integer(RoQConstant.ADD_SEED).toString() + "," + ip + ":" + logPort);
            globalConfigSocket.recv();
        } catch (IOException e) {
            logger.error("Error while executing script", e);
            return false;
        }
    }

    if (this.qExchangeMap.containsKey(qName)) {
        this.qExchangeMap.get(qName).add("tcp://" + ip + ":" + frontPort);
        logger.debug("Storing Xchange info: " + "tcp://" + ip + ":" + frontPort);
    } else {
        List<String> xChange = new ArrayList<String>();
        xChange.add("tcp://" + ip + ":" + frontPort);
        this.qExchangeMap.put(qName, xChange);
        logger.debug("Storing Xchange info: " + "tcp://" + ip + ":" + frontPort);
    }

    return true;
}

From source file:eu.udig.omsbox.core.OmsScriptExecutor.java

/**
 * Execute an OMS script.//w w  w  .  j  a  va 2s .  c o  m
 * 
 * @param script the script file or the script string.
 * @param internalStream
 * @param errorStream
 * @param loggerLevelGui the log level as presented in the GUI, can be OFF|ON. This is not the OMS logger level, which 
 *                              in stead has to be picked from the {@link OmsBoxConstants#LOGLEVELS_MAP}.
 * @param ramLevel the heap size to use in megabytes.
 * @return the process.
 * @throws Exception
 */
public Process exec(String script, final PrintStream internalStream, final PrintStream errorStream,
        String loggerLevelGui, String ramLevel) throws Exception {
    if (loggerLevelGui == null)
        loggerLevelGui = OmsBoxConstants.LOGLEVEL_GUI_OFF;

    File scriptFile = new File(script);
    if (!scriptFile.exists()) {
        // if the file doesn't exist, it is a script, let's put it into a file
        scriptFile = File.createTempFile("omsbox_script_", ".oms");
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(scriptFile));
            bw.write(script);
        } finally {
            bw.close();
        }

    } else {
        // it is a script in a file, read it to log it
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            br = new BufferedReader(new FileReader(scriptFile));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            br.close();
        }
        script = sb.toString();
    }

    // tmp folder
    String tempdir = System.getProperty("java.io.tmpdir");
    File omsTmp = new File(tempdir + File.separator + "oms");
    if (!omsTmp.exists())
        omsTmp.mkdirs();

    List<String> arguments = new ArrayList<String>();
    arguments.add(javaFile);

    // ram usage
    String ramExpr = "-Xmx" + ramLevel + "m";
    arguments.add(ramExpr);

    // modules jars
    List<String> modulesJars = OmsModulesManager.getInstance().getModulesJars();
    StringBuilder sb = new StringBuilder();
    for (String moduleJar : modulesJars) {
        sb.append(File.pathSeparator).append(moduleJar);
    }
    String modulesJarsString = sb.toString().replaceFirst(File.pathSeparator, "");
    String resourcesFlag = "-Doms.sim.resources=\"" + modulesJarsString + "\"";
    arguments.add(resourcesFlag);

    // grass gisbase
    String grassGisbase = OmsBoxPlugin.getDefault().getGisbasePreference();
    if (grassGisbase != null && grassGisbase.length() > 0) {
        arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_GISBASE_KEY + "=" + grassGisbase);
    }
    String grassShell = OmsBoxPlugin.getDefault().getShellPreference();
    if (grassShell != null && grassShell.length() > 0) {
        arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_SHELL_KEY + "=" + grassShell);
    }

    // all the arguments
    arguments.add("-cp");
    arguments.add(classPath);
    arguments.add(CLI.class.getCanonicalName());
    arguments.add("-r ");
    arguments.add("\"" + scriptFile.getAbsolutePath() + "\"");

    String homeDir = System.getProperty("java.io.tmpdir");
    File homeFile = new File(homeDir);
    StringBuilder runSb = new StringBuilder();
    for (String arg : arguments) {
        runSb.append(arg).append(" ");
    }

    String[] args;
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        File tmpRunFile = new File(homeFile, "udig_spatialtoolbox.bat");
        FileUtils.writeStringToFile(tmpRunFile, "@echo off\n" + runSb.toString());
        args = new String[] { "cmd", "/c", tmpRunFile.getAbsolutePath() };
    } else {
        File tmpRunFile = new File(homeFile, "udig_spatialtoolbox.sh");
        FileUtils.writeStringToFile(tmpRunFile, runSb.toString());
        args = new String[] { "sh", tmpRunFile.getAbsolutePath() };
    }

    // {javaFile, ramExpr, resourcesFlag, "-cp", classPath,
    // CLI.class.getCanonicalName(), "-r",
    // scriptFile.getAbsolutePath()};

    ProcessBuilder processBuilder = new ProcessBuilder(args);
    // work in home
    // processBuilder.directory(homeFile);

    // environment
    Map<String, String> environment = processBuilder.environment();
    // environment.put("CLASSPATH", classPath);

    final Process process = processBuilder.start();
    internalStream.println(
            "Process started: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
    internalStream.println("");

    // command launched
    if (loggerLevelGui.equals(OmsBoxConstants.LOGLEVEL_GUI_ON)) {
        internalStream.println("------------------------------>8----------------------------");
        internalStream.println("Launching command: ");
        internalStream.println("------------------");
        List<String> command = processBuilder.command();
        for (String arg : command) {
            internalStream.print(arg);
            internalStream.print(" ");
        }
        internalStream.println("\n");
        internalStream.println("(you can run the above from command line, customizing the content)");
        internalStream.println("----------------------------------->8---------------------------------");
        internalStream.println("");
        // script run
        internalStream.println("Script run: ");
        internalStream.println("-----------");
        internalStream.println(script);
        internalStream.println("");
        internalStream.println("------------------------------>8----------------------------");
        internalStream.println("");
        // environment used
        internalStream.println("Environment used: ");
        internalStream.println("-----------------");

        Set<Entry<String, String>> entrySet = environment.entrySet();
        for (Entry<String, String> entry : entrySet) {
            internalStream.print(entry.getKey());
            internalStream.print(" =\t");
            internalStream.println(entry.getValue());
        }
        internalStream.println("------------------------------>8----------------------------");
        internalStream.println("");
    }
    internalStream.println("");
    isRunning = true;

    new Thread() {
        public void run() {
            BufferedReader br = null;
            try {
                InputStream is = process.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    internalStream.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
                errorStream.println(e.getLocalizedMessage());
            } finally {
                if (br != null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                isRunning = false;
                updateListeners();
            }
            internalStream.println("");
            internalStream.println("");
            internalStream.println("Process finished: "
                    + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
        };
    }.start();

    new Thread() {
        public void run() {
            BufferedReader br = null;
            try {
                InputStream is = process.getErrorStream();
                InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    /*
                     * remove of ugly recurring geotools warnings. Not nice, but 
                     * at least users do not get confused. 
                     */
                    if (ConsoleMessageFilter.doRemove(line)) {
                        continue;
                    }
                    errorStream.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
                errorStream.println(e.getLocalizedMessage());
            } finally {
                if (br != null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        };
    }.start();

    return process;
}

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./*from ww  w.java2 s  .co 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: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./*from ww w  .j  av  a 2 s  .  c  om*/
 * @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.nifi.bootstrap.RunNiFi.java

private boolean isProcessRunning(final String pid, final Logger logger) {
    try {//from  w  w  w.j av a 2s  .  c om
        // We use the "ps" command to check if the process is still running.
        final ProcessBuilder builder = new ProcessBuilder();

        builder.command("ps", "-p", pid);
        final Process proc = builder.start();

        // Look for the pid in the output of the 'ps' command.
        boolean running = false;
        String line;
        try (final InputStream in = proc.getInputStream();
                final Reader streamReader = new InputStreamReader(in);
                final BufferedReader reader = new BufferedReader(streamReader)) {

            while ((line = reader.readLine()) != null) {
                if (line.trim().startsWith(pid)) {
                    running = true;
                }
            }
        }

        // If output of the ps command had our PID, the process is running.
        if (running) {
            logger.debug("Process with PID {} is running", pid);
        } else {
            logger.debug("Process with PID {} is not running", pid);
        }

        return running;
    } catch (final IOException ioe) {
        System.err.println("Failed to determine if Process " + pid + " is running; assuming that it is not");
        return false;
    }
}

From source file:it.drwolf.ridire.session.CrawlerManager.java

@Restrict("#{s:hasRole('Admin')}")
public String startCrawlerEngine() throws HeritrixNotStartingException {
    String launchCommand = this.getHeritrixBinPath() + CrawlerManager.FILE_SEPARATOR + this.entityManager
            .find(CommandParameter.class, CommandParameter.HERITRIX_LAUNCH_KEY).getCommandValue();
    // + " -a "//from   ww  w.j av  a  2s  . com
    // + this.entityManager.find(CrawlerCommand.class,
    // CrawlerCommand.HERITRIX_ADMINPW_KEY).getCommandValue();
    ProcessBuilder pb = new ProcessBuilder();
    pb.directory(new File(this.getHeritrixBinPath()));
    pb.command(launchCommand, "-a",
            "admin:" + this.entityManager.find(CommandParameter.class, CommandParameter.HERITRIX_ADMINPW_KEY)
                    .getCommandValue(),
            "-p", this.entityManager.find(Parameter.class, Parameter.ENGINE_PORT.getKey()).getValue());
    try {
        pb.start();
        // try CONN_ATTEMPTS times to get connection to heritrix
        for (int i = 0; i < CrawlerManager.CONN_ATTEMPTS; i++) {
            Thread.sleep(10000);
            if (this.getCrawlerEngineStatus().equals(CrawlerManager.RUNNING)) {
                break;
            }
        }
    } catch (IOException e) {
        throw new HeritrixNotStartingException();
    } catch (InterruptedException e) {
        throw new HeritrixNotStartingException();
    }
    return "OK";
}