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:de.huberlin.wbi.hiway.am.HiWay.java

/**
 * If the debug flag is set, dump out contents of current working directory and the environment to stdout for debugging.
 *//*from ww w  .j  a  v a2s .co m*/
private static void dumpOutDebugInfo() {
    System.out.println("Dump debug output");
    Map<String, String> envs = System.getenv();
    for (Map.Entry<String, String> env : envs.entrySet()) {
        System.out.println("System env: key=" + env.getKey() + ", val=" + env.getValue());
    }

    String cmd = "ls -al";
    Runtime run = Runtime.getRuntime();
    Process pr = null;
    try {
        pr = run.exec(cmd);
        pr.waitFor();

        try (BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()))) {
            String line = "";
            while ((line = buf.readLine()) != null) {
                System.out.println("System CWD content: " + line);
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

/**
 * TODO This does not work. The ./dcmdeleteSeries script invoked the dcm4chee twiddle command but it appears that the
 * moveSeriesToTrash operation it calls has no effect in this version of dcm4chee. See:
 * http://www.dcm4che.org/jira/browse/WEB-955
 *///from w  ww .j  ava  2 s.co m
public static boolean deleteSeries(String seriesUID, String seriesPk) {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    boolean success = false;

    try {
        log.info("Deleting series " + seriesUID + " seriesPK:" + seriesPk);

        String[] command = { "./dcmdeleteSeries", seriesPk, EPADConfig.xnatUploadProjectPassword };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmdeleteSeries");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir();
        script = new File(dicomScriptsDir, "dcmdeleteSeries");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        processBuilder.directory(new File(dicomScriptsDir));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.info("./dcmdeleteSeries: " + line);
        }
        try {
            int exitValue = process.waitFor();
            if (exitValue == 0) {
                log.info("Deleted DICOM series " + seriesUID + " pk:" + seriesPk);
                success = true;
            } else {
                log.warning("Failed to delete DICOM series " + seriesUID + " pk=" + seriesPk + "; exitValue="
                        + exitValue + "\n" + sb.toString());
            }
        } catch (Exception e) {
            log.warning("Failed to delete DICOM series " + seriesUID, e);
        }

        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        }
    } catch (IOException e) {
        log.warning("Failed to delete DICOM series " + seriesUID, e);
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }
    return success;
}

From source file:edu.kit.dama.util.SystemUtils.java

/**
 * Lock a folder in a Unix system. Therefor, the script previously generated
 * by generateScript() is used to lock the provided folder 'pLocalFolder'.
 *
 * @param pLocalScriptFile The lock script.
 * @param pLocalFolder The folder to lock.
 *
 * @return TRUE if the locking succeeded.
 *//*  w w w  .  j a  v  a 2 s  .  c o m*/
private static boolean applyScriptToFolder(String pLocalScriptFile, String... pArguments) {
    BufferedReader brStdOut = null;
    BufferedReader brStdErr = null;
    try {
        String line;
        StringBuilder stdOut = new StringBuilder();
        StringBuilder stdErr = new StringBuilder();

        List<String> cmdArrayList = new ArrayList<>();
        cmdArrayList.add("sh");
        cmdArrayList.add(pLocalScriptFile);
        if (pArguments != null) {
            cmdArrayList.addAll(Arrays.asList(pArguments));
        }

        Process p = Runtime.getRuntime().exec(cmdArrayList.toArray(new String[cmdArrayList.size()]));

        brStdOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
        brStdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((line = brStdOut.readLine()) != null) {
            stdOut.append(line).append("\n");
        }
        brStdOut.close();
        while ((line = brStdErr.readLine()) != null) {
            stdErr.append(line).append("\n");
        }
        brStdErr.close();
        int result = p.waitFor();
        LOGGER.debug("Script finished execution with return code {}", result);
        LOGGER.debug("StdOut: {}", stdOut.toString());
        LOGGER.warn("StdErr: {}", stdErr.toString());
    } catch (IOException err) {
        LOGGER.error("Script execution failed", err);
        return false;
    } catch (InterruptedException err) {
        LOGGER.error("Script execution might have failed", err);
        return false;
    } finally {
        if (brStdErr != null) {
            try {
                brStdErr.close();
            } catch (IOException ex) {
            }
        }
        if (brStdOut != null) {
            try {
                brStdOut.close();
            } catch (IOException ex) {
            }
        }
    }
    return true;
}

From source file:com.moviejukebox.scanner.AttachmentScanner.java

/**
 * Extract an attachment/*w w  w.j  av a  2 s .  com*/
 *
 * @param attachment the attachment to extract
 * @param setImage true, if a set image should be extracted; in this case ".set" is append before file extension
 * @param counter a counter (only used for NFOs cause there may be multiple NFOs in one file)
 * @return
 */
private static File extractAttachment(Attachment attachment) {
    File sourceFile = attachment.getSourceFile();
    if (sourceFile == null) {
        // source file must exist
        return null;
    } else if (!sourceFile.exists()) {
        // source file must exist
        return null;
    }

    // build return file name
    StringBuilder returnFileName = new StringBuilder();
    returnFileName.append(tempDirectory.getAbsolutePath());
    returnFileName.append(File.separatorChar);
    returnFileName.append(FilenameUtils.removeExtension(sourceFile.getName()));
    // add attachment id so the extracted file becomes unique per movie file
    returnFileName.append(".");
    returnFileName.append(attachment.getAttachmentId());

    switch (attachment.getContentType()) {
    case NFO:
        returnFileName.append(".nfo");
        break;
    case POSTER:
    case FANART:
    case BANNER:
    case SET_POSTER:
    case SET_FANART:
    case SET_BANNER:
    case VIDEOIMAGE:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    default:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    }

    File returnFile = new File(returnFileName.toString());
    if (returnFile.exists() && (returnFile.lastModified() >= sourceFile.lastModified())) {
        // already present or extracted
        LOG.debug("File to extract already exists; no extraction needed");
        return returnFile;
    }

    LOG.trace("Extract attachement ({})", attachment);
    try {
        // Create the command line
        List<String> commandMedia = new ArrayList<>(MT_EXTRACT_EXE);
        commandMedia.add("attachments");
        commandMedia.add(sourceFile.getAbsolutePath());
        commandMedia.add(attachment.getAttachmentId() + ":" + returnFileName.toString());

        ProcessBuilder pb = new ProcessBuilder(commandMedia);
        pb.directory(MT_PATH);
        Process p = pb.start();

        if (p.waitFor() != 0) {
            LOG.error("Error during extraction - ErrorCode={}", p.exitValue());
            returnFile = null;
        }
    } catch (IOException | InterruptedException ex) {
        LOG.error(SystemTools.getStackTrace(ex));
        returnFile = null;
    }

    if (returnFile != null) {
        if (returnFile.exists()) {
            // need to reset last modification date to last modification date
            // of source file to fulfill later checks
            try {
                returnFile.setLastModified(sourceFile.lastModified());
            } catch (Exception ignore) {
                // nothing to do anymore
            }
        } else {
            // reset return file to null if not existent
            returnFile = null;
        }
    }
    return returnFile;
}

From source file:fxts.stations.util.BrowserLauncher.java

/**
 * Attempts to open the default web browser to the given URL.
 *
 * @param url The URL to open//from  w w  w. j av a  2 s  .  co m
 *
 * @throws IOException If the web browser could not be located or does not run
 */
public static void openURL(String url) throws IOException {
    if (!loadedWithoutErrors) {
        throw new IOException("Exception in finding browser: " + errorMessage);
    }
    Object browser = locateBrowser();
    if (browser == null) {
        throw new IOException("Unable to locate browser: " + errorMessage);
    }
    switch (jvm) {
    case MRJ_2_0:
        Object aeDesc = null;
        try {
            aeDesc = aeDescConstructor.newInstance(new Object[] { url });
            putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
            sendNoReply.invoke(browser, new Object[] {});
        } catch (InvocationTargetException ite) {
            throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
        } catch (IllegalAccessException iae) {
            throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
        } catch (InstantiationException ie) {
            throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
        } finally {
            aeDesc = null; // Encourage it to get disposed if it was created
            browser = null; // Ditto
        }
        break;
    case MRJ_2_1:
        Runtime.getRuntime().exec(new String[] { (String) browser, url });
        break;
    case MRJ_3_0:
        int[] instance = new int[1];
        int result = ICStart(instance, 0);
        if (result == 0) {
            int[] selectionStart = new int[] { 0 };
            byte[] urlBytes = url.getBytes();
            int[] selectionEnd = new int[] { urlBytes.length };
            result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes, urlBytes.length, selectionStart,
                    selectionEnd);
            if (result == 0) {
                // Ignore the return value; the URL was launched successfully
                // regardless of what happens here.
                ICStop(instance);
            } else {
                throw new IOException("Unable to launch URL: " + result);
            }
        } else {
            throw new IOException("Unable to create an Internet Config instance: " + result);
        }
        break;
    case MRJ_3_1:
        try {
            openURL.invoke(null, new Object[] { url });
        } catch (InvocationTargetException ite) {
            throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
        } catch (IllegalAccessException iae) {
            throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
        }
        break;
    case WINDOWS_NT:
    case WINDOWS_9x:
        // cmd = 'rundll32 url.dll,FileProtocolHandler http://...'
        Process process = Runtime.getRuntime().exec(WIN_PATH + " " + WIN_FLAG + " " + url);
        // This avoids a memory leak on some versions of Java on Windows.
        // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
        try {
            process.waitFor();
            process.exitValue();
        } catch (InterruptedException ie) {
            throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
        }
        break;
    case OTHER:
        // Assume that we're on Unix and that Netscape is installed

        // First, attempt to open the URL in a currently running session of Netscape
        process = Runtime.getRuntime().exec(new String[] { (String) browser, NETSCAPE_REMOTE_PARAMETER,
                NETSCAPE_OPEN_PARAMETER_START + url + NETSCAPE_OPEN_PARAMETER_END });
        try {
            int exitCode = process.waitFor();
            if (exitCode != 0) { // if Netscape was not open
                Runtime.getRuntime().exec(new String[] { (String) browser, url });
            }
        } catch (InterruptedException ie) {
            throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
        }
        break;
    default:
        // This should never occur, but if it does, we'll try the simplest thing possible
        Runtime.getRuntime().exec(new String[] { (String) browser, url });
        break;
    }
}

From source file:edu.cornell.med.icb.R.RUtils.java

/**
 * Can be used to start a rserve instance.
 * @param threadPool The ExecutorService used to start the Rserve process
 * @param rServeCommand Full path to command used to start Rserve process
 * @param host Host where the command should be sent
 * @param port Port number where the command should be sent
 * @param username Username to send to the server if authentication is required
 * @param password Password to send to the server if authentication is required
 * @return The return value from the Rserve instance
 *///  ww w.  j ava 2 s. c om
static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host,
        final int port, final String username, final String password) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Attempting to start Rserve on " + host + ":" + port);
    }

    return threadPool.submit(new Callable<Integer>() {
        public Integer call() throws IOException {
            final List<String> commands = new ArrayList<String>();

            // if the host is not local, use ssh to exec the command
            if (!"localhost".equals(host) && !"127.0.0.1".equals(host)
                    && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) {
                commands.add("ssh");
                commands.add(host);
            }

            // TODO - this will fail when spaces are in the the path to the executable
            CollectionUtils.addAll(commands, rServeCommand.split(" "));
            commands.add("--RS-port");
            commands.add(Integer.toString(port));

            final String[] command = commands.toArray(new String[commands.size()]);
            LOG.debug(ArrayUtils.toString(commands));

            final ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            final Process process = builder.start();
            BufferedReader br = null;
            try {
                final InputStream is = process.getInputStream();
                final InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(host + ":" + port + "> " + line);
                    }
                }

                process.waitFor();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Rserve on " + host + ":" + port + " terminated");
                }
            } catch (InterruptedException e) {
                LOG.error("Interrupted!", e);
                process.destroy();
                Thread.currentThread().interrupt();
            } finally {
                IOUtils.closeQuietly(br);
            }

            final int exitValue = process.exitValue();
            if (LOG.isInfoEnabled()) {
                LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue);
            }
            return exitValue;
        }
    });
}

From source file:com.github.maven_nar.NarUtil.java

public static int runCommand(final String cmd, final String[] args, final File workingDirectory,
        final String[] env, final TextStream out, final TextStream err, final TextStream dbg, final Log log,
        final boolean expectFailure) throws MojoExecutionException, MojoFailureException {
    final Commandline cmdLine = new Commandline();

    try {//  ww  w .  j  a  v a 2  s . co  m
        dbg.println("RunCommand: " + cmd);
        cmdLine.setExecutable(cmd);
        if (args != null) {
            for (final String arg : args) {
                dbg.println("  '" + arg + "'");
            }
            cmdLine.addArguments(args);
        }
        if (workingDirectory != null) {
            dbg.println("in: " + workingDirectory.getPath());
            cmdLine.setWorkingDirectory(workingDirectory);
        }

        if (env != null) {
            dbg.println("with Env:");
            for (final String element : env) {
                final String[] nameValue = element.split("=", 2);
                if (nameValue.length < 2) {
                    throw new MojoFailureException("   Misformed env: '" + element + "'");
                }
                dbg.println("   '" + nameValue[0] + "=" + nameValue[1] + "'");
                cmdLine.addEnvironment(nameValue[0], nameValue[1]);
            }
        }

        final Process process = cmdLine.execute();
        final StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), err);
        final StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), out);

        errorGobbler.start();
        outputGobbler.start();
        process.waitFor();
        final int exitValue = process.exitValue();
        dbg.println("ExitValue: " + exitValue);
        final int timeout = 5000;
        errorGobbler.join(timeout);
        outputGobbler.join(timeout);
        if (exitValue != 0 ^ expectFailure) {
            if (log == null) {
                System.err.println(err.toString());
                System.err.println(out.toString());
                System.err.println(dbg.toString());
            } else {
                log.warn(err.toString());
                log.warn(out.toString());
                log.warn(dbg.toString());
            }
            throw new MojoExecutionException("exit code: " + exitValue);
        }
        return exitValue;
    } catch (final MojoExecutionException e) {
        throw e;
    } catch (final Exception e) {
        throw new MojoExecutionException("Could not launch " + cmdLine, e);
    }
}

From source file:BrowserLauncher.java

/**
 * Attempts to open the default web browser to the given URL.
 * @param url The URL to open//from ww  w. j  a v a 2s.c  o  m
 * @throws IOException If the web browser could not be located or does not run
 */
public static void openURL(String url) throws IOException {
    if (!loadedWithoutErrors) {
        throw new IOException("Exception in finding browser: " + errorMessage);
    }
    Object browser = locateBrowser();
    if (browser == null) {
        throw new IOException("Unable to locate browser: " + errorMessage);
    }

    switch (jvm) {
    case MRJ_2_0:
        Object aeDesc = null;
        try {
            aeDesc = aeDescConstructor.newInstance(new Object[] { url });
            putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
            sendNoReply.invoke(browser, new Object[] {});
        } catch (InvocationTargetException ite) {
            throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
        } catch (IllegalAccessException iae) {
            throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
        } catch (InstantiationException ie) {
            throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
        } finally {
            aeDesc = null; // Encourage it to get disposed if it was created
            browser = null; // Ditto
        }
        break;
    case MRJ_2_1:
        Runtime.getRuntime().exec(new String[] { (String) browser, url });
        break;
    case MRJ_3_0:
        int[] instance = new int[1];
        int result = ICStart(instance, 0);
        if (result == 0) {
            int[] selectionStart = new int[] { 0 };
            byte[] urlBytes = url.getBytes();
            int[] selectionEnd = new int[] { urlBytes.length };
            result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes, urlBytes.length, selectionStart,
                    selectionEnd);
            if (result == 0) {
                // Ignore the return value; the URL was launched successfully
                // regardless of what happens here.
                ICStop(instance);
            } else {
                throw new IOException("Unable to launch URL: " + result);
            }
        } else {
            throw new IOException("Unable to create an Internet Config instance: " + result);
        }
        break;
    case MRJ_3_1:
        try {
            openURL.invoke(null, new Object[] { url });
        } catch (InvocationTargetException ite) {
            throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
        } catch (IllegalAccessException iae) {
            throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
        }
        break;
    case WINDOWS_NT:
    case WINDOWS_9x:
        // Add quotes around the URL to allow ampersands and other special
        // characters to work.
        Process process = Runtime.getRuntime().exec(new String[] { (String) browser, FIRST_WINDOWS_PARAMETER,
                SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER, '"' + url + '"' });
        // This avoids a memory leak on some versions of Java on Windows.
        // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
        try {
            process.waitFor();
            process.exitValue();
        } catch (InterruptedException ie) {
            throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
        }
        break;
    case OTHER:
        // Assume that we're on Unix and that Netscape is installed

        // First, attempt to open the URL in a currently running session of Netscape
        process = Runtime.getRuntime().exec(new String[] { (String) browser, NETSCAPE_REMOTE_PARAMETER,
                NETSCAPE_OPEN_PARAMETER_START + url + NETSCAPE_OPEN_PARAMETER_END });
        try {
            int exitCode = process.waitFor();
            if (exitCode != 0) { // if Netscape was not open
                Runtime.getRuntime().exec(new String[] { (String) browser, url });
            }
        } catch (InterruptedException ie) {
            throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
        }
        break;
    default:
        // This should never occur, but if it does, we'll try the simplest thing possible
        Runtime.getRuntime().exec(new String[] { (String) browser, url });
        break;
    }
}

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

private static void link(File something, File somewhere) throws IOException, InterruptedException {
    Process process = Runtime.getRuntime()
            .exec(new String[] { "ln", something.getAbsolutePath(), somewhere.getAbsolutePath() }, null, null); //$NON-NLS-1$
    process.waitFor();
}

From source file:de.ub0r.android.wifibarcode.WifiBarcodeActivity.java

/**
 * Run command as root.//from   ww w . ja  v  a 2 s. c om
 *
 * @param command command
 * @return true, if command was successfully executed
 */
private static boolean runAsRoot(final String command) {
    Log.i(TAG, "running command as root: ", command);
    try {
        Runtime r = Runtime.getRuntime();
        Process p = r.exec("su");
        DataOutputStream d = new DataOutputStream(p.getOutputStream());
        d.writeBytes(command);
        d.writeBytes("\nexit\n");
        d.flush();
        int retval = p.waitFor();
        Log.i(TAG, "done");
        return (retval == 0);
    } catch (Exception e) {
        Log.e(TAG, "runAsRoot", e);
        return false;
    }
}