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:Browser.java

/**
 * Open the specified URL in the client web browser.
 * /*w w w. j  a  v  a 2 s . c om*/
 * @param url  URL to open.
 * @throws     IOException If there is brwoser problem.   
 */
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
        String command = browser.toString() + " -raise " + NETSCAPE_REMOTE_PARAMETER + " "
                + NETSCAPE_OPEN_PARAMETER_START + url + NETSCAPE_OPEN_PARAMETER_END;

        process = Runtime.getRuntime().exec(command);

        try {
            int exitCode = process.waitFor();
            if (exitCode != 0) { // if Netscape was not open
                Runtime.getRuntime().exec(new String[] { (String) browser, url });
            }
        } catch (InterruptedException exception) {
            exception.printStackTrace();
            throw new IOException("InterruptedException while launching browser: " + exception.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:com.netscape.cmstools.cli.HelpCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args);

    String[] cmdArgs = cmd.getArgs();

    String manPage = null;/* w  w  w .  ja  v a  2s .  co  m*/
    if (cmdArgs.length == 0) {
        // no command specified, show the pki man page
        manPage = parent.getManPage();

    } else {
        // find all modules handling the specified command
        List<CLI> modules = parent.findModules(cmdArgs[0]);

        // find the module that has a man page starting from the last one
        for (int i = modules.size() - 1; i >= 0; i--) {
            CLI module = modules.get(i);
            manPage = module.getManPage();
            if (manPage != null)
                break;
        }

        // if no module has a man page, show the pki man page
        if (manPage == null)
            manPage = parent.getManPage();
    }

    while (true) {
        // display man page for the command
        ProcessBuilder pb = new ProcessBuilder("/usr/bin/man", manPage);

        pb.inheritIO();
        Process p = pb.start();
        int rc = p.waitFor();

        if (rc == 16) {
            // man page not found, find the parent command
            int i = manPage.lastIndexOf('-');
            if (i >= 0) {
                // parent command exists, try again
                manPage = manPage.substring(0, i);
                continue;

            } else {
                // parent command not found, stop
                break;
            }

        } else {
            // man page found or there's a different error, stop
            break;
        }
    }
}

From source file:gov.nasa.jpf.symbc.tree.visualizer.DOTVisualizerListener.java

private void convertDotFile(File file, OUTPUT_FORMAT format) throws InterruptedException {
    String dotCmd = "dot " + file.getPath() + " -T" + format.getFormat() + " -o "
            + file.getPath().replace(".dot", "." + format.getFormat());
    try {/* w w  w  .  j av  a 2  s .  c o  m*/
        Process p = Runtime.getRuntime().exec(dotCmd);
        p.waitFor();
        p.exitValue();
        p.destroy();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ape.TouchCommand.java

public boolean runImpl(String[] args) {
    System.out.println("Going to touch /tmp/foo.tst");

    Runtime rt = Runtime.getRuntime();
    Process p;
    try {//  w w w. j a  v a2 s .co  m
        p = rt.exec("touch /tmp/foo.tst");
        p.waitFor();
        p = rt.exec("ls /tmp");
        p.waitFor();
        return writeSTDOut(p);
    } catch (IOException e) {
        System.out.println("IOException caught in executing command.");
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        System.out.println("The process for the 'ls /tmp' command was interrupted.");
        e.printStackTrace();
        return false;
    }
}

From source file:com.yfiton.oauth.receiver.GraphicalReceiver.java

@Override
public AuthorizationData requestAuthorizationData(String authorizationUrl,
        String authorizationCodeParameterName, String... requestParameterNames) throws NotificationException {
    try {//from   ww w  .  j a  v  a  2  s .c o  m
        File tmpFile = File.createTempFile("yfiton", ".auth");

        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.inheritIO();
        processBuilder.command("java",
                //"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005",
                "-classpath", getClasspath(), WebBrowser.class.getName(),
                "--authorization-code-parameter-name=" + authorizationCodeParameterName,
                "--authorization-file=" + tmpFile.getAbsolutePath(), "--authorization-url=" + authorizationUrl,
                "--debug=" + (debug ? "true" : "false"),
                "--webengine-listener-class=" + webEngineListenerClazz.getName());

        Process process = processBuilder.start();

        int returnCode = process.waitFor();

        switch (returnCode) {
        case 0:
            return OAuthUtils.readAuthorizationInfo(tmpFile.toPath());
        case 255:
            throw new NotificationException("Authorization process aborted");
        default:
            throw new NotificationException(
                    "Error occurred while waiting for process: return code " + returnCode);
        }
    } catch (ClassNotFoundException | ConfigurationException | IOException | InterruptedException e) {
        throw new NotificationException(e.getMessage());
    }
}

From source file:ch.unibas.fittingwizard.infrastructure.base.VmdRunner.java

private int run() {
    logger.info("Running vmd:\n" + pb.command() + "\nin directory:\n" + pb.directory() + "\nwith environment:\n"
            + pb.environment());/*from   www.  j  av a 2s . c  o  m*/

    int exitCode = 0;
    try {
        Process p = pb.start();
        exitCode = p.waitFor();
    } catch (Exception e) {
        throw new RuntimeException(String.format("Vmd [%s] failed.", e));
    }
    logger.info("Vmd return value: " + exitCode);
    if (exitCode != 0) {
        throw new ScriptExecutionException(
                String.format("Vmd did not exit correctly. Exit code: %s", String.valueOf(exitCode)));
    }

    return exitCode;
}

From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java

private void execute(File directory, String... cmd) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    Map<String, String> env = pb.environment();
    pb.directory(directory);// w  w w.  jav a  2 s.  com
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = br.readLine()) != null) {
        if (this.log.isInfoEnabled())
            this.log.info(line);
    }
}

From source file:com.codemage.sql.util.SonarQubeManager.java

private String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {//from   w w  w. j  av  a2  s  .c  om
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

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

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}

From source file:io.ballerina.plugins.idea.preloading.TerminatorUnix.java

/**
 * Terminate running ballerina program.//from   w ww.j  ava 2  s  .  c  o m
 *
 * @param pid - process id
 */
public void kill(int pid) {
    //todo need to put aditional validation
    if (pid < 0) {
        return;
    }
    String killCommand = String.format("kill -9 %d", pid);
    try {
        Process kill = Runtime.getRuntime().exec(killCommand);
        kill.waitFor();
    } catch (Throwable e) {
        LOGGER.error("Launcher was unable to terminate process:" + pid + ".");
    }
}

From source file:edu.wisc.doit.tcrypt.TokenEncryptDecryptIT.java

@Test
public void testOpenSSLEncJavaDec() throws Exception {
    //Encrypt with openssl
    final File encryptFileScript = setupTempFile("encryptToken.sh");
    encryptFileScript.setExecutable(true);

    final File publicKey = setupTempFile("my.wisc.edu-public.pem");

    final String expected = "foobar";
    final ProcessBuilder pb = new ProcessBuilder(encryptFileScript.getAbsolutePath(),
            publicKey.getAbsolutePath(), expected);

    final Process p = pb.start();
    final int ret = p.waitFor();
    if (ret != 0) {
        final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pOut);
        final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pErr);
    }//from w ww .ja v  a2s  . c  o  m
    assertEquals(0, ret);

    final String encrypted = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();

    //Decrypt with java
    final String actual = this.tokenDecrypter.decrypt(encrypted);

    //Verify
    assertEquals(expected, actual);
}