Best Selenium code snippet using org.openqa.selenium.HealthCheckFailedException
Source:LocalDistributor.java
...31import net.jodah.failsafe.Failsafe;32import net.jodah.failsafe.RetryPolicy;33import org.openqa.selenium.Beta;34import org.openqa.selenium.Capabilities;35import org.openqa.selenium.HealthCheckFailedException;36import org.openqa.selenium.ImmutableCapabilities;37import org.openqa.selenium.RetrySessionRequestException;38import org.openqa.selenium.SessionNotCreatedException;39import org.openqa.selenium.WebDriverException;40import org.openqa.selenium.concurrent.GuardedRunnable;41import org.openqa.selenium.events.EventBus;42import org.openqa.selenium.grid.config.Config;43import org.openqa.selenium.grid.data.Availability;44import org.openqa.selenium.grid.data.CreateSessionRequest;45import org.openqa.selenium.grid.data.CreateSessionResponse;46import org.openqa.selenium.grid.data.DistributorStatus;47import org.openqa.selenium.grid.data.NodeAddedEvent;48import org.openqa.selenium.grid.data.NodeDrainComplete;49import org.openqa.selenium.grid.data.NodeHeartBeatEvent;50import org.openqa.selenium.grid.data.NodeId;51import org.openqa.selenium.grid.data.NodeRemovedEvent;52import org.openqa.selenium.grid.data.NodeStatus;53import org.openqa.selenium.grid.data.NodeStatusEvent;54import org.openqa.selenium.grid.data.RequestId;55import org.openqa.selenium.grid.data.SessionRequest;56import org.openqa.selenium.grid.data.SessionRequestCapability;57import org.openqa.selenium.grid.data.Slot;58import org.openqa.selenium.grid.data.SlotId;59import org.openqa.selenium.grid.data.TraceSessionRequest;60import org.openqa.selenium.grid.distributor.Distributor;61import org.openqa.selenium.grid.distributor.GridModel;62import org.openqa.selenium.grid.distributor.config.DistributorOptions;63import org.openqa.selenium.grid.distributor.selector.SlotSelector;64import org.openqa.selenium.grid.log.LoggingOptions;65import org.openqa.selenium.grid.node.HealthCheck;66import org.openqa.selenium.grid.node.Node;67import org.openqa.selenium.grid.node.remote.RemoteNode;68import org.openqa.selenium.grid.security.Secret;69import org.openqa.selenium.grid.security.SecretOptions;70import org.openqa.selenium.grid.server.EventBusOptions;71import org.openqa.selenium.grid.server.NetworkOptions;72import org.openqa.selenium.grid.sessionmap.SessionMap;73import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;74import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;75import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;76import org.openqa.selenium.internal.Debug;77import org.openqa.selenium.internal.Either;78import org.openqa.selenium.internal.Require;79import org.openqa.selenium.remote.SessionId;80import org.openqa.selenium.remote.http.HttpClient;81import org.openqa.selenium.remote.tracing.AttributeKey;82import org.openqa.selenium.remote.tracing.EventAttribute;83import org.openqa.selenium.remote.tracing.EventAttributeValue;84import org.openqa.selenium.remote.tracing.Span;85import org.openqa.selenium.remote.tracing.Status;86import org.openqa.selenium.remote.tracing.Tracer;87import org.openqa.selenium.status.HasReadyState;88import java.io.Closeable;89import java.io.UncheckedIOException;90import java.net.URI;91import java.time.Duration;92import java.util.ArrayList;93import java.util.Collection;94import java.util.HashMap;95import java.util.List;96import java.util.Map;97import java.util.Optional;98import java.util.Set;99import java.util.concurrent.ConcurrentHashMap;100import java.util.concurrent.Executor;101import java.util.concurrent.Executors;102import java.util.concurrent.ScheduledExecutorService;103import java.util.concurrent.TimeUnit;104import java.util.concurrent.locks.Lock;105import java.util.concurrent.locks.ReadWriteLock;106import java.util.concurrent.locks.ReentrantReadWriteLock;107import java.util.logging.Level;108import java.util.logging.Logger;109import java.util.stream.Collectors;110public class LocalDistributor extends Distributor implements Closeable {111 private static final Logger LOG = Logger.getLogger(LocalDistributor.class.getName());112 private final Tracer tracer;113 private final EventBus bus;114 private final HttpClient.Factory clientFactory;115 private final SessionMap sessions;116 private final SlotSelector slotSelector;117 private final Secret registrationSecret;118 private final Map<NodeId, Runnable> allChecks = new HashMap<>();119 private final Duration healthcheckInterval;120 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);121 private final GridModel model;122 private final Map<NodeId, Node> nodes;123 private final ScheduledExecutorService newSessionService =124 Executors.newSingleThreadScheduledExecutor(125 r -> {126 Thread thread = new Thread(r);127 thread.setDaemon(true);128 thread.setName("Local Distributor - New Session Queue");129 return thread;130 });131 private final ScheduledExecutorService purgeDeadNodesService =132 Executors.newSingleThreadScheduledExecutor(133 r -> {134 Thread thread = new Thread(r);135 thread.setDaemon(true);136 thread.setName("Local Distributor - Purge Dead Nodes");137 return thread;138 });139 private final ScheduledExecutorService nodeHealthCheckService =140 Executors.newSingleThreadScheduledExecutor(141 r -> {142 Thread thread = new Thread(r);143 thread.setDaemon(true);144 thread.setName("Local Distributor - Node Health Check");145 return thread;146 });147 private final Executor sessionCreatorExecutor = Executors.newFixedThreadPool(148 Runtime.getRuntime().availableProcessors(),149 r -> {150 Thread thread = new Thread(r);151 thread.setName("Local Distributor - Session Creation");152 thread.setDaemon(true);153 return thread;154 }155 );156 private final NewSessionQueue sessionQueue;157 private final boolean rejectUnsupportedCaps;158 public LocalDistributor(159 Tracer tracer,160 EventBus bus,161 HttpClient.Factory clientFactory,162 SessionMap sessions,163 NewSessionQueue sessionQueue,164 SlotSelector slotSelector,165 Secret registrationSecret,166 Duration healthcheckInterval,167 boolean rejectUnsupportedCaps,168 Duration sessionRequestRetryInterval) {169 super(tracer, clientFactory, registrationSecret);170 this.tracer = Require.nonNull("Tracer", tracer);171 this.bus = Require.nonNull("Event bus", bus);172 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);173 this.sessions = Require.nonNull("Session map", sessions);174 this.sessionQueue = Require.nonNull("New Session Request Queue", sessionQueue);175 this.slotSelector = Require.nonNull("Slot selector", slotSelector);176 this.registrationSecret = Require.nonNull("Registration secret", registrationSecret);177 this.healthcheckInterval = Require.nonNull("Health check interval", healthcheckInterval);178 this.model = new GridModel(bus);179 this.nodes = new ConcurrentHashMap<>();180 this.rejectUnsupportedCaps = rejectUnsupportedCaps;181 Require.nonNull("Session request interval", sessionRequestRetryInterval);182 bus.addListener(NodeStatusEvent.listener(this::register));183 bus.addListener(NodeStatusEvent.listener(model::refresh));184 bus.addListener(NodeRemovedEvent.listener(nodeStatus -> remove(nodeStatus.getNodeId())));185 bus.addListener(NodeHeartBeatEvent.listener(nodeStatus -> {186 if (nodes.containsKey(nodeStatus.getNodeId())) {187 model.touch(nodeStatus.getNodeId());188 } else {189 register(nodeStatus);190 }191 }));192 NewSessionRunnable newSessionRunnable = new NewSessionRunnable();193 bus.addListener(NodeDrainComplete.listener(this::remove));194 purgeDeadNodesService.scheduleAtFixedRate(195 GuardedRunnable.guard(model::purgeDeadNodes), 30, 30, TimeUnit.SECONDS);196 nodeHealthCheckService.scheduleAtFixedRate(197 runNodeHealthChecks(),198 this.healthcheckInterval.toMillis(),199 this.healthcheckInterval.toMillis(),200 TimeUnit.MILLISECONDS);201 // if sessionRequestRetryInterval is 0, we will schedule session creation every 10 millis202 long period = sessionRequestRetryInterval.isZero() ?203 10 : sessionRequestRetryInterval.toMillis();204 newSessionService.scheduleAtFixedRate(205 GuardedRunnable.guard(newSessionRunnable),206 sessionRequestRetryInterval.toMillis(),207 period,208 TimeUnit.MILLISECONDS209 );210 }211 public static Distributor create(Config config) {212 Tracer tracer = new LoggingOptions(config).getTracer();213 EventBus bus = new EventBusOptions(config).getEventBus();214 DistributorOptions distributorOptions = new DistributorOptions(config);215 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);216 SessionMap sessions = new SessionMapOptions(config).getSessionMap();217 SecretOptions secretOptions = new SecretOptions(config);218 NewSessionQueueOptions newSessionQueueOptions = new NewSessionQueueOptions(config);219 NewSessionQueue sessionQueue = newSessionQueueOptions.getSessionQueue(220 "org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue");221 return new LocalDistributor(222 tracer,223 bus,224 clientFactory,225 sessions,226 sessionQueue,227 distributorOptions.getSlotSelector(),228 secretOptions.getRegistrationSecret(),229 distributorOptions.getHealthCheckInterval(),230 distributorOptions.shouldRejectUnsupportedCaps(),231 newSessionQueueOptions.getSessionRequestRetryInterval());232 }233 @Override234 public boolean isReady() {235 try {236 return ImmutableSet.of(bus, sessions).parallelStream()237 .map(HasReadyState::isReady)238 .reduce(true, Boolean::logicalAnd);239 } catch (RuntimeException e) {240 return false;241 }242 }243 private void register(NodeStatus status) {244 Require.nonNull("Node", status);245 Lock writeLock = lock.writeLock();246 writeLock.lock();247 try {248 if (nodes.containsKey(status.getNodeId())) {249 return;250 }251 Set<Capabilities> capabilities = status.getSlots().stream()252 .map(Slot::getStereotype)253 .map(ImmutableCapabilities::copyOf)254 .collect(toImmutableSet());255 // A new node! Add this as a remote node, since we've not called add256 RemoteNode remoteNode = new RemoteNode(257 tracer,258 clientFactory,259 status.getNodeId(),260 status.getExternalUri(),261 registrationSecret,262 capabilities);263 add(remoteNode);264 } finally {265 writeLock.unlock();266 }267 }268 @Override269 public LocalDistributor add(Node node) {270 Require.nonNull("Node", node);271 // An exception occurs if Node heartbeat has started but the server is not ready.272 // Unhandled exception blocks the event-bus thread from processing any event henceforth.273 NodeStatus initialNodeStatus;274 try {275 initialNodeStatus = node.getStatus();276 model.add(initialNodeStatus);277 nodes.put(node.getId(), node);278 } catch (Exception e) {279 LOG.log(280 Debug.getDebugLogLevel(),281 String.format("Exception while adding Node %s", node.getUri()),282 e);283 return this;284 }285 // Extract the health check286 Runnable healthCheck = asRunnableHealthCheck(node);287 allChecks.put(node.getId(), healthCheck);288 updateNodeStatus(initialNodeStatus, healthCheck);289 LOG.info(String.format(290 "Added node %s at %s. Health check every %ss",291 node.getId(),292 node.getUri(),293 healthcheckInterval.toMillis() / 1000));294 bus.fire(new NodeAddedEvent(node.getId()));295 return this;296 }297 private void updateNodeStatus(NodeStatus status, Runnable healthCheck) {298 // Setting the Node as available if the initial call to status was successful.299 // Otherwise, retry to have it available as soon as possible.300 if (status.getAvailability() == UP) {301 updateNodeAvailability(status.getExternalUri(), status.getNodeId(), status.getAvailability());302 } else {303 // Running the health check right after the Node registers itself. We retry the304 // execution because the Node might on a complex network topology. For example,305 // Kubernetes pods with IPs that take a while before they are reachable.306 RetryPolicy<Object> initialHealthCheckPolicy = new RetryPolicy<>()307 .withMaxAttempts(-1)308 .withMaxDuration(Duration.ofSeconds(90))309 .withDelay(Duration.ofSeconds(15))310 .abortIf(result -> true);311 LOG.log(getDebugLogLevel(), "Running health check for Node " + status.getExternalUri());312 Executors.newSingleThreadExecutor().submit(313 () -> Failsafe.with(initialHealthCheckPolicy).run(healthCheck::run));314 }315 }316 private Runnable runNodeHealthChecks() {317 return () -> {318 ImmutableMap<NodeId, Runnable> nodeHealthChecks = ImmutableMap.copyOf(allChecks);319 for (Runnable nodeHealthCheck : nodeHealthChecks.values()) {320 GuardedRunnable.guard(nodeHealthCheck).run();321 }322 };323 }324 private Runnable asRunnableHealthCheck(Node node) {325 HealthCheck healthCheck = node.getHealthCheck();326 NodeId id = node.getId();327 return () -> {328 boolean checkFailed = false;329 Exception failedCheckException = null;330 LOG.log(getDebugLogLevel(), "Running health check for " + node.getUri());331 HealthCheck.Result result;332 try {333 result = healthCheck.check();334 } catch (Exception e) {335 LOG.log(Level.WARNING, "Unable to process node " + id, e);336 result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");337 checkFailed = true;338 failedCheckException = e;339 }340 updateNodeAvailability(node.getUri(), id, result.getAvailability());341 if (checkFailed) {342 throw new HealthCheckFailedException("Node " + id, failedCheckException);343 }344 };345 }346 private void updateNodeAvailability(URI nodeUri, NodeId id, Availability availability) {347 Lock writeLock = lock.writeLock();348 writeLock.lock();349 try {350 LOG.log(351 getDebugLogLevel(),352 String.format("Health check result for %s was %s", nodeUri, availability));353 model.setAvailability(id, availability);354 model.updateHealthCheckCount(id, availability);355 } finally {356 writeLock.unlock();...
Source:HealthCheckFailedException.java
...17package org.openqa.selenium;18/**19 * Indicates that a Node health check failed.20 */21public class HealthCheckFailedException extends WebDriverException {22 public HealthCheckFailedException(String msg, Throwable cause) {23 super(msg, cause);24 }25}...
HealthCheckFailedException
Using AI Code Generation
1package com.seleniumeasy.demo;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.support.ui.Select;7import org.testng.Assert;8import org.testng.annotations.AfterTest;9import org.testng.annotations.BeforeTest;10import org.testng.annotations.Test;11public class FirstTestNGFile {12 WebDriver driver;13 public void launchBrowser() {14 System.setProperty("webdriver.chrome.driver", "/Users/rajeshkumar/Downloads/chromedriver");15 driver = new ChromeDriver();16 driver.manage().window().maximize();17 }18 public void test() {19 WebElement sum1 = driver.findElement(By.id("sum1"));20 sum1.sendKeys("10");21 WebElement sum2 = driver.findElement(By.id("sum2"));22 sum2.sendKeys("20");23 getTotal.click();24 WebElement displayValue = driver.findElement(By.id("displayvalue"));25 String text = displayValue.getText();26 Assert.assertEquals(text, "30");27 }28 public void test2() {29 simpleFormDemo.click();30 WebElement message = driver.findElement(By.id("user-message"));31 message.sendKeys("Hello World");32 showMessage.click();33 WebElement displayMessage = driver.findElement(By.id("display"));34 String text = displayMessage.getText();35 Assert.assertEquals(text, "Hello World");36 }37 public void test3() {38 twoInputFormDemo.click();39 WebElement valueA = driver.findElement(By.id("sum1"));40 valueA.sendKeys("10");41 WebElement valueB = driver.findElement(By.id("sum2"));42 valueB.sendKeys("20");43 getTotal.click();44 WebElement displayValue = driver.findElement(By.id("displayvalue"));45 String text = displayValue.getText();
HealthCheckFailedException
Using AI Code Generation
1import org.openqa.selenium.HealthCheckFailedException;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.chrome.ChromeOptions;5public class ChromeDriverTest {6 public static void main(String[] args) {7 ChromeOptions options = new ChromeOptions();8 options.addArguments("--disable-notifications");9 options.setExperimentalOption("excludeSwitches", new String[] {"enable-automation"});10 options.setBinary("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");11 WebDriver driver = new ChromeDriver(options);12 System.out.println("Successfully opened the website www.google.com");13 driver.quit();14 }15}16import org.openqa.selenium.HealthCheckFailedException;17import org.openqa.selenium.WebDriver;18import org.openqa.selenium.chrome.ChromeDriver;19import org.openqa.selenium.chrome.ChromeOptions;20public class ChromeDriverTest {21 public static void main(String[] args) {22 ChromeOptions options = new ChromeOptions();23 options.addArguments("--disable-notifications");24 options.setExperimentalOption("excludeSwitches", new String[] {"enable-automation"});25 options.setBinary("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");26 WebDriver driver = new ChromeDriver(options);27 System.out.println("Successfully opened the website
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!!