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:energy.usef.environment.tool.security.VaultService.java

/**
 * Executes a class's static main method with the current java executable and classpath in a separate process.
 * //from   ww w.  j a v  a2s  .  com
 * @param klass the class to call the static main method for
 * @param params the parameters to provide
 * @return the exit code of the process
 * @throws IOException
 * @throws InterruptedException
 */
public static int exec(@SuppressWarnings("rawtypes") Class klass, List<String> params)
        throws IOException, InterruptedException {
    String javaHome = System.getProperty("java.home");
    String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
    String classpath = System.getProperty("java.class.path");
    String className = klass.getCanonicalName();

    // construct the command line
    List<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-cp");
    command.add(classpath);
    command.add(className);
    command.addAll(params);
    LOGGER.debug("executing class '{}' with params '{}' in classpath '{}' with java binary '{}'", className,
            params.toString(), classpath, javaBin);

    // build and start the Vault's process
    ProcessBuilder builder = new ProcessBuilder(command);
    Process process = builder.start();
    process.waitFor();

    // get the input and error streams of the process and log them
    InputStream in = process.getInputStream();
    InputStream en = process.getErrorStream();
    InputStreamReader is = new InputStreamReader(in);
    InputStreamReader es = new InputStreamReader(en);
    BufferedReader br = new BufferedReader(is);
    BufferedReader be = new BufferedReader(es);

    String read = br.readLine();
    while (read != null) {
        LOGGER.debug(read);
        read = br.readLine();
    }
    read = be.readLine();
    while (read != null) {
        LOGGER.debug(read);
        read = be.readLine();
    }

    br.close();
    is.close();
    in.close();

    return process.exitValue();
}

From source file:Main.java

public static boolean isRoot() {
    Process process = null;
    DataOutputStream dos = null;//from   www.jav a 2  s  .  c  om
    try {
        process = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(process.getOutputStream());
        dos.writeBytes("exit\n");
        dos.flush();
        int exitValue = process.waitFor();
        if (exitValue == 0) {
            return true;
        }
    } catch (IOException e) {

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
            }
        }
    }
    return false;
}

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 .ja va  2 s . c  om*/
            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:com.cedarsoft.io.LinkUtils.java

/**
 * Creates a link./*from w w  w .j  a v  a  2s.c  o m*/
 * Returns true if the link has been created, false if the link (with the same link source) still exists.
 *
 * @param linkTarget the link source
 * @param linkFile   the link file
 * @param symbolic   whether to create a symbolic link
 * @return whether the link has been created (returns false if the link still existed)
 *
 * @throws IOException if something went wrong
 */
public static boolean createLink(@Nonnull File linkTarget, @Nonnull File linkFile, boolean symbolic)
        throws IOException {
    if (linkFile.exists()) {
        //Maybe the hard link still exists - we just don't know, so throw an exception
        if (!symbolic) {
            throw new IOException("link still exists " + linkFile.getAbsolutePath());
        }

        if (linkFile.getCanonicalFile().equals(linkTarget.getCanonicalFile())) {
            //still exists - that is ok, since it points to the same directory
            return false;
        } else {
            //Other target
            throw new IOException("A link still exists at <" + linkFile.getAbsolutePath()
                    + "> but with different target: <" + linkTarget.getCanonicalPath() + "> exected <"
                    + linkFile.getCanonicalPath() + ">");
        }
    }

    List<String> args = new ArrayList<String>();
    args.add("ln");
    if (symbolic) {
        args.add("-s");
    }
    args.add(linkTarget.getPath());
    args.add(linkFile.getAbsolutePath());

    ProcessBuilder builder = new ProcessBuilder(args);
    Process process = builder.start();
    try {
        int result = process.waitFor();
        if (result != 0) {
            throw new IOException("Creation of link failed: " + IOUtils.toString(process.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    return true;
}

From source file:Main.java

public static void exec(File workingDir, String command) {
    try {/*from   ww  w.  j a  v a2s. c o m*/
        ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
        processBuilder.directory(workingDir);
        Process process = processBuilder.start();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        process.waitFor();
        process.destroy();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:minij.assembler.Assembler.java

public static void assemble(Configuration config, String assembly) throws AssemblerException {

    try {/*from   w w  w  .  j a v a 2 s  . c o  m*/
        new File(FilenameUtils.getPath(config.outputFile)).mkdirs();

        // -xc specifies the input language as C and is required for GCC to read from stdin
        ProcessBuilder processBuilder = new ProcessBuilder("gcc", "-o", config.outputFile, "-m32", "-xc",
                MiniJCompiler.RUNTIME_DIRECTORY.toString() + File.separator + "runtime_32.c", "-m32",
                "-xassembler", "-");
        Process gccCall = processBuilder.start();
        // Write C code to stdin of C Compiler
        OutputStream stdin = gccCall.getOutputStream();
        stdin.write(assembly.getBytes());
        stdin.close();

        gccCall.waitFor();

        // Print error messages of GCC
        if (gccCall.exitValue() != 0) {

            StringBuilder errOutput = new StringBuilder();
            InputStream stderr = gccCall.getErrorStream();
            String line;
            BufferedReader bufferedStderr = new BufferedReader(new InputStreamReader(stderr));
            while ((line = bufferedStderr.readLine()) != null) {
                errOutput.append(line + System.lineSeparator());
            }
            bufferedStderr.close();
            stderr.close();

            throw new AssemblerException(
                    "Failed to compile assembly:" + System.lineSeparator() + errOutput.toString());
        }

        Logger.logVerbosely("Successfully compiled assembly");
    } catch (IOException e) {
        throw new AssemblerException("Failed to transfer assembly to gcc", e);
    } catch (InterruptedException e) {
        throw new AssemblerException("Failed to invoke gcc", e);
    }

}

From source file:ezbake.amino.cli.Main.java

/**
 * A funny hack in order to get the proper terminal width so that we can word wrap properly
 * @return The number of characters wide the terminal is currently.
 *///www. j  a va  2  s  .c o  m
public static int getTerminalWidth() {
    try {
        Process p = Runtime.getRuntime().exec(new String[] { "sh", "-c", "tput cols 2> /dev/tty" });
        p.waitFor();
        return Integer.parseInt(new BufferedReader(new InputStreamReader(p.getInputStream())).readLine());
    } catch (Exception e) {
        logger.error("Error getting terminal width", e);
        return 80;
    }

}

From source file:ca.uqac.info.Job.Launcher.JobLauncher.java

/**
 * Sets up the ProcessBuilder for the bat file and start it
 * @return The exitStatus /*from  w  w  w .j  av a 2 s .  co  m*/
 */
private static int launchJob(String fileBat, String outName, File outFolder) throws Exception {
    // The batch file to execute
    final File batchFile = new File(fileBat);

    // The output file. All activity is written to this file
    final File outputFile = new File(outName);

    // Create the process
    final ProcessBuilder processBuilder = new ProcessBuilder(batchFile.getAbsolutePath(), outName);
    // Redirect any output (including error) to a file. This avoids deadlocks
    // when the buffers get full. 
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectOutput(outputFile);

    // Add a new environment variable
    processBuilder.environment().put("JobLauncher", "Bat File Execution");

    // Set the working directory. The batch file will run as if you are in this
    // directory.
    processBuilder.directory(outFolder);

    // Start the process and wait for it to finish. 
    /* while(nextJob != true)
     {
     //Wait the end of the current Job to Launch the next one
     }
             
     nextJob = false;*/
    final Process process = processBuilder.start();
    final int exitStatus = process.waitFor();
    process.destroy();

    return exitStatus;
}

From source file:io.amient.yarn1.YarnClient.java

private static void executeShell(String command) throws IOException, InterruptedException {
    Process shellProcess = Runtime.getRuntime().exec(command);
    if (shellProcess.waitFor() != 0) {
        throw new IOException("Failed to command: " + command);
    }//from  w w w .j a v  a2  s  .c o  m
}

From source file:myproject.Model.Common.ProcessExecutor.java

private static String properExecute(File file, String... commands) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder(commands);
    if (file != null) {
        builder.directory(file);/*w  w  w.j  av  a 2 s . c o m*/
    }
    Process process = builder.start();
    String input = IOUtils.toString(process.getInputStream(), "utf-8");
    String error = IOUtils.toString(process.getErrorStream(), "utf-8");
    //String command = Arrays.toString(builder.command().toArray(new String[] {}));
    process.waitFor();
    process.getInputStream().close();
    if (!error.isEmpty()) {
        Log.errorLog(error, ProcessExecutor.class);
    }
    String result = input;
    if (input.isEmpty()) {
        result = error;
    }
    return result;
}