Example usage for java.lang Process exitValue

List of usage examples for java.lang Process exitValue

Introduction

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

Prototype

public abstract int exitValue();

Source Link

Document

Returns the exit value for the process.

Usage

From source file:com.act.utils.ProcessRunner.java

/**
 * Run's a child process using the specified command and arguments, timing out after a specified number of seconds
 * if the process does not terminate on its own in that time.
 * @param command The process to run./*www.  j ava  2s . c  om*/
 * @param args The arguments to pass to that process.
 * @param timeoutInSeconds A timeout to impose on the child process; an InterruptedException is likely to occur
 *                         when the child process times out.
 * @return The exit code of the child process.
 * @throws InterruptedException
 * @throws IOException
 */
public static int runProcess(String command, List<String> args, Long timeoutInSeconds)
        throws InterruptedException, IOException {
    /* The ProcessBuilder doesn't differentiate the command from its arguments, but we do in our API to ensure the user
     * doesn't just pass us a single string command, which invokes the shell and can cause all sorts of bugs and
     * security issues. */
    List<String> commandAndArgs = new ArrayList<String>(args.size() + 1) {
        {
            add(command);
            addAll(args);
        }
    };
    ProcessBuilder processBuilder = new ProcessBuilder(commandAndArgs);
    LOGGER.info("Running child process: %s", StringUtils.join(commandAndArgs, " "));

    Process p = processBuilder.start();
    // Log whatever the child writes.
    new StreamLogger(p.getInputStream(), l -> LOGGER.info("[child STDOUT]: %s", l)).run();
    new StreamLogger(p.getErrorStream(), l -> LOGGER.warn("[child STDERR]: %s", l)).run();
    // Wait for the child process to exit, timing out if it takes to long to finish.
    if (timeoutInSeconds != null) {
        p.waitFor(timeoutInSeconds, TimeUnit.SECONDS);
    } else {
        p.waitFor();
    }

    // 0 is the default success exit code in *nix land.
    if (p.exitValue() != 0) {
        LOGGER.error("Child process exited with non-zero status code: %d", p.exitValue());
    }

    return p.exitValue();
}

From source file:ee.ria.xroad.proxy.messagelog.TestUtil.java

static ShellCommandOutput runShellCommand(String command) {
    if (isBlank(command)) {
        return null;
    }//w w  w .j  av a  2  s. co m

    log.info("Executing shell command: \t{}", command);

    try {
        Process process = new ProcessBuilder(command.split("\\s+")).start();

        StandardErrorCollector standardErrorReader = new StandardErrorCollector(process);

        StandardOutputReader standardOutputReader = new StandardOutputReader(process);

        standardOutputReader.start();
        standardErrorReader.start();

        standardOutputReader.join();
        standardErrorReader.join();
        process.waitFor();

        int exitCode = process.exitValue();

        return new ShellCommandOutput(exitCode, standardOutputReader.getStandardOutput(),
                standardErrorReader.getStandardError());
    } catch (Exception e) {
        log.error("Failed to execute archive transfer command '{}'", command);
        throw new RuntimeException(e);
    }
}

From source file:com.ibm.iotf.sample.client.gateway.devicemgmt.GatewayFirmwareHandlerSample.java

/**
 * Since JDK7 doesn't take any timeout parameter, we provide an workaround
 * that wakes up every second and checks for the completion status of the process.
 * @param process/*w  w w  . java  2s  .c  o m*/
 * @param minutes
 * @return
 * @throws InterruptedException 
 */
public static boolean waitForCompletion(Process process, int minutes) throws InterruptedException {
    long timeToWait = (60 * minutes);

    int exitValue = -1;
    for (int i = 0; i < timeToWait; i++) {
        try {
            exitValue = process.exitValue();
        } catch (IllegalThreadStateException e) {
            // Process is still running
        }
        if (exitValue == 0) {
            return true;
        }
        Thread.sleep(1000);
    }
    // Destroy the process forcibly
    try {
        process.destroy();
    } catch (Exception e) {
    }

    return false;
}

From source file:docs.AbstractGemFireIntegrationTests.java

protected static int waitForProcessToStop(Process process, File directory, long duration) {
    final long timeout = (System.currentTimeMillis() + duration);

    try {//from ww  w.  j  av a 2  s  .com
        while (process.isAlive() && System.currentTimeMillis() < timeout) {
            if (process.waitFor(DEFAULT_WAIT_INTERVAL, TimeUnit.MILLISECONDS)) {
                return process.exitValue();
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

    return (process.isAlive() ? -1 : process.exitValue());
}

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static String getSubjectFromCSR(String csr) throws IOException, InterruptedException {
    File csrFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".csr");
    FileUtils.writeStringToFile(csrFile, csr);
    List<String> cmds = new ArrayList<>();
    //openssl req -in certs-dir/hops-site-certs/csr.pem -noout -subject
    cmds.add("openssl");
    cmds.add("req");
    cmds.add("-in");
    cmds.add(csrFile.getAbsolutePath());
    cmds.add("-noout");
    cmds.add("-subject");

    StringBuilder sb = new StringBuilder("/usr/bin/ ");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }/*from ww w .  j ava  2  s  . c  o  m*/
    logger.info(sb.toString());
    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    StringBuilder lines = new StringBuilder("");
    while ((line = br.readLine()) != null) {
        logger.info(line);
        lines.append(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to get subject. Exit value: " + exitValue);
    }
    return lines.toString();
}

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static String getSerialNumberFromCert(String cert) throws IOException, InterruptedException {
    File csrFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".pem");
    FileUtils.writeStringToFile(csrFile, cert);
    List<String> cmds = new ArrayList<>();
    //openssl x509 -in certs-dir/hops-site-certs/pub.pem -noout -serial
    cmds.add("openssl");
    cmds.add("x509");
    cmds.add("-in");
    cmds.add(csrFile.getAbsolutePath());
    cmds.add("-noout");
    cmds.add("-serial");

    StringBuilder sb = new StringBuilder("/usr/bin/ ");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }/*from   www. jav a  2s  . c o  m*/
    logger.info(sb.toString());
    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    StringBuilder lines = new StringBuilder("");
    while ((line = br.readLine()) != null) {
        logger.info(line);
        lines.append(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to get Serial Number. Exit value: " + exitValue);
    }
    return lines.toString();
}

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static String verifyCertificate(Settings settings, String cert, boolean intermediate)
        throws IOException, InterruptedException {
    File certFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".pem");
    FileUtils.writeStringToFile(certFile, cert);
    String certDir = intermediate ? settings.getIntermediateCaDir() : settings.getCaDir();
    String crlFile = intermediate ? certDir + "/crl/intermediate.crl.pem" : certDir + "/crl/ca.crl.pem";
    String pubCert = intermediate ? "/intermediate/certs/intermediate.cert.pem " : "/certs/ca.cert.pem ";
    //update the crl
    createCRL(settings, intermediate);//from   w  w  w. jav  a2s  . c o m
    logger.info("Checking certificate...");
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("verify");
    cmds.add("-crl_check");
    cmds.add("-CAfile");
    cmds.add("<(cat " + certDir + pubCert + crlFile + ")");
    cmds.add(certFile.getAbsolutePath());
    StringBuilder sb = new StringBuilder("/usr/bin/");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }
    logger.info(sb.toString());

    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    StringBuilder lines = new StringBuilder("");
    while ((line = br.readLine()) != null) {
        logger.info(line);
        lines.append(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed cert check. Exit value: " + exitValue);
    }
    logger.info("Done cert check.");
    return lines.toString();
}

From source file:org.moeaframework.TestUtils.java

/**
 * Attempts to run make in the given folder.  If make is not successful,
 * the test is skipped./*from   w w  w. j  av a2  s .  c om*/
 * 
 * @param folder the folder in which make is executed
 */
public static void runMake(File folder) {
    System.out.println("Running make to build test executables");

    try {
        Process process = Runtime.getRuntime().exec("make", null, folder);

        if (process.waitFor() != 0) {
            System.err.println("make exited with an error status (" + process.exitValue() + "), skipping test");
            Assume.assumeTrue(false);
        }
    } catch (InterruptedException e) {
        System.err.println("interrupted while waiting for make to " + "complete, skipping test");
        Assume.assumeTrue(false);
    } catch (IOException e) {
        System.err.println("unable to run make, skipping test");
        Assume.assumeTrue(false);
    }
}

From source file:org.oscarehr.util.WKHtmlToPdfUtils.java

/**
 * Normally you can just run a command and it'll complete. The problem with doing that is if the command takes a while and you need to know when it's completed, like if it's cpu intensive like image processing and possibly in this case pdf creation.
 * This method will run the command and it has 2 stopping conditions, 1) normal completion as per the process.exitValue() or if the process does not appear to be doing anything. As a result there's a polling thread to check the out put file to see if
 * anything is happening. The example is if you're doing image processing and you're scaling an image with say imagemagick it could take 5 minutes to finish. You don't want to set a time out that long, but you don't want to stop if it it's proceeding
 * normally. Normal proceeding is defined by the out put file is still changing. If the out put file isn't changing, and it's taking "a while" then we would assume it's failed some how or hung or stalled at which point we'll terminate it.
 */// w w w.  j  a  v  a2  s .c  o  m
private static void runtimeExec(ArrayList<String> command, String outputFilename) throws IOException {
    File f = new File(outputFilename);
    Process process = null;
    try {
        process = Runtime.getRuntime().exec(command.toArray(new String[0]));
    } catch (Exception e) {
        logger.error("PDF conversion exception: ", e);
    }
    long previousFileSize = 0;
    int noFileSizeChangeCounter = 0;

    try {
        while (true) {
            try {
                Thread.sleep(PROCESS_COMPLETION_CYCLE_CHECK_PERIOD);
            } catch (InterruptedException e) {
                logger.error("Thread interrupted", e);
            }

            try {
                int exitValue = process.exitValue();

                if (exitValue != 0) {
                    logger.debug("Error running command : " + command);

                    String errorMsg = StringUtils.trimToNull(IOUtils.toString(process.getInputStream()));
                    if (errorMsg != null)
                        logger.debug(errorMsg);

                    errorMsg = StringUtils.trimToNull(IOUtils.toString(process.getErrorStream()));
                    if (errorMsg != null)
                        logger.debug(errorMsg);
                }

                return;
            } catch (IllegalThreadStateException e) {
                long tempSize = f.length();

                logger.debug("Progress output filename=" + outputFilename + ", filesize=" + tempSize);

                if (tempSize != previousFileSize)
                    noFileSizeChangeCounter = 0;
                else {
                    noFileSizeChangeCounter++;

                    if (noFileSizeChangeCounter > MAX_NO_CHANGE_COUNT)
                        break;
                }
            }
        }

        logger.error("Error, process appears stalled. command=" + command);
    } finally {
        process.destroy();
    }
}

From source file:org.midonet.util.process.ProcessHelper.java

public static RunnerConfiguration newProcess(final String commandLine) {

    return new RunnerConfiguration() {
        DrainTarget drainTarget;//from   www .  j ava 2s  .  co  m
        String procCommandLine = commandLine;
        Map<String, String> envVars = new HashMap<>();

        EnumSet<OutputStreams> streamsToLog = EnumSet.allOf(OutputStreams.class);
        final List<Runnable> exitHandlers = new ArrayList<>(1);

        @Override
        public RunnerConfiguration logOutput(Logger log, String marker, OutputStreams... streams) {
            streamsToLog.clear();

            if (streams.length == 0) {
                streamsToLog = EnumSet.of(OutputStreams.StdOutput);
            } else {
                streamsToLog = EnumSet.noneOf(OutputStreams.class);
                Collections.addAll(streamsToLog, streams);
            }

            drainTarget = DrainTargets.slf4jTarget(log, marker);
            return this;
        }

        public RunnerConfiguration setDrainTarget(DrainTarget drainTarget) {
            this.drainTarget = drainTarget;
            return this;
        }

        @Override
        public RunnerConfiguration setEnvVariables(Map<String, String> vars) {

            this.envVars.putAll(vars);
            return this;
        }

        @Override
        public RunnerConfiguration setEnvVariable(String var, String value) {
            this.envVars.put(var, value);
            return this;
        }

        @Override
        public RunnerConfiguration addExitHandler(Runnable handler) {
            synchronized (exitHandlers) {
                exitHandlers.add(handler);
            }
            return this;
        }

        @Override
        public int runAndWait() {
            Process p = createProcess(true);

            String processName = procCommandLine;

            try {
                if (p != null) {
                    p.waitFor();

                    IOUtils.closeQuietly(p.getInputStream());
                    IOUtils.closeQuietly(p.getErrorStream());
                    IOUtils.closeQuietly(p.getOutputStream());

                    if (p.exitValue() == 0) {
                        log.trace("Process \"{}\" exited with code: {}", processName, p.exitValue());

                    } else {
                        log.debug("Process \"{}\" exited with non zero code: {}", processName, p.exitValue());
                    }
                    return p.exitValue();
                }
            } catch (InterruptedException e) {
                log.error(String.format("Error while launching command: \"%s\"", processName), e);
            }

            return -1;
        }

        public Process run() {
            return createProcess(false);
        }

        @Override
        public RunnerConfiguration withSudo() {
            procCommandLine = "sudo " + procCommandLine;
            return this;
        }

        private Process createProcess(boolean wait) {
            try {
                final Process process = launchProcess();
                if (drainTarget == null) {
                    drainTarget = DrainTargets.noneTarget();
                }

                Runnable exitHandler = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            process.waitFor();
                        } catch (InterruptedException e) {
                        }
                        synchronized (exitHandlers) {
                            for (Runnable handler : exitHandlers) {
                                handler.run();
                            }
                        }
                    }
                };

                ProcessOutputDrainer outputDrainer;

                if (streamsToLog.contains(OutputStreams.StdError)) {
                    outputDrainer = new ProcessOutputDrainer(process, true);
                } else {
                    outputDrainer = new ProcessOutputDrainer(process);
                }

                outputDrainer.drainOutput(drainTarget, wait, exitHandler);

                return process;
            } catch (IOException e) {
                log.error("Error while executing command: \"{}\"", commandLine, e);
            }

            return null;
        }

        private Process launchProcess() throws IOException {

            if (envVars.isEmpty()) {
                return Runtime.getRuntime().exec(procCommandLine);
            } else {
                List<String> param = new ArrayList<>();
                for (Map.Entry<String, String> var : envVars.entrySet()) {
                    param.add(var.getKey() + "=" + var.getValue());
                }
                return Runtime.getRuntime().exec(procCommandLine, param.toArray(new String[param.size()]));

            }
        }
    };
}