Example usage for java.lang Process isAlive

List of usage examples for java.lang Process isAlive

Introduction

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

Prototype

public boolean isAlive() 

Source Link

Document

Tests whether the process represented by this Process is alive.

Usage

From source file:gov.nist.appvet.tool.sigverifier.Service.java

private static boolean execute(String command, StringBuffer output) {
    List<String> commandArgs = Arrays.asList(command.split("\\s+"));
    ProcessBuilder pb = new ProcessBuilder(commandArgs);
    Process process = null;
    IOThreadHandler outputHandler = null;
    IOThreadHandler errorHandler = null;
    int exitValue = -1;
    try {//from   ww  w .ja  v  a  2 s.c  o m
        if (command == null || command.isEmpty()) {
            log.error("Command is null or empty");
            return false;
        }
        log.debug("Executing " + command);
        process = pb.start();
        outputHandler = new IOThreadHandler(process.getInputStream());
        outputHandler.start();
        errorHandler = new IOThreadHandler(process.getErrorStream());
        errorHandler.start();
        if (process.waitFor(Properties.commandTimeout, TimeUnit.MILLISECONDS)) {
            // Process has waited and exited within the timeout
            exitValue = process.exitValue();
            if (exitValue == 0) {
                log.debug("Command terminated normally: \n" + outputHandler.getOutput() + "\nErrors: "
                        + errorHandler.getOutput());
                StringBuffer resultOut = outputHandler.getOutput();
                output.append(resultOut);
                return true;
            } else {
                log.error("Command terminated abnormally: \n" + outputHandler.getOutput() + "\nErrors: "
                        + errorHandler.getOutput());
                StringBuffer resultError = errorHandler.getOutput();
                output.append(resultError);
                return false;
            }
        } else {
            // Process exceed timeout or was interrupted
            log.error("Command timed-out or was interrupted: \n" + outputHandler.getOutput() + "\nErrors: "
                    + errorHandler.getOutput());
            StringBuffer resultOutput = outputHandler.getOutput();
            StringBuffer resultError = errorHandler.getOutput();
            if (resultOutput != null) {
                output.append(resultOutput);
                return false;
            } else if (resultError != null) {
                output.append(resultError);
            } else {
                output.append(Properties.toolName + " timed-out");
            }
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    } finally {
        if (outputHandler.isAlive()) {
            try {
                outputHandler.inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (errorHandler.isAlive()) {
            try {
                errorHandler.inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (process.isAlive()) {
            process.destroy();
        }
    }
}

From source file:com.stratio.qa.specs.CommonG.java

/**
 * Runs a command locally//  w  w  w. j a  v a  2  s.  co  m
 *
 * @param command command used to be run locally
 */
public void runLocalCommand(String command) throws Exception {

    String result = "";
    String line;
    Process p;
    try {
        p = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command });
        p.waitFor();
    } catch (java.io.IOException e) {
        this.commandExitStatus = 1;
        this.commandResult = "Error";
        return;
    }

    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
        result += line;
    }

    input.close();
    this.commandResult = result;
    this.commandExitStatus = p.exitValue();

    p.destroy();

    if (p.isAlive()) {
        p.destroyForcibly();
    }

}

From source file:com.jpmorgan.cakeshop.bean.QuorumConfigBean.java

public void createKeys(final String keyName, final String destination)
        throws IOException, InterruptedException {
    constellationConfig = destination;/*from   w  w w.  j  a v  a2  s . c o m*/
    File dir = new File(destination);
    Boolean createKeys = true;

    if (!dir.exists()) {
        dir.mkdirs();
    } else {
        String[] fileNames = dir.list();
        if (fileNames.length >= 4) {
            for (String fileName : fileNames) {
                if (fileName.endsWith(".key") || fileName.endsWith(".pub")) {
                    createKeys = false;
                    break;
                }
            }
        }
    }

    if (createKeys) {
        //create keys
        ProcessBuilder pb = new ProcessBuilder(getKeyGen(), destination.concat(keyName));
        Process process = pb.start();
        try (Scanner scanner = new Scanner(process.getInputStream())) {
            boolean flag = scanner.hasNext();
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(process.getOutputStream()))) {
                while (flag) {
                    String line = scanner.next();
                    if (line.isEmpty()) {
                        continue;
                    }
                    if (line.contains("[none]:")) {
                        writer.newLine();
                        writer.flush();
                        writer.newLine();
                        writer.flush();
                        flag = false;
                    }
                }
            }
        }

        int ret = process.waitFor();
        if (ret != 0) {
            LOG.error(
                    "Failed to generate keys. Please make sure that berkeley db is installed properly. Version of berkeley db is 6.2.23");
        } else {
            //create archive keys
            pb = new ProcessBuilder(getKeyGen(), destination.concat(keyName.concat("a")));
            process = pb.start();
            try (Scanner scanner = new Scanner(process.getInputStream())) {
                boolean flag = scanner.hasNext();
                try (BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(process.getOutputStream()))) {
                    while (flag) {
                        String line = scanner.next();
                        if (line.isEmpty()) {
                            continue;
                        }
                        if (line.contains("[none]:")) {
                            writer.write(" ");
                            writer.flush();
                            writer.newLine();
                            writer.flush();
                            flag = false;
                        }
                    }
                }
            }

            ret = process.waitFor();
            if (ret != 0) {
                LOG.error(
                        "Failed to generate keys. Please make sure that berkeley db is installed properly. Version of berkeley db is 6.2.23");
            }
        }

        if (process.isAlive()) {
            process.destroy();
        }
    }
}

From source file:org.wildfly.swarm.proc.Monitor.java

/**
 * Main test execution. Spawns an external process
 * @param iteration/*from   w  ww. j  a  v  a  2  s  .c o m*/
 * @param file
 * @param httpCheck
 * @param collector
 */
private void runTest(int iteration, File file, String httpCheck, final Collector collector) {

    System.out.println("Testing " + file.getAbsolutePath() + ", iteration " + iteration);
    String id = file.getAbsolutePath();

    String uid = UUID.randomUUID().toString();
    Process process = null;
    int attempts = 0;

    try {
        Path workDir = Files.createDirectories(
                this.workDir.toPath().resolve(Paths.get(file.getName(), "iteration-" + iteration)));
        Path tmp = Files.createDirectory(workDir.resolve("tmp"));

        ProcessBuilder pb = new ProcessBuilder("java", "-Duid=" + uid,
                "-Djava.io.tmpdir=" + tmp.toAbsolutePath().toString(), "-jar", file.getAbsolutePath())
                        .redirectOutput(workDir.resolve("stdout.txt").toFile())
                        .redirectError(workDir.resolve("stderr.txt").toFile());

        final long s0 = System.currentTimeMillis();
        process = pb.start();

        final CloseableHttpClient httpClient = HttpClients.createDefault();

        while (true) {
            if (attempts >= NUM_CONNECTION_ATTEMPTS) {
                System.out.println("Max attempts reached, escaping sequence");
                break;
            }

            CloseableHttpResponse response = null;
            try {
                HttpGet request = new HttpGet(httpCheck);
                response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();

                if (statusCode == 200) {
                    collector.onMeasurement(id, Measure.STARTUP_TIME,
                            (double) (System.currentTimeMillis() - s0));
                    warmup(httpClient, httpCheck);
                    measureMemory(id, uid, collector);
                    measureJarSize(id, file, collector);
                    measureTmpDirSize(id, tmp, collector);
                    break;
                } else if (statusCode == 404) {
                    // this can happen during server boot, when the HTTP endpoint is already exposed
                    // but the application is not yet deployed
                } else {
                    System.err.println("Failed to execute HTTP check: " + statusCode);
                    break;
                }
            } catch (HttpHostConnectException e) {
                // server not running yet
            } finally {
                if (response != null) {
                    response.close();
                }
            }

            attempts++;
            Thread.sleep(MS_BETWEEN_ATTEMPTS);
        }

        httpClient.close();

        final long s1 = System.currentTimeMillis();
        process.destroy();
        boolean finished = process.waitFor(2, TimeUnit.SECONDS);
        if (finished) {
            collector.onMeasurement(id, Measure.SHUTDOWN_TIME, (double) (System.currentTimeMillis() - s1));
        }
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        if (process != null && process.isAlive()) {
            process.destroyForcibly();
            try {
                process.waitFor(2, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}