Best Selenium code snippet using org.openqa.selenium.os.CommandLine.waitFor
Source:FirefoxBinary.java  
...245  /**246   * Waits for the process to execute, returning the command output taken from the profile's247   * execution.248   */249  public void waitFor() {250    process.waitFor();251  }252  /**253   * Waits for the process to execute, returning the command output taken from the profile's254   * execution.255   *256   * @param timeout the maximum time to wait in milliseconds257   */258  public void waitFor(long timeout) {259	  process.waitFor(timeout);260  }261  /**262   * Gets all console output of the binary. Output retrieval is non-destructive and non-blocking.263   *264   * @return the console output of the executed binary.265   */266  public String getConsoleOutput() {267    if (process == null) {268      return null;269    }270    return process.getStdOut();271  }272  public long getTimeout() {273    return timeout;...Source:OsProcess.java  
...90        : new MultiOutputStream(inputOut, drainTo);91  }92  public int destroy() {93    SeleniumWatchDog watchdog = executeWatchdog;94    watchdog.waitForProcessStarted();95    // I literally have no idea why we don't try and kill the process nicely on Windows. If you do,96    // answers on the back of a postcard to SeleniumHQ, please.97    if (!thisIsWindows()) {98      watchdog.destroyProcess();99      watchdog.waitForTerminationAfterDestroy(2, SECONDS);100    }101    if (isRunning()) {102      watchdog.destroyHarder();103      watchdog.waitForTerminationAfterDestroy(1, SECONDS);104    }105    // Make a best effort to drain the streams.106    if (streamHandler != null) {107      // Stop trying to read the output stream so that we don't race with the stream being closed108      // when the process is destroyed.109      streamHandler.setStopTimeout(2000);110      try {111        streamHandler.stop();112      } catch (IOException e) {113        // Ignore and destroy the process anyway.114        log.log(115            Level.INFO,116            "Unable to drain process streams. Ignoring but the exception being swallowed follows.",117            e);118      }119    }120    if (!isRunning()) {121      return getExitCode();122    }123    log.severe(String.format("Unable to kill process %s", watchdog.process));124    int exitCode = -1;125    executor.setExitValue(exitCode);126    return exitCode;127  }128  public void waitFor() throws InterruptedException {129    handler.waitFor();130  }131  public void waitFor(long timeout) throws InterruptedException {132    long until = System.currentTimeMillis() + timeout;133    boolean timedOut = true;134    while (System.currentTimeMillis() < until) {135      if (handler.hasResult()) {136        timedOut = false;137        break;138      }139      Thread.sleep(50);140    }141    if (timedOut) {142      throw new InterruptedException(143          String.format("Process timed out after waiting for %d ms.", timeout));144    }145    // Wait until syserr and sysout have been read146  }147  public boolean isRunning() {148    return !handler.hasResult();149  }150  public int getExitCode() {151    if (isRunning()) {152      throw new IllegalStateException(153          "Cannot get exit code before executing command line: " + cl);154    }155    return handler.getExitValue();156  }157  public void checkForError() {158    if (handler.getException() != null) {159      log.severe(handler.getException().toString());160    }161  }162  public String getStdOut() {163    return inputOut.toString();164  }165  public void setInput(String allInput) {166    this.allInput = allInput;167  }168  public void setWorkingDirectory(File workingDirectory) {169    executor.setWorkingDirectory(workingDirectory);170  }171  @Override172  public String toString() {173    return cl.toString() + "[ " + env + "]";174  }175  public void copyOutputTo(OutputStream out) {176    drainTo = out;177  }178  class SeleniumWatchDog extends ExecuteWatchdog {179    private volatile Process process;180    private volatile boolean starting = true;181    SeleniumWatchDog(long timeout) {182      super(timeout);183    }184    @Override185    public synchronized void start(Process process) {186      this.process = process;187      starting = false;188      super.start(process);189    }190    public void reset() {191      starting = true;192    }193    private void waitForProcessStarted() {194      while (starting) {195        try {196          Thread.sleep(50);197        } catch (InterruptedException e) {198          throw new WebDriverException(e);199        }200      }201    }202    private void waitForTerminationAfterDestroy(int duration, TimeUnit unit) {203      long end = System.currentTimeMillis() + unit.toMillis(duration);204      while (isRunning() && System.currentTimeMillis() < end) {205        try {206          Thread.sleep(50);207        } catch (InterruptedException e) {208          throw new WebDriverException(e);209        }210      }211    }212    private void destroyHarder() {213      try {214        Process awaitFor = this.process.destroyForcibly();215        awaitFor.waitFor(10, SECONDS);216      } catch (InterruptedException e) {217        Thread.interrupted();218        throw new RuntimeException(e);219      }220    }221  }222}...Source:ProcessUtils.java  
...34   * @param p The process to kill.35   * @param timeout How long to wait in milliseconds.36   * @return The exit code of the given process.37   */38  private static int waitForProcessDeath(Process p, long timeout) {39    ProcessWaiter pw = new ProcessWaiter(p);40    Thread waiter = new Thread(pw);  // Thread safety reviewed41    waiter.start();42    try {43      waiter.join(timeout);44    } catch (InterruptedException e) {45      throw new RuntimeException("Bug? Main interrupted while waiting for process", e);46    }47    if (waiter.isAlive()) {48      waiter.interrupt();49    }50    try {51      waiter.join();52    } catch (InterruptedException e) {53      throw new RuntimeException("Bug? Main interrupted while waiting for dead process waiter", e);54    }55    InterruptedException ie = pw.getException();56    if (ie != null) {57      throw new ProcessStillAliveException("Timeout waiting for process to die", ie);58    }59    return p.exitValue();60  }61  /**62   * Forcibly kills a process, using OS tools like "kill" as a last resort63   *64   * @param process The process to kill.65   * @return The exit value of the process.66   */67  public static int killProcess(Process process) {68    if (thisIsWindows()) {69      return killWinProcess(process);70    }71    return killUnixProcess(process);72  }73  private static int killUnixProcess(Process process) {74    int exitValue;75    // first, wait a second to see if the process will die on it's own (we will likely have asked76    // the process to kill itself just before calling this method77    try {78      exitValue = waitForProcessDeath(process, 1000);79      closeAllStreamsAndDestroyProcess( process);80      if (exitValue == 0) {81        return exitValue;82      }83    } catch (Exception e) {84      // no? ok, no biggie, now let's force kill it...85    }86    process.destroy();87    try {88      exitValue = waitForProcessDeath(process, 10000);89      closeAllStreamsAndDestroyProcess( process);90    } catch (ProcessStillAliveException ex) {91      if (Platform.getCurrent().is(Platform.WINDOWS)) {92        throw ex;93      }94      try {95        LOG.info("Process didn't die after 10 seconds");96        kill9(process);97        exitValue = waitForProcessDeath(process, 10000);98        closeAllStreamsAndDestroyProcess( process);99      } catch (Exception e) {100        LOG.log(Level.WARNING, "Process refused to die after 10 seconds, and couldn't kill9 it", ex);101        throw new RuntimeException(102            "Process refused to die after 10 seconds, and couldn't kill9 it: " + e.getMessage(),103            ex);104      }105    }106    return exitValue;107  }108  private static int killWinProcess(Process process) {109    int exitValue;110    try {111      killPID("" + getProcessId(process));112      exitValue = waitForProcessDeath(process, 10000);113    } catch (Exception ex) {114      LOG.log(Level.WARNING, "Process refused to die after 10 seconds, and couldn't taskkill it", ex);115      throw new RuntimeException(116          "Process refused to die after 10 seconds, and couldn't taskkill it: " + ex.getMessage(),117          ex);118    }119    return exitValue;120  }121  private static class ProcessWaiter implements Runnable {122    private volatile InterruptedException t;123    private final Process p;124    public ProcessWaiter(Process p) {125      this.p = p;126    }127    public InterruptedException getException() {128      return t;129    }130    public void run() {131      try {132        p.waitFor();133      } catch (InterruptedException e) {134        this.t = e;135      }136    }137  }138  public static class ProcessStillAliveException extends RuntimeException {139    public ProcessStillAliveException(String message, Throwable cause) {140      super(message, cause);141    }142  }143  private static void closeAllStreamsAndDestroyProcess(Process process) {144    try {145      Closeables.close(process.getInputStream(), true);146      Closeables.close(process.getErrorStream(), true);...Source:CommandLineTest.java  
...71  @Test72  public void executeWaitsForProcessFinish() throws InterruptedException {73    commandLine.execute();74    verify(process).executeAsync();75    verify(process).waitFor();76    verifyNoMoreInteractions(process);77  }78  @Test79  public void testDestroy() {80    commandLine.executeAsync();81    verify(process).executeAsync();82    assertThat(commandLine.isRunning()).isTrue();83    verify(process).isRunning();84    commandLine.destroy();85    verify(process).destroy();86    assertThat(commandLine.isRunning()).isFalse();87    verify(process, atLeastOnce()).isRunning();88  }89  @Test...Source:CommandLine.java  
...76  }77  78  public void execute() {79    executeAsync();80    waitFor();81  }82  83  public void waitFor() {84    try {85      process.waitFor();86    } catch (InterruptedException e) {87      throw new WebDriverException(e);88    }89  }90  91  public void waitFor(long timeout) {92    try {93      process.waitFor(timeout);94    } catch (InterruptedException e) {95      throw new WebDriverException(e);96    }97  }98  99  public boolean isSuccessful() {100    return 0 == getExitCode();101  }102  103  public int getExitCode() {104    return process.getExitCode();105  }106  107  public String getStdOut() {...Source:SeleniumServerStarter.java  
...11import org.openqa.selenium.net.PortProber;12import org.openqa.selenium.net.NetworkUtils;1314import static java.util.concurrent.TimeUnit.*;15import static org.openqa.selenium.TestWaiter.waitFor;16import static org.openqa.selenium.net.PortProber.freeLocalPort;17import static org.openqa.selenium.net.PortProber.pollPort;1819@SuppressWarnings({"UnusedDeclaration"})20public class SeleniumServerStarter extends TestSetup {2122  private static final NetworkUtils networkUtils = new NetworkUtils();23  private static final String SELENIUM_JAR = "build/java/server/test/org/openqa/selenium/server-with-tests-standalone.jar";24  private CommandLine command;2526  public SeleniumServerStarter(Test test) {27    super(test);28  }2930  @Override31  protected void setUp() throws Exception {32    // Walk up the path until we find the "third_party/selenium" directory33    File seleniumJar = findSeleniumJar();3435    if (!seleniumJar.exists()) {36      new Build().of("//java/server/test/org/openqa/selenium:server-with-tests:uber").go();37      if (!seleniumJar.exists()) {38        throw new IllegalStateException("Cannot locate selenium jar");39      }40    }4142    String port = startSeleniumServer(seleniumJar);4344    // Wait until the server process is running (port 4444)45    if (!pollPort(Integer.valueOf(port))) {46      throw new RuntimeException("Unable to start selenium server");47    }4849    super.setUp();50  }5152  @SuppressWarnings({"UseOfSystemOutOrSystemErr"})53  private String startSeleniumServer(File seleniumJar) throws IOException {5455    final String port = getPortString();56    command = new CommandLine("java", "-jar", seleniumJar.getAbsolutePath(), "-port", port);57    if (Boolean.getBoolean("webdriver.debug")) {58      command.copyOutputTo(System.err);59    }60    command.executeAsync();6162    PortProber.pollPort(getPort(port));6364    return port;65  }6667  private int getPort(String portString) {68    return Integer.parseInt(portString);69  }7071  private String getPortString() {72    return System.getProperty("webdriver.selenium.server.port", "5555");73  }7475  private File findSeleniumJar() {76    File dir = new File(".");77    File seleniumJar = null;78    while (dir != null) {79      seleniumJar = new File(dir, SELENIUM_JAR);80      if (seleniumJar.exists()) {81        break;82      }83      dir = dir.getParentFile();84    }85    return seleniumJar;86  }8788  @Override89  protected void tearDown() throws Exception {90    if (command != null) {91      command.destroy();92    }9394    waitFor(freeLocalPort(getPort(getPortString())), 10, SECONDS);95    super.tearDown();96  }97}
...waitFor
Using AI Code Generation
1import org.openqa.selenium.os.CommandLine;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.firefox.FirefoxDriver;4public class WaitFor {5    public static void main(String[] args) {6        CommandLine command = new CommandLine("C:\\Program Files\\Java\\jdk1.7.0_07\\bin\\java.exe", "-jar", "C:\\selenium\\selenium-server-standalone-2.32.0.jar");7        command.copyOutputTo(System.out);8        command.executeAsync();9        command.waitFor();10        WebDriver driver = new FirefoxDriver();11        driver.quit();12        command.destroy();13    }14}waitFor
Using AI Code Generation
1import org.openqa.selenium.os.CommandLine;2import org.openqa.selenium.os.WindowsUtils;3import org.openqa.selenium.os.CommandLine;4import org.openqa.selenium.os.WindowsUtils;5CommandLine commandLine = new CommandLine("cmd");6commandLine.execute("sleep 5");7WindowsUtils.tryToKillByName("sleep");8WindowsUtils.killByName("sleep");9WindowsUtils.killByName("sleep", 5);waitFor
Using AI Code Generation
1import org.openqa.selenium.os.CommandLine;2public class WaitForProcessTermination {3    public static void main(String[] args) {4        CommandLine cmd = new CommandLine("notepad.exe");5        cmd.execute();6        cmd.waitFor(20, java.util.concurrent.TimeUnit.SECONDS);7        cmd.destroy();8    }9}waitFor
Using AI Code Generation
1CommandLine commandLine = new CommandLine("cmd");2commandLine.addArgument("/c");3commandLine.addArgument("dir");4commandLine.addArgument("C:\\");5commandLine.executeAsync();6commandLine.waitFor();7CommandLine commandLine = new CommandLine("cmd");8commandLine.addArgument("/c");9commandLine.addArgument("dir");10commandLine.addArgument("C:\\");11commandLine.execute();12commandLine.waitFor();13CommandLine commandLine = new CommandLine("cmd");14commandLine.addArgument("/c");15commandLine.addArgument("dir");16commandLine.executeAsync();17commandLine.waitFor();18CommandLine commandLine = new CommandLine("cmd");19commandLine.addArgument("/c");20commandLine.addArgument("dir");21commandLine.execute();22commandLine.waitFor();23CommandLine commandLine = new CommandLine("cmd");24commandLine.addArgument("/c");25commandLine.addArgument("dir");26commandLine.addArgument("C:\\");27commandLine.executeAsync();28commandLine.waitFor(10000);29CommandLine commandLine = new CommandLine("cmd");30commandLine.addArgument("/c");31commandLine.addArgument("dir");32commandLine.addArgument("C:\\");33commandLine.execute();34commandLine.waitFor(10000);35CommandLine commandLine = new CommandLine("cmd");36commandLine.addArgument("/c");37commandLine.addArgument("dir");38commandLine.executeAsync();39commandLine.waitFor(10000);40CommandLine commandLine = new CommandLine("cmd");41commandLine.addArgument("/c");42commandLine.addArgument("dir");LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
