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:org.apache.tika.eval.TikaEvalCLITest.java

private static void execute(List<String> incomingArgs, long maxMillis) throws IOException {
    List<String> args = new ArrayList<>();
    String cp = System.getProperty("java.class.path");
    args.add("java");
    args.add("-cp");
    args.add(cp);/*from w  w w.j a v  a2  s . c  o  m*/
    args.add("org.apache.tika.eval.TikaEvalCLI");
    args.addAll(incomingArgs);

    ProcessBuilder pb = new ProcessBuilder(args);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process process = pb.start();
    long started = new Date().getTime();
    long elapsed = new Date().getTime() - started;
    int exitValue = Integer.MIN_VALUE;
    while (elapsed < maxMillis && exitValue == Integer.MIN_VALUE) {
        try {
            exitValue = process.exitValue();
        } catch (IllegalThreadStateException e) {

        }
        elapsed = new Date().getTime() - started;
    }
    if (exitValue == Integer.MIN_VALUE) {
        process.destroy();
        throw new RuntimeException(
                "Process never exited within the allowed amount of time.\n" + "I needed to destroy it");
    }
}

From source file:org.kuali.student.git.utils.ExternalGitUtils.java

/**
 * Run the batch ref updates using the external git command instead of the
 * JGit command./*from w w w. j  a  v a2  s. c o  m*/
 * 
 * @param externalGitCommand
 * @param repo
 * @param deferredReferenceDeletes
 * @param redirectStream
 * @throws IOException
 */
public static void batchRefUpdate(String externalGitCommand, Repository repo,
        List<ReceiveCommand> deferredReferenceDeletes, OutputStream redirectStream) throws IOException {

    for (ReceiveCommand receiveCommand : deferredReferenceDeletes) {

        String[] parts = receiveCommand.getRefName().split("/");

        String refName = parts[parts.length - 1];

        ObjectId refObjectId = receiveCommand.getNewId();

        List<String> commandOptions = new ArrayList<>();

        commandOptions.add(externalGitCommand);

        switch (receiveCommand.getType()) {

        case CREATE:
            commandOptions.add("branch");
            commandOptions.add(refName);
            commandOptions.add(refObjectId.getName());
            break;
        case DELETE:
            commandOptions.add("branch");
            commandOptions.add("-D");
            commandOptions.add(refName);
            break;
        case UPDATE:
        case UPDATE_NONFASTFORWARD:
            commandOptions.add("branch");
            commandOptions.add("-f");
            commandOptions.add(refName);
            commandOptions.add(refObjectId.getName());
            break;
        }

        try {
            Process p = runGitCommand(repo, true, commandOptions);

            waitFor(p, redirectStream);

            if (p.exitValue() == 0) {
                // normal termination

                if (receiveCommand.getType().equals(Type.CREATE)) {
                    // C git doesn't say anything in this case so log it
                    redirectStream.write(("Created branch " + receiveCommand.getRefName() + "\n").getBytes());
                }

            }

        } catch (InterruptedException e) {
        }

    }
}

From source file:org.noroomattheinn.utils.Utils.java

public static void openFileViewer(String where) {
    String command = "";

    if (SystemUtils.IS_OS_MAC) {
        command = "open";
    } else if (SystemUtils.IS_OS_WINDOWS) {
        command = "Explorer.exe";
    } else if (SystemUtils.IS_OS_LINUX) {
        //command = "vi";
        command = "xdg-open";
    }/*from www.  ja v  a2 s  .  c om*/

    try {
        Process p = (new ProcessBuilder(command, where)).start();
        p.waitFor();
        if (p.exitValue() != 0) {
            logger.warning("Unable to open file viewer with command: " + command);
        }
    } catch (IOException | InterruptedException ex) {
        logger.warning("Unable able to open file viewer: " + ex);
    }
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

public static int executeCommandGetReturnCode(String cmd, String workingDir, String executeFrom) {
    if (workingDir == null) {
        workingDir = "/tmp";
    }/* w  w w  .jav a 2  s.  c  o  m*/
    logger.debug("Execute command: " + cmd + ". Working dir: " + workingDir);
    try {
        String[] splitStr = cmd.split("\\s+");
        ProcessBuilder pb = new ProcessBuilder(splitStr);
        pb.directory(new File(workingDir));
        pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
        Map<String, String> env = pb.environment();
        String path = env.get("PATH");
        path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
        logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
        env.put("PATH", path);

        Process p = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            logger.debug(line);
        }
        p.waitFor();
        int returnCode = p.exitValue();
        logger.debug("Execute command done: " + cmd + ". Get return code: " + returnCode);
        return returnCode;
    } catch (InterruptedException | IOException e1) {
        logger.error("Error when execute command. Error: " + e1);
    }
    return -1;
}

From source file:de.bamamoto.mactools.png2icns.Scaler.java

protected static String runProcess(String[] commandLine) throws IOException {
    StringBuilder cl = new StringBuilder();
    for (String i : commandLine) {
        cl.append(i);/*from  w w  w  . j a  va 2  s .c  o m*/
        cl.append(" ");
    }

    String result = "";

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    Map<String, String> env = builder.environment();
    env.put("PATH", "/usr/sbin:/usr/bin:/sbin:/bin");
    builder.redirectErrorStream(true);
    Process process = builder.start();

    String line;

    InputStream stdout = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));

    while ((line = reader.readLine()) != null) {
        result += line + "\n";
    }

    boolean isProcessRunning = true;
    int maxRetries = 60;

    do {
        try {
            isProcessRunning = process.exitValue() < 0;
        } catch (IllegalThreadStateException ex) {
            System.out.println("Process not terminated. Waiting ...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException iex) {
                //nothing todo
            }
            maxRetries--;
        }
    } while (isProcessRunning && maxRetries > 0);
    System.out.println("Process has terminated");
    if (process.exitValue() != 0) {
        throw new IllegalStateException("Exit value not equal to 0: " + result);
    }
    if (maxRetries == 0 && isProcessRunning) {
        System.out.println("Process does not terminate. Try to kill the process now.");
        process.destroy();
    }

    return result;
}

From source file:net.sf.jasperreports.customvisualization.export.CVElementPhantomJSImageDataProvider.java

/**
 * Kill a process, if still active, after millisDelay
 * //from   ww w .j  a v a  2s.co m
 * @param externalProcess
 * @param millisDelay
 * @return true if the process had to be terminated, false if the process
 *         exited before the timeout
 */
public static boolean killProcess(Process externalProcess, int millisDelay) {
    try {
        Thread.sleep(millisDelay);
    } catch (InterruptedException e) {
        // e.printStackTrace();
    }

    try {
        int exitValue = externalProcess.exitValue();
        if (log.isDebugEnabled()) {
            log.debug("External Process monitoring thread - exit value: " + exitValue);
        }
        return false;
    } catch (IllegalThreadStateException e) {
        if (log.isDebugEnabled()) {
            log.debug("External Process monitoring thread - destroying process");
        }
        externalProcess.destroy();
        return true;
    }
}

From source file:com.ikanow.aleph2.data_model.utils.ProcessUtils.java

private static boolean killProcess(final String pid, final Optional<Integer> kill_signal) throws IOException {
    //      kill -15 the process, wait a few cycles to let it die            
    final ProcessBuilder pb = new ProcessBuilder(Arrays.asList("kill", "-" + kill_signal.orElse(15), pid));
    logger.debug("trying to kill -" + kill_signal.orElse(15) + " pid: " + pid);
    final Process px = pb.start();
    for (int i = 0; i < 5; ++i) {
        try {/*ww  w .ja v  a2s .com*/
            Thread.sleep(1000L);
        } catch (Exception e) {
        }
        if (!isProcessRunning(pid)) {
            break;
        }
    }
    if (!isProcessRunning(pid)) {
        return 0 == px.exitValue();
    } else {
        //we are still alive, so send a harder kill signal if we haven't already sent a 9
        if (kill_signal.isPresent() && kill_signal.get() == 9) {
            return false;
        } else {
            logger.debug("Timed out trying to kill: " + pid + " sending kill -9 to force kill");
            return killProcess(pid, Optional.of(9));
        }

    }
}

From source file:de.micromata.mgc.application.webserver.config.KeyTool.java

public static void generateKey(ValContext ctx, File keyFile, String storePass, String keyAlias) {
    String[] args = { "keytool", "-genkey", "-alias", keyAlias, "-keyalg", "RSA", "-keystore",
            keyFile.getAbsolutePath(), "-keysize", "2048", "-keypass", storePass, "-storepass", storePass,
            "-dname", "cn=Launcher, ou=MGC, o=Microamta, c=DE" };
    StringBuilder oksb = new StringBuilder();
    oksb.append("Execute: " + StringUtils.join(args, " "));
    try {/*from  ww w  .  j  a  v a2s  .  com*/
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            oksb.append(line);
        }
        boolean success = process.waitFor(5, TimeUnit.SECONDS);
        if (success == false) {
            ctx.directError(null, "Fail to wait for keytool");
        } else {
            int exitValue = process.exitValue();
            if (exitValue == 0) {
                oksb.append("\nSuccess");
                ctx.directInfo(null, oksb.toString());
            } else {
                ctx.directError(null, oksb.toString());
                ctx.directError(null, "Failure executing keytool. ReturnCode: " + exitValue);
            }
        }
    } catch (Exception ex) {
        ctx.directError(null, "Failure executing keytool: " + ex.getMessage(), ex);
    }
}

From source file:org.bml.util.io.net.NetworkUtils.java

/**
 * <p>//from   ww  w .  j a v  a2s. c o m
 * Attempt to resolve this computers host name. In its current state this 
 * method only calls 'hostname'.
 * </p>
 * <p>
 * <b>WARNING:</b>This method uses Runtime and a Process. It also waits for
 * the process to complete before returning.
 * </p>
 * <p>
 * Order of host name source.
 * <ol>
 * <li><code>Runtime.getRuntime().exec("hostname")</code>(Linux)</li>
 * <li><code>Runtime.getRuntime().exec("gethostname")</code>(Unix)</li>
 * <li><code>InetAddress.getLocalHost().getHostName()</code>(Other)</li>
 * </ol>
 * </p>
 *
 * @return The host name of the server that this code runs on.
 *
 * @throws java.io.IOException If there is a problem with {@link Process} IO
 * @throws java.lang.InterruptedException if this thread is interrupted while
 * it is waiting for a process to complete.
 * 
 * @todo Implement multiple hostname attempts and try to guess the rite one for the OS.
 */
public static String getThisHostName() throws IOException, InterruptedException {
    String hostname = null;
    Process process;
    StringWriter writer = new StringWriter();
    InputStream processInputStream;
    Runtime runtime = Runtime.getRuntime();
    try {
        //Attempt hostname call
        process = Runtime.getRuntime().exec("hostname");
        process.waitFor();
        processInputStream = process.getInputStream();
        IOUtils.copy(processInputStream, writer, CharEncoding.UTF_8);
        hostname = writer.toString();
        process.exitValue();
    } catch (IOException ioe) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("IPException caught while attempting to resolve hostname.", ioe);
        }
        throw ioe;
    }
    return hostname;
}

From source file:Main.java

public static int execRootCmdForExitCode(String[] cmds) {
    int result = -1;
    DataOutputStream dos = null;//from w ww . j  a  v  a 2  s.  c o m
    DataInputStream dis = null;

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        for (String cmd : cmds) {
            Log.i("CmdUtils", cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
        }
        dos.writeBytes("exit\n");
        dos.flush();
        String line;
        while ((line = dis.readLine()) != null) {
            Log.d("result", line);
        }
        p.waitFor();
        result = p.exitValue();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}