Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

In this page you can find the example usage for java.lang Process waitFor.

Prototype

public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException 

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated, or the specified waiting time elapses.

Usage

From source file:org.eclipse.swt.snippets.SnippetExplorer.java

/**
 * Test if the given command can be executed.
 *
 * @param command command to test// w w w  . j  av a  2s  . c o  m
 * @return <code>false</code> if executing the command failed for any reason
 */
private static boolean canRunCommand(String command) {
    try {
        final Process p = Runtime.getRuntime().exec(command);
        p.waitFor(150, TimeUnit.MILLISECONDS);
        if (p.isAlive()) {
            p.destroy();
            p.waitFor(100, TimeUnit.MILLISECONDS);
            if (p.isAlive()) {
                p.destroyForcibly();
            }
        }
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:de.jcup.egradle.core.process.SimpleProcessExecutor.java

void waitFor(Process p) throws InterruptedException {
    p.waitFor(3, TimeUnit.SECONDS);
}

From source file:com.hi.datacleaner.ExternalCommandTransformer.java

private String[] getResult(List<String> commandTokens) throws IOException, InterruptedException {
    Process process = new ProcessBuilder(commandTokens).start();

    if (!process.waitFor(_timeout, TimeUnit.MILLISECONDS)) {
        process.destroy();/*from   w  w  w .j a va  2s  . c  om*/
        throw new InterruptedException(
                "Process has been interrupted because of timeout (" + _timeout + "ms). ");
    }

    BufferedReader stdin = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    StringBuilder result = new StringBuilder();
    String line;
    int linesCount = 0;

    while ((line = stdin.readLine()) != null) {
        linesCount++;
        result.append(line).append(_separator);
    }

    if (linesCount == 0) {
        result.append(ERROR);

        while ((line = stderr.readLine()) != null) {
            result.append(line).append(_separator);
        }
    }

    return new String[] { result.toString() };
}

From source file:de.uni_freiburg.informatik.ultimate.licence_manager.authors.SvnAuthorProvider.java

private boolean isUnderVersionControl(String absolutePath) {
    final ProcessBuilder pbuilder = new ProcessBuilder("svn", "info", absolutePath);
    try {/*from   w  w w  .j  a va2  s.co  m*/
        final Process process = pbuilder.start();
        if (process.waitFor(1000, TimeUnit.MILLISECONDS)) {
            final List<String> lines = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
            if (lines == null || lines.isEmpty()) {
                return false;
            }
            return !lines.get(0).contains("is not a working copy");
        }
    } catch (IOException | InterruptedException e) {
        System.err.println("Could not find 'svn' executable, disabling author provider");
        return false;
    }
    return false;

}

From source file:eu.vital.vitalcep.cep.CepProcess.java

public void stopCEP() throws FileNotFoundException, IOException {

    String cmd = "kill -9 " + Integer.toString(PID);

    try {/*from w ww  .  j  ava  2  s.co  m*/
        Process pr = Runtime.getRuntime().exec(cmd);
        if (pr.waitFor(500, TimeUnit.MILLISECONDS)) {
            if (pr.exitValue() == 0) {
                logger.debug("bCEP stoped: " + PID);
                PID = -1;

                try {
                    File file = new File(cepFolder//+"/"+dolceFile
                            + "/" + fileName + "_dolce");
                    file.delete();
                    be.stop_while();
                } catch (Exception e) {
                    java.util.logging.Logger.getLogger(CepProcess.class.getName()).log(Level.SEVERE, null, e);
                }
            }
        }
    } catch (IOException | InterruptedException e) {
        java.util.logging.Logger.getLogger(CepProcess.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:com.bekwam.resignator.commands.KeytoolCommand.java

public List<KeystoreEntry> findKeystoreEntries(String keytoolExec, String keystore, String storepass)
        throws CommandExecutionException {

    List<KeystoreEntry> entries = new ArrayList<>();

    Preconditions.checkNotNull(keytoolExec);
    Preconditions.checkNotNull(keystore);
    Preconditions.checkNotNull(storepass);

    File outputFile = null;//from www . j av a  2  s  .co  m

    try {

        String[] cmdAndArgs = { keytoolExec, "-keystore", keystore, "-storepass", storepass, "-list" };

        File resignatorDir = new File(System.getProperty("user.home"), ".resignator");

        String outputFileName = OUTPUTFILE_PREFIX
                + StringUtils.lowerCase(RandomStringUtils.randomAlphabetic(12)) + OUTPUTFILE_SUFFIX;

        outputFile = new File(resignatorDir, outputFileName);

        ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
        pb.redirectErrorStream(false);
        pb.redirectOutput(outputFile);

        Process p = pb.start();

        boolean exitted = p.waitFor(TIMEOUT_SECS, TimeUnit.SECONDS);

        if (exitted) {

            if (p.exitValue() == 0) {

                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile)));
                entries.addAll(parseKeystoreEntries(br));
                br.close();

            } else {

                String firstLine = "";
                if (outputFile != null && outputFile.exists()) {
                    BufferedReader br = new BufferedReader(new FileReader(outputFile));
                    firstLine = br.readLine();
                    br.close();
                }

                if (logger.isErrorEnabled()) {
                    logger.error("error running exec={}; firstLine={}", keytoolExec, firstLine);
                }

                throw new CommandExecutionException(
                        "Command '" + keytoolExec + "' failed to run" + newLine + firstLine);
            }

        } else {

            if (logger.isErrorEnabled()) {
                logger.error("command '" + keytoolExec + "' timed out");
            }

            throw new CommandExecutionException("Command '" + keytoolExec + "' timed out");
        }

    } catch (Exception exc) { // includes interrupted exception

        if (logger.isErrorEnabled()) {
            logger.error("error running keytool", exc);
        }

        throw new CommandExecutionException("Error running keytool command" + newLine + exc.getMessage());

    } finally {
        if (outputFile != null) {
            outputFile.delete();
        }
    }

    return entries;
}

From source file:com.openshift.internal.restclient.capability.resources.OpenShiftBinaryRSync.java

private void waitForExit(String source, String destination, Process process) {
    try {/*from  w  w  w  .  j  a  va  2 s .  co  m*/
        if (process == null) {
            throw new OpenShiftException("Could not sync %s to %s, no process was launched.", destination);
        }
        if (!process.waitFor(WAIT_FOR_EXIT_TIMEOUT, TimeUnit.MINUTES)) {
            throw new OpenShiftException("Syncing %s to %s did not terminate within %d minutes.", source,
                    destination, WAIT_FOR_EXIT_TIMEOUT);
        }

        if (process.exitValue() != 0) {
            String errorMessage = getErrorMessage(process.getErrorStream());
            throw new OpenShiftException(
                    "Syncing %s to %s failed" + (StringUtil.isBlank(errorMessage) ? "" : ":%s"), source,
                    destination, errorMessage);
        }
    } catch (InterruptedException e) {
        throw new OpenShiftException(e, "Syncing %s to %s was interrupted.", source, destination);
    }
}

From source file:com.yahoo.rdl.maven.ProcessRunner.java

public String run(List<String> command, ProcessBuilder processBuilder) throws IOException {
    Process process = processBuilder.start();
    try (StreamConsumer stdout = new StreamConsumer(process.getInputStream()).start()) {
        try (StreamConsumer stderr = new StreamConsumer(process.getErrorStream()).start()) {
            if (!process.waitFor(10, TimeUnit.SECONDS)) {
                throw new IOException("Process took longer than 10 seconds to execute: " + command);
            }//  www.j  a v a  2s .  co  m
            if (process.exitValue() != 0) {
                String s = stderr.getContents();
                throw new IOException("command '" + StringUtils.join(command, " ") + "' produced error: " + s);
            }
        }
        return stdout.getContents();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.palantir.docker.compose.execution.DefaultDockerCompose.java

/**
 * Blocks until all logs collected from the container.
 * @return Whether the docker container terminated prior to log collection ending
 *//*  w w  w. ja va  2  s.c o m*/
@Override
public boolean writeLogs(String container, OutputStream output) throws IOException {
    try {
        Process executedProcess = followLogs(container);
        IOUtils.copy(executedProcess.getInputStream(), output);
        executedProcess.waitFor(COMMAND_TIMEOUT.getMillis(), MILLISECONDS);
    } catch (InterruptedException e) {
        return false;
    }
    return true;
}

From source file:com.netscape.cms.profile.constraint.ExternalProcessConstraint.java

public void validate(IRequest request, X509CertInfo info) throws ERejectException {
    CMS.debug("About to execute command: " + this.executable);
    ProcessBuilder pb = new ProcessBuilder(this.executable);

    // set up process environment
    Map<String, String> env = pb.environment();
    for (String k : envVars.keySet()) {
        String v = request.getExtDataInString(envVars.get(k));
        if (v != null)
            env.put(k, v);//from  www .  j  a v  a2s .  c o  m
    }
    for (String k : extraEnvVars.keySet()) {
        String v = request.getExtDataInString(extraEnvVars.get(k));
        if (v != null)
            env.put(k, v);
    }

    Process p;
    String stdout = "";
    String stderr = "";
    boolean timedOut;
    try {
        p = pb.start();
        timedOut = !p.waitFor(timeout, TimeUnit.SECONDS);
        if (timedOut)
            p.destroyForcibly();
        else
            stdout = IOUtils.toString(p.getInputStream());
        stderr = IOUtils.toString(p.getErrorStream());
    } catch (Throwable e) {
        String msg = "Caught exception while executing command: " + this.executable;
        CMS.debug(msg);
        CMS.debug(e);
        throw new ERejectException(msg, e);
    }
    if (timedOut)
        throw new ERejectException("Request validation timed out");
    int exitValue = p.exitValue();
    CMS.debug("ExternalProcessConstraint: exit value: " + exitValue);
    CMS.debug("ExternalProcessConstraint: stdout: " + stdout);
    CMS.debug("ExternalProcessConstraint: stderr: " + stderr);
    if (exitValue != 0)
        throw new ERejectException(stdout);
}