Skip to content

Instantly share code, notes, and snippets.

@rgpower
Created June 29, 2021 12:06
Show Gist options
  • Select an option

  • Save rgpower/23bc4b3566f10783aa4e6ece9d5ade7d to your computer and use it in GitHub Desktop.

Select an option

Save rgpower/23bc4b3566f10783aa4e6ece9d5ade7d to your computer and use it in GitHub Desktop.
Wait for Selenium Grid to become available
/**
* Wait for Grid to come online
* @param url to check, e.g. http://127.0.0.1:4444/wd/hub/status
* @param duration value
* @param unit of duration
*/
public static boolean waitForSeleniumGrid(String url, long duration, TemporalUnit unit) throws ExecutionException, InterruptedException {
Instant start = Instant.now();
Instant stopWaiting = start.plus(duration, unit);
final ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
final CompletableFuture<Boolean> cf = new CompletableFuture<>();
final AtomicBoolean success = new AtomicBoolean(false);
final ScheduledFuture<?>[] m = new ScheduledFuture[] { null };
Runnable r = () -> {
Instant now = Instant.now();
long timeLeft = Duration.between(now, stopWaiting).getSeconds();
logger.warning(String.format("waiting for Selenium grid to start... time left=%d seconds", timeLeft));
try {
long elapsed = Duration.between(start, now).getSeconds();
if (stopWaiting.isBefore(Instant.now())) {
cf.completeExceptionally(new Exception(String.format("Could not connect to Selenium Grid after %d seconds", elapsed)));
} else {
URLConnection connection = new URL(url).openConnection();
connection.connect();
Reader content = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);
WDHubStatus hubStatus = new Gson().fromJson(content, WDHubStatus.class);
content.close();
if (0 == hubStatus.status && hubStatus.value.ready) {
m[0].cancel(true);
success.set(true);
cf.complete(true);
}
}
} catch (MalformedURLException e) {
cf.completeExceptionally(e);
} catch(IOException ignored) {
}
};
m[0] = ses.scheduleAtFixedRate(r, 1000, 1000, TimeUnit.MILLISECONDS);
cf.join();
ses.shutdown();
return success.get();
}
private static class WDHubStatusValue {
boolean ready;
String message;
}
private static class WDHubStatus {
long status;
WDHubStatusValue value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment