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 abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

From source file:com.almarsoft.GroundhogReader.lib.FSUtils.java

public static boolean deleteDirectory(String directory) {

    Process process;
    try {//from  www.j a  va  2 s  .  c  o  m
        process = Runtime.getRuntime().exec("rm -r " + directory);
        process.waitFor();
        if (process.exitValue() == 0)
            return true;
    } catch (IOException e) {
        Log.d("Groundhog", "IOException in rm -r " + directory);
        e.printStackTrace();
    } catch (InterruptedException e) {
        Log.d("Groundhog", "InterruptedException in rm -r " + directory);
        e.printStackTrace();
    }

    return false;

}

From source file:gool.executor.Command.java

/**
 * Executes a command in the specified working directory.
 * //from  w ww . j av a 2s .  co m
 * @param workingDir
 *            the working directory.
 * @param params
 *            the command to execute and its parameters.
 * @return the console output.
 */
public static String exec(File workingDir, List<String> params, Map<String, String> env) {
    try {
        StringBuffer buffer = new StringBuffer();

        ProcessBuilder pb = new ProcessBuilder(params);
        pb.directory(workingDir);

        for (Entry<String, String> e : env.entrySet()) {
            pb.environment().put(e.getKey(), e.getValue());
        }
        Process p = pb.redirectErrorStream(true).start();

        p.getOutputStream().close();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line;
        while ((line = in.readLine()) != null) {
            buffer.append(line).append("\n");
        }

        int retval = p.waitFor();

        if (retval != 0) {
            throw new CommandException(
                    "The command execution returned " + retval + " as return value... !\n" + buffer);
        }

        return buffer.toString();
    } catch (IOException e) {
        throw new CommandException(e);
    } catch (InterruptedException e) {
        throw new CommandException("It seems the process was killed", e);
    }
}

From source file:TestFuseDFS.java

/**
 * Exec the given command and assert it executed successfully
 *//*from   ww  w.  j  a v a2  s. c  o  m*/
private static void execWaitRet(String cmd) throws IOException {
    LOG.debug("EXEC " + cmd);
    Process p = r.exec(cmd);
    try {
        p.waitFor();
    } catch (InterruptedException ie) {
        fail("Process interrupted: " + ie.getMessage());
    }
}

From source file:Main.java

public static String getLocalDns(String dns) {
    Process process = null;
    String str = "";
    BufferedReader reader = null;
    try {/*  ww  w .j  av  a 2  s  .c o m*/
        process = Runtime.getRuntime().exec("getprop net." + dns);
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            str += line;
        }
        reader.close();
        process.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            process.destroy();
        } catch (Exception e) {
        }
    }
    return str.trim();
}

From source file:net.morimekta.idltool.IdlUtils.java

public static Git getCacheRepository(File cacheDir, String repository) throws IOException, GitAPIException {
    File repoCache = getCacheDirectory(cacheDir, repository);

    Runtime runtime = Runtime.getRuntime();
    if (!repoCache.exists()) {
        Process p = runtime
                .exec(new String[] { "git", "clone", repository, repoCache.getAbsoluteFile().toString() });
        try {/*from w  ww  .  ja  va  2s  .  c o m*/
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    } else {
        Process p = runtime.exec(new String[] { "git", "fetch", "origin", "-p" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "add", "-A" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "reset", "origin/master", "--hard" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
    return Git.open(repoCache);
}

From source file:com.qubit.terra.docs.util.helpers.OpenofficeInProcessConverter.java

public static synchronized byte[] convert(final byte[] odtContent, final String tempDirFullPath,
        final String mimeTypeAbbreviation) {

    try {//from  www. j av  a  2 s.  com
        long currentTimeMillis = System.currentTimeMillis();
        if (System.getProperty("os.name").startsWith("Windows")) {
            final String odtFilename = tempDirFullPath + "openofficeConversion-" + currentTimeMillis + ".odt";

            FileUtils.writeByteArrayToFile(new File(odtFilename), odtContent);

            final Process process = Runtime.getRuntime()
                    .exec(String.format("soffice --headless --convert-to %s --outdir %s %s",
                            mimeTypeAbbreviation, tempDirFullPath.subSequence(0, tempDirFullPath.length() - 1),
                            odtFilename));

            try {
                process.waitFor();
            } catch (InterruptedException e) {
            }

            process.destroy();

            final String outputFilename = tempDirFullPath + "openofficeConversion-" + currentTimeMillis + "."
                    + mimeTypeAbbreviation;
            final byte[] output = FileUtils.readFileToByteArray(new File(outputFilename));

            FileUtils.deleteQuietly(new File(odtFilename));
            FileUtils.deleteQuietly(new File(outputFilename));
            return output;

        } else {
            final String odtFilename = tempDirFullPath + "/openofficeConversion-" + currentTimeMillis + ".odt";

            FileUtils.writeByteArrayToFile(new File(odtFilename), odtContent);

            final Process process = Runtime.getRuntime()
                    .exec(String.format(
                            "soffice --headless --convert-to %s -env:UserInstallation=file://%s --outdir %s %s",
                            mimeTypeAbbreviation, tempDirFullPath, tempDirFullPath, odtFilename));

            try {
                process.waitFor();
            } catch (InterruptedException e) {
            }

            process.destroy();

            final String outputFilename = tempDirFullPath + "/openofficeConversion-" + currentTimeMillis + "."
                    + mimeTypeAbbreviation;
            final byte[] output = FileUtils.readFileToByteArray(new File(outputFilename));
            FileUtils.deleteQuietly(new File(odtFilename));
            FileUtils.deleteQuietly(new File(outputFilename));
            return output;

        }
    } catch (final Throwable e) {
        throw new OpenofficeInProcessConversionException(e);
    }

}

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

public static void executeCommandSimple(String cmd, String workingDir) {
    logger.debug("Running command: {} in folder: {}", cmd, workingDir);
    Process p;
    try {/*from   ww  w  . j a  v  a 2  s  . c om*/
        String newCmd = "cd " + workingDir + " && " + cmd;
        logger.debug("The whole command to execute: {}", newCmd);
        p = Runtime.getRuntime().exec(newCmd);
        p.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error when run command: {}", cmd, ex);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.task.SVMHMMTestTask.java

/**
 * Executes the command (runs a new process outside the JVM and waits for its completion)
 *
 * @param command command as list of Strings
 *///w w  w  . j a v  a 2 s. c o  m
private static void runCommand(List<String> command) throws Exception {
    log.info(StringUtils.join(command, " "));

    if (PRINT_STD_OUT) {
        Process process = new ProcessBuilder().inheritIO().command(command).start();
        process.waitFor();
    } else {
        // create temp files for capturing output instead of printing to stdout/stderr
        File tmpOutLog = File.createTempFile("tmp.out.", ".log");

        ProcessBuilder processBuilder = new ProcessBuilder(command);

        processBuilder.redirectError(tmpOutLog);
        processBuilder.redirectOutput(tmpOutLog);

        // run the process
        Process process = processBuilder.start();
        process.waitFor();

        // re-read the output and debug it
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tmpOutLog)));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug(line);
        }
        IOUtils.closeQuietly(br);

        // delete files
        FileUtils.deleteQuietly(tmpOutLog);
    }
}

From source file:edu.clemson.cs.nestbed.server.util.UsbPowerControl.java

private static void setPowerState(int bus, int device, int port, int state) {
    ProcessBuilder processBuilder;
    Process process;
    int exitValue;

    try {// w  ww  . j a v  a  2s  . co  m
        //processBuilder = new ProcessBuilder(SET_DEV_POWER,
        processBuilder = new ProcessBuilder("/usr/bin/sudo", SET_DEV_POWER, "-b", Integer.toString(bus), "-d",
                Integer.toString(device), "-P", Integer.toString(port), "-p", Integer.toString(state));
        process = processBuilder.start();

        process.waitFor();
        exitValue = process.exitValue();

        if (exitValue == 0) {
            log.debug("Set power state successfully");
        } else {
            log.error("Unable to set power state");
        }
    } catch (InterruptedException ex) {
        log.error("Process interrupted", ex);
    } catch (IOException ex) {
        log.error("I/O Exception occured while reading device info", ex);
    }
}

From source file:edu.umd.cs.marmoset.utilities.MarmosetUtilities.java

/**
 * Uses the kill command to kill this process as a group leader with: <br>
 * kill -9 -&lt;pid&gt;//from w w  w . j  a v  a2s  . c o m
 * <p>
 * If kill -9 -&lt;pid&gt; fails, then this method will call
 * @param process
 */
public static void destroyProcessGroup(Process process, Logger log) {
    int pid = 0;
    try {
        pid = getPid(process);

        log.debug("PID to be killed = " + pid);

        //String command = "kill -9 -" +pid;
        String command = "kill -9 " + pid;

        String[] cmd = command.split("\\s+");

        Process kill = Runtime.getRuntime().exec(cmd);
        log.warn("Trying to kill the process group leader: " + command);
        kill.waitFor();
    } catch (IOException e) {
        // if we can't execute the kill command, then try to destroy the process
        log.warn("Unable to execute kill -9 -" + pid + "; now calling process.destroy()");
    } catch (InterruptedException e) {
        log.error("kill -9 -" + pid + " process was interrupted!  Now calling process.destroy()");
    } finally {
        // call process.destroy() whether or not "kill -9 -<pid>" worked
        // in order to maintain proper internal state
        process.destroy();
    }
}