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.ibm.iotf.sample.devicemgmt.device.RasPiFirmwareHandlerSample.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.  j ava2s.  c o  m*/
 * @param minutes
 * @return
 * @throws InterruptedException 
 */
private 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:org.arquillian.cube.kubernetes.impl.utils.ProcessUtil.java

public static int runCommand(final Logger log, String command, List<String> args, Map<String, String> env,
        boolean withShutdownHook) throws IOException {
    String[] commandWithArgs = prepareCommandArray(command, args);
    String[] envp = prepareEnvp(env);
    Process process = Runtime.getRuntime().exec(commandWithArgs, envp);
    if (withShutdownHook) {
        addShutdownHook(log, process, command);
    }/*  ww  w .  j a v a 2  s  . com*/
    List<Thread> threads = startLoggingThreads(process, log, command + " " + Strings.join(args, " "));
    try {
        int answer = process.waitFor();
        joinThreads(threads, log);
        return answer;
    } catch (InterruptedException e) {
        return process.exitValue();
    }
}

From source file:org.openengsb.openengsbplugin.tools.Tools.java

public static int executeProcess(List<String> command, File targetDirectory)
        throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(targetDirectory);
    if (targetDirectory != null) {
        LOG.trace(//ww  w  . j a v  a  2 s  .co  m
                String.format("processBuilder.directory().exists(): %s", processBuilder.directory().exists()));
    }
    Process p = processBuilder.start();

    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            LOG.debug(line);
        }
    } finally {
        IOUtils.closeQuietly(br);
    }

    p.waitFor();
    return p.exitValue();
}

From source file:edu.dfci.cccb.mev.analysis.Limma.java

public static void execute(Heatmap heatmap, String selection1, String selection2, final File output,
        final File significant, final File rnk, String dimension)
        throws IOException, ScriptException, AnnotationNotFoundException {
    try (final Provisional input = file();
            final Provisional configuration = file();
            final Provisional script = file();
            final OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(script))) {
        if ("row".equals(dimension))
            configureRows(new FileOutputStream(configuration), heatmap, selection1, selection2);
        else/*from  w w  w  .java  2 s .c o m*/
            configureColumns(new FileOutputStream(configuration), heatmap, selection1, selection2);
        heatmap.toStream(new FileOutputStream(input));
        if (log.isDebugEnabled())
            try (BufferedReader readBack = new BufferedReader(new FileReader(input))) {
                log.debug("Dump line 1: \"" + readBack.readLine() + "\"");
                log.debug("Dump line 2: \"" + readBack.readLine() + "\"");
            }
        velocity.getTemplate(Limma.script).merge(new VelocityContext(new HashMap<String, String>() {
            private static final long serialVersionUID = 1L;

            {
                if (log.isDebugEnabled())
                    log.debug("Running LIMMA with input " + input.getAbsolutePath() + " configuration "
                            + configuration.getAbsolutePath() + " output " + output.getAbsolutePath()
                            + " significant " + significant);
                put("input", input.getAbsolutePath());
                put("configuration", configuration.getAbsolutePath());
                put("output", output.getAbsolutePath());
                put("significant", significant.getAbsolutePath());
                put("rnk", rnk.getAbsolutePath());
            }
        }), writer);
        writer.flush();
        Process r = Runtime.getRuntime().exec(Limma.r + " " + script.getAbsolutePath());
        try {
            r.waitFor();
        } catch (InterruptedException e) {
            log.error("Interrupted while waiting for R", e);
        }
        if (log.isDebugEnabled()) {
            ByteArrayOutputStream listing = new ByteArrayOutputStream();
            IOUtils.copy(r.getErrorStream(), listing);
            log.debug("Return value " + r.exitValue() + " error output:\n" + listing.toString());
        }
        if (r.exitValue() != 0)
            throw new RuntimeException("Non zero return value from R process " + r.exitValue());
        // r.eval (new InputStreamReader (new ByteArrayInputStream
        // (script.toByteArray ())));
    }
}

From source file:io.fabric8.maven.core.util.ProcessUtil.java

private static void addShutdownHook(final Logger log, final Process process, final File command) {
    Runtime.getRuntime().addShutdownHook(new Thread(command.getName()) {
        @Override//from www.j  a  va 2s  .com
        public void run() {
            if (process != null) {
                // Trying to determine if the process is alive
                boolean alive = false;
                try {
                    process.exitValue();
                } catch (IllegalThreadStateException e) {
                    alive = true;
                }

                if (alive) {
                    log.info("Terminating process %s", command);
                    try {
                        process.destroy();
                    } catch (Exception e) {
                        log.error("Failed to terminate process %s", command);
                    }
                    /* Only available in Java 8: So disabled for now until we switch to Java 8
                    try {
                    if (process != null && process.isAlive()) {
                        process.destroyForcibly();
                    }
                    } catch (Exception e) {
                    log.error("Failed to forcibly terminate process %s", command);
                    }
                    */
                }
            }
        }
    });
}

From source file:org.apache.storm.daemon.supervisor.ClientSupervisorUtils.java

/**
 * Launch a new process as per {@link ProcessBuilder} with a given
 * callback.//from  www . j a v a 2s . c  o  m
 * @param command the command to be executed in the new process
 * @param environment the environment to be applied to the process. Can be
 *                    null.
 * @param logPrefix a prefix for log entries from the output of the process.
 *                  Can be null.
 * @param exitCodeCallback code to be called passing the exit code value
 *                         when the process completes
 * @param dir the working directory of the new process
 * @return the new process
 * @throws IOException
 * @see ProcessBuilder
 */
public static Process launchProcess(List<String> command, Map<String, String> environment,
        final String logPrefix, final ExitCodeCallback exitCodeCallback, File dir) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command);
    Map<String, String> procEnv = builder.environment();
    if (dir != null) {
        builder.directory(dir);
    }
    builder.redirectErrorStream(true);
    if (environment != null) {
        procEnv.putAll(environment);
    }
    final Process process = builder.start();
    if (logPrefix != null || exitCodeCallback != null) {
        Utils.asyncLoop(new Callable<Object>() {
            public Object call() {
                if (logPrefix != null) {
                    Utils.readAndLogStream(logPrefix, process.getInputStream());
                }
                if (exitCodeCallback != null) {
                    try {
                        process.waitFor();
                        exitCodeCallback.call(process.exitValue());
                    } catch (InterruptedException ie) {
                        LOG.info("{} interrupted", logPrefix);
                        exitCodeCallback.call(-1);
                    }
                }
                return null; // Run only once.
            }
        });
    }
    return process;
}

From source file:org.apache.storm.daemon.supervisor.SupervisorUtils.java

public static int processLauncherAndWait(Map conf, String user, List<String> args,
        final Map<String, String> environment, final String logPreFix) throws IOException {
    int ret = 0;/*from w w w .j a v  a  2s .c o  m*/
    Process process = processLauncher(conf, user, null, args, environment, logPreFix, null, null);
    if (StringUtils.isNotBlank(logPreFix))
        Utils.readAndLogStream(logPreFix, process.getInputStream());
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        LOG.info("{} interrupted.", logPreFix);
    }
    ret = process.exitValue();
    return ret;
}

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

private static void runTransferCommand(String transferCommand) {
    if (isBlank(transferCommand)) {
        return;//from  w ww  .j  a  v a  2s  .  c  om
    }

    log.info("Transferring archives with shell command: \t{}", transferCommand);

    try {
        String[] command = new String[] { "/bin/bash", "-c", transferCommand };

        Process process = new ProcessBuilder(command).start();

        StandardErrorCollector standardErrorCollector = new StandardErrorCollector(process);

        new StandardOutputReader(process).start();

        standardErrorCollector.start();
        standardErrorCollector.join();

        process.waitFor();

        int exitCode = process.exitValue();
        if (exitCode != 0) {
            String errorMsg = String.format(
                    "Running archive transfer command '%s' " + "exited with status '%d'", transferCommand,
                    exitCode);

            log.error("{}\n -- STANDARD ERROR START\n{}\n" + " -- STANDARD ERROR END", errorMsg,
                    standardErrorCollector.getStandardError());
        }
    } catch (Exception e) {
        log.error("Failed to execute archive transfer command '{}'", transferCommand, e);
    }
}

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

public static void revokeCert(Settings settings, String certFile, boolean intermediate)
        throws IOException, InterruptedException {
    logger.info("Revoking certificate...");
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("ca");
    cmds.add("-batch");
    cmds.add("-config");
    if (intermediate) {
        cmds.add(settings.getIntermediateCaDir() + "/openssl-intermediate.cnf");
    } else {// ww  w. j ava2  s  .com
        cmds.add(settings.getCaDir() + "/openssl-ca.cnf");
    }
    cmds.add("-passin");
    cmds.add("pass:" + settings.getHopsworksMasterPasswordSsl());
    cmds.add("-revoke");
    cmds.add(certFile);

    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;
    while ((line = br.readLine()) != null) {
        logger.info(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to revoke certificate. Exit value: " + exitValue);
    }
    logger.info("Revoked certificate.");
    //update the crl
    createCRL(settings, intermediate);
}

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

public static String createCRL(Settings settings, boolean intermediate)
        throws IOException, InterruptedException {
    logger.info("Creating crl...");
    String generatedCrlFile;/*from  w w  w . j  av  a2  s  .  c o  m*/
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("ca");
    cmds.add("-batch");
    cmds.add("-config");
    if (intermediate) {
        cmds.add(settings.getIntermediateCaDir() + "/openssl-intermediate.cnf");
        generatedCrlFile = settings.getIntermediateCaDir() + "/crl/intermediate.crl.pem";
    } else {
        cmds.add(settings.getCaDir() + "/openssl-ca.cnf");
        generatedCrlFile = settings.getCaDir() + "/crl/ca.crl.pem";
    }
    cmds.add("-passin");
    cmds.add("pass:" + settings.getHopsworksMasterPasswordSsl());
    cmds.add("-gencrl");
    cmds.add("-out");
    cmds.add(generatedCrlFile);

    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;
    while ((line = br.readLine()) != null) {
        logger.info(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to create crl. Exit value: " + exitValue);
    }
    logger.info("Created crl.");
    return FileUtils.readFileToString(new File(generatedCrlFile));
}