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.arm.connector.bridge.core.Utils.java

/**
 * Execute the AWS CLI//from   w w  w  . j  ava  2 s  .  c  om
 * @param logger - ErrorLogger instance
 * @param args - arguments for the AWS CLI 
 * @return response from CLI action
 */
public static String awsCLI(ErrorLogger logger, String args) {
    // construct the arguments
    String cmd = "./aws " + args;
    String response = null;
    String error = null;

    try {
        // invoke the AWS CLI
        Process proc = Runtime.getRuntime().exec(cmd);
        response = Utils.convertStreamToString(proc.getInputStream());
        error = Utils.convertStreamToString(proc.getErrorStream());

        // wait to completion
        proc.waitFor();
        int status = proc.exitValue();

        // DEBUG
        if (status != 0) {
            // non-zero exit status
            logger.warning("AWS CLI: Invoked: " + cmd);
            logger.warning("AWS CLI: Response: " + response);
            logger.warning("AWS CLI: Errors: " + error);
            logger.warning("AWS CLI: Exit Code: " + status);
        } else {
            // successful exit status
            logger.info("AWS CLI: Invoked: " + cmd);
            logger.info("AWS CLI: Response: " + response);
            logger.info("AWS CLI: Exit Code: " + status);
        }
    } catch (IOException | InterruptedException ex) {
        logger.warning("AWS CLI: Exception for command: " + cmd, ex);
        response = null;
    }

    // return the resposne
    return response;
}

From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProvider.java

private static File detectHadoopConfigurationDirectory(File command, File temporary, Map<String, String> envp)
        throws IOException {
    assert command != null;
    assert temporary != null;
    assert envp != null;

    prepareClasspath(temporary, ConfigurationDetecter.class);
    File resultOutput = new File(temporary, PATH_SUBPROC_OUTPUT);

    List<String> arguments = new ArrayList<>();
    arguments.add(command.getAbsolutePath());
    arguments.add(ConfigurationDetecter.class.getName());
    arguments.add(resultOutput.getAbsolutePath());

    ProcessBuilder processBuilder = new ProcessBuilder(arguments);
    processBuilder.environment().clear();
    processBuilder.environment().putAll(envp);
    processBuilder.environment().put(ENV_HADOOP_CLASSPATH, temporary.getPath());

    Process process = processBuilder.start();
    try {/*from   w w  w  .jav a 2  s .  co  m*/
        Thread redirectOut = redirect(process.getInputStream(), System.out);
        Thread redirectErr = redirect(process.getErrorStream(), System.err);
        try {
            int exit = process.waitFor();
            redirectOut.join();
            redirectErr.join();
            if (exit != 0) {
                throw new IOException(
                        MessageFormat.format("Failed to execute Hadoop command (exitcode={1}): {0}", arguments,
                                String.valueOf(exit)));
            }
        } catch (InterruptedException e) {
            throw (IOException) new InterruptedIOException(
                    MessageFormat.format("Failed to execute Hadoop command (interrupted): {0}", arguments))
                            .initCause(e);
        }
    } finally {
        process.destroy();
    }
    if (resultOutput.isFile() == false) {
        throw new IOException(
                MessageFormat.format("Failed to restore Hadoop configuration path: {0}", resultOutput));
    }
    File path = ConfigurationDetecter.read(resultOutput);
    return path;
}

From source file:eu.interedition.collatex.tools.CollationServer.java

private static String detectDotPath() {
    for (String detectionCommand : new String[] { "which dot", "where dot.exe" }) {
        try {//from w ww. jav a2  s.c o m

            final Process process = Runtime.getRuntime().exec(detectionCommand);
            try (BufferedReader processReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) {
                final CompletableFuture<Optional<String>> path = CompletableFuture
                        .supplyAsync(() -> processReader.lines().map(String::trim)
                                .filter(l -> l.toLowerCase().contains("dot")).findFirst());
                process.waitFor();
                final String dotPath = path.get().get();
                LOG.info(() -> "Detected GraphViz' dot at '" + dotPath + "'");
                return dotPath;
            }
        } catch (Throwable t) {
            LOG.log(Level.FINE, detectionCommand, t);
        }
    }
    return null;
}

From source file:io.sloeber.core.managers.InternalPackageManager.java

private static void chmod(File file, int mode) throws IOException, InterruptedException {
    String octal = Integer.toOctalString(mode);
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        boolean ownerExecute = (((mode / (8 * 8)) & 1) == 1);
        boolean ownerRead = (((mode / (8 * 8)) & 4) == 4);
        boolean ownerWrite = (((mode / (8 * 8)) & 2) == 2);
        boolean everyoneExecute = (((mode / 8) & 1) == 1);
        boolean everyoneRead = (((mode / 8) & 4) == 4);
        boolean everyoneWrite = (((mode / 8) & 2) == 2);
        file.setWritable(true, false);/*www . java 2  s .c o  m*/
        file.setExecutable(ownerExecute, !everyoneExecute);
        file.setReadable(ownerRead, !everyoneRead);
        file.setWritable(ownerWrite, !everyoneWrite);
    } else {
        Process process = Runtime.getRuntime().exec(new String[] { "chmod", octal, file.getAbsolutePath() }, //$NON-NLS-1$
                null, null);
        process.waitFor();
    }
}

From source file:com.modeln.build.common.tool.CMnCmdLineTool.java

/**
 * Wait for the executing process to complete.
 *
 * @param  process  Process to monitor//from w  w  w  . j  a va 2 s .  c  o  m
 * @param  profile  Enable or disable execution profiling
 */
public static int wait(Process process, boolean profile) throws InterruptedException {
    Date startDate = null;
    if (profile) {
        startDate = new Date();
    }

    // Use a separate thread to relay the process output to the user
    CMnProcessOutput stdout = new CMnProcessOutput(process, process.getInputStream());
    CMnProcessOutput stderr = new CMnProcessOutput(process, process.getErrorStream());
    Thread out = new Thread(stdout);
    Thread err = new Thread(stderr);
    out.start();
    err.start();

    // Wait for the process to complete
    int result = process.waitFor();

    // Display the elapsed time for this operation
    if (profile) {
        displayElapsedTime(startDate, new Date(), "Execution complete: ");
    }

    return result;
}

From source file:canreg.client.analysis.Tools.java

public static LinkedList<String> callR(String rScript, String rpath, String reportFileName)
        throws TableErrorException {
    LinkedList<String> filesCreated = new LinkedList<String>();
    Runtime rt = Runtime.getRuntime();
    ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(rpath);//from  w  ww.j  a va  2s  .c  o  m
    commandList.add("CMD");
    commandList.add("BATCH");
    commandList.add("--vanilla");
    commandList.add("--slave");
    commandList.add(rScript);
    commandList.add(reportFileName);

    //String command = canreg.common.Tools.encapsulateIfNeeded(rpath)
    //        + " CMD BATCH --vanilla --slave "
    //        + canreg.common.Tools.encapsulateIfNeeded(rScript) + " "
    //        + canreg.common.Tools.encapsulateIfNeeded(reportFileName);
    System.out.println(commandList);
    Process pr = null;
    try {
        pr = rt.exec(commandList.toArray(new String[] {}));
        // collect the output from the R program in a stream
        // BufferedInputStream is = new BufferedInputStream(pr.getInputStream());
        pr.waitFor();
        BufferedInputStream is = new BufferedInputStream(new FileInputStream(reportFileName));
        // convert the output to a string
        String theString = convertStreamToString(is);
        Logger.getLogger(RTableBuilderGrouped.class.getName()).log(Level.INFO, "Messages from R: \n{0}",
                theString);
        // System.out.println(theString);
        // and add all to the list of files to return
        for (String fileName : theString.split("\n")) {
            if (fileName.startsWith("-outFile:")) {
                fileName = fileName.replaceFirst("-outFile:", "");
                if (new File(fileName).exists()) {
                    filesCreated.add(fileName);
                }
            }
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
    } catch (java.util.NoSuchElementException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
        if (pr != null) {
            BufferedInputStream errorStream = new BufferedInputStream(pr.getErrorStream());
            String errorMessage = convertStreamToString(errorStream);
            System.out.println(errorMessage);
            throw new TableErrorException("R says:\n \"" + errorMessage + "\"");
        }
    } catch (IOException ex) {
        Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (pr != null) {
            System.out.println(pr.exitValue());
        }
    }
    return filesCreated;
}

From source file:com.samsung.sjs.Compiler.java

public static int manage_c_compiler(Process clang, CompilerOptions opts)
        throws IOException, InterruptedException {
    clang.waitFor();
    if (clang.exitValue() != 0 && !opts.debug()) {
        // If clang failed and we didn't already dump its stderr
        StringWriter w_stdout = new StringWriter(), w_stderr = new StringWriter();
        IOUtils.copy(clang.getInputStream(), w_stdout, Charset.defaultCharset());
        IOUtils.copy(clang.getErrorStream(), w_stderr, Charset.defaultCharset());
        String compstdout = w_stdout.toString();
        String compstderr = w_stderr.toString();
        System.err.println("C compiler [" + opts.clangPath() + "] failed.");
        System.out.println("C compiler stdout:");
        System.out.println(compstdout);
        System.err.println("C compiler stderr:");
        System.err.println(compstderr);
    }/*from   ww  w  .  j  a  va 2s  .com*/
    return clang.exitValue();
}

From source file:hdfs.FileUtil.java

/**
 * Create a soft link between a src and destination
 * only on a local disk. HDFS does not support this
 * @param target the target for symlink 
 * @param linkname the symlink/*from   w w w  . j  a v a 2  s . com*/
 * @return value returned by the command
 */
public static int symLink(String target, String linkname) throws IOException {
    String cmd = "ln -s " + target + " " + linkname;
    Process p = Runtime.getRuntime().exec(cmd, null);
    int returnVal = -1;
    try {
        returnVal = p.waitFor();
    } catch (InterruptedException e) {
        //do nothing as of yet
    }
    if (returnVal != 0) {
        LOG.warn("Command '" + cmd + "' failed " + returnVal + " with: " + copyStderr(p));
    }
    return returnVal;
}

From source file:io.hops.hopsworks.common.util.HopsUtils.java

/**
 * Retrieves the global hadoop classpath.
 *
 * @param params//from  w  w  w  .j  a v  a  2s  . c  o  m
 * @return hadoop global classpath
 */
public static String getHadoopClasspathGlob(String... params) {
    ProcessBuilder pb = new ProcessBuilder(params);
    try {
        Process process = pb.start();
        int errCode = process.waitFor();
        if (errCode != 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        }
        //Now we must remove the yarn shuffle library as it creates issues for 
        //Zeppelin Spark Interpreter
        StringBuilder classpath = new StringBuilder();

        for (String path : sb.toString().split(File.pathSeparator)) {
            if (!path.contains("yarn") && !path.contains("jersey") && !path.contains("servlet")) {
                classpath.append(path).append(File.pathSeparator);
            }
        }
        if (classpath.length() > 0) {
            return classpath.toString().substring(0, classpath.length() - 1);
        }

    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(HopsUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:io.sloeber.core.managers.InternalPackageManager.java

private static void symlink(String from, File to) throws IOException, InterruptedException {
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        // needs special rights only one board seems to fail due to this
        // Process process = Runtime.getRuntime().exec(new String[] {
        // "mklink", from, to.getAbsolutePath() }, //$NON-NLS-1$
        // null, to.getParentFile());
        // process.waitFor();
    } else {//from w  w w .  j  a v  a2s. co m
        Process process = Runtime.getRuntime().exec(new String[] { "ln", "-s", from, to.getAbsolutePath() }, //$NON-NLS-1$ //$NON-NLS-2$
                null, to.getParentFile());
        process.waitFor();
    }

}