Best Selenium code snippet using org.openqa.selenium.grid.node.Node.isSupporting
Source:OneShotNode.java  
...115    Capabilities stereotype = new ImmutableCapabilities(raw);116    Optional<String> driverName = config.get("k8s", "driver_name").map(String::toLowerCase);117    // Find the webdriver info corresponding to the driver name118    WebDriverInfo driverInfo = StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false)119      .filter(info -> info.isSupporting(stereotype))120      .filter(info -> driverName.map(name -> name.equals(info.getDisplayName().toLowerCase())).orElse(true))121      .findFirst()122      .orElseThrow(() -> new ConfigException(123        "Unable to find matching driver for %s and %s", stereotype, driverName.orElse("any driver")));124    LOG.info(String.format("Creating one-shot node for %s with stereotype %s", driverInfo, stereotype));125    LOG.info("Grid URI is: " + nodeOptions.getPublicGridUri());126    return new OneShotNode(127      loggingOptions.getTracer(),128      eventOptions.getEventBus(),129      serverOptions.getRegistrationSecret(),130      new NodeId(UUID.randomUUID()),131      serverOptions.getExternalUri(),132      nodeOptions.getPublicGridUri().orElseThrow(() -> new ConfigException("Unable to determine public grid address")),133      stereotype,134      driverInfo);135  }136  @Override137  public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {138    if (driver != null) {139      throw new IllegalStateException("Only expected one session at a time");140    }141    Optional<WebDriver> driver = driverInfo.createDriver(sessionRequest.getCapabilities());142    if (!driver.isPresent()) {143      return Optional.empty();144    }145    if (!(driver.get() instanceof RemoteWebDriver)) {146      driver.get().quit();147      return Optional.empty();148    }149    this.driver = (RemoteWebDriver) driver.get();150    this.sessionId = this.driver.getSessionId();151    this.client = extractHttpClient(this.driver);152    this.capabilities = rewriteCapabilities(this.driver);153    this.sessionStart = Instant.now();154    LOG.info("Encoded response: " + JSON.toJson(ImmutableMap.of(155      "value", ImmutableMap.of(156        "sessionId", sessionId,157        "capabilities", capabilities))));158    events.fire(new NodeDrainStarted(getId()));159    return Optional.of(160      new CreateSessionResponse(161        getSession(sessionId),162        JSON.toJson(ImmutableMap.of(163          "value", ImmutableMap.of(164            "sessionId", sessionId,165            "capabilities", capabilities))).getBytes(UTF_8)));166  }167  private HttpClient extractHttpClient(RemoteWebDriver driver) {168    CommandExecutor executor = driver.getCommandExecutor();169    try {170      Field client = null;171      Class<?> current = executor.getClass();172      while (client == null && (current != null || Object.class.equals(current))) {173        client = findClientField(current);174        current = current.getSuperclass();175      }176      if (client == null) {177        throw new IllegalStateException("Unable to find client field in " + executor.getClass());178      }179      if (!HttpClient.class.isAssignableFrom(client.getType())) {180        throw new IllegalStateException("Client field is not assignable to http client");181      }182      client.setAccessible(true);183      return (HttpClient) client.get(executor);184    } catch (ReflectiveOperationException e) {185      throw new IllegalStateException(e);186    }187  }188  private Field findClientField(Class<?> clazz) {189    try {190      return clazz.getDeclaredField("client");191    } catch (NoSuchFieldException e) {192      return null;193    }194  }195  private Capabilities rewriteCapabilities(RemoteWebDriver driver) {196    // Rewrite the se:options if necessary197    Object rawSeleniumOptions = driver.getCapabilities().getCapability("se:options");198    if (rawSeleniumOptions == null || rawSeleniumOptions instanceof Map) {199      @SuppressWarnings("unchecked") Map<String, Object> original = (Map<String, Object>) rawSeleniumOptions;200      Map<String, Object> updated = new TreeMap<>(original == null ? new HashMap<>() : original);201      String cdpPath = String.format("/session/%s/se/cdp", driver.getSessionId());202      updated.put("cdp", rewrite(cdpPath));203      return new PersistentCapabilities(driver.getCapabilities()).setCapability("se:options", updated);204    }205    return ImmutableCapabilities.copyOf(driver.getCapabilities());206  }207  private URI rewrite(String path) {208    try {209      return new URI(210        gridUri.getScheme(),211        gridUri.getUserInfo(),212        gridUri.getHost(),213        gridUri.getPort(),214        path,215        null,216        null);217    } catch (URISyntaxException e) {218      throw new RuntimeException(e);219    }220  }221  @Override222  public HttpResponse executeWebDriverCommand(HttpRequest req) {223    LOG.info("Executing " + req);224    HttpResponse res = client.execute(req);225    if (DELETE.equals(req.getMethod()) && req.getUri().equals("/session/" + sessionId)) {226      // Ensure the response is sent before we viciously kill the node227      new Thread(228        () -> {229          try {230            Thread.sleep(500);231          } catch (InterruptedException e) {232            Thread.currentThread().interrupt();233            throw new RuntimeException(e);234          }235          LOG.info("Stopping session: " + sessionId);236          stop(sessionId);237        },238        "Node clean up: " + getId())239      .start();240    }241    return res;242  }243  @Override244  public Session getSession(SessionId id) throws NoSuchSessionException {245    if (!isSessionOwner(id)) {246      throw new NoSuchSessionException("Unable to find session with id: " + id);247    }248    return new Session(249      sessionId,250      getUri(),251      stereotype,252      capabilities,253      sessionStart); }254  @Override255  public HttpResponse uploadFile(HttpRequest req, SessionId id) {256    return null;257  }258  @Override259  public void stop(SessionId id) throws NoSuchSessionException {260    LOG.info("Stop has been called: " + id);261    Require.nonNull("Session ID", id);262    if (!isSessionOwner(id)) {263      throw new NoSuchSessionException("Unable to find session " + id);264    }265    LOG.info("Quitting session " + id);266    try {267      driver.quit();268    } catch (Exception e) {269      // It's possible that the driver has already quit.270    }271    events.fire(new SessionClosedEvent(id));272    LOG.info("Firing node drain complete message");273    events.fire(new NodeDrainComplete(getId()));274  }275  @Override276  public boolean isSessionOwner(SessionId id) {277    return driver != null && sessionId.equals(id);278  }279  @Override280  public boolean isSupporting(Capabilities capabilities) {281    return driverInfo.isSupporting(capabilities);282  }283  @Override284  public NodeStatus getStatus() {285    return new NodeStatus(286      getId(),287      getUri(),288      1,289      ImmutableSet.of(290        new Slot(291          new SlotId(getId(), slotId),292          stereotype,293          Instant.EPOCH,294          driver == null ?295            Optional.empty() :...Source:NodeOptionsTest.java  
...72    verify(builderSpy, atLeastOnce()).add(73        argThat(caps -> caps.getBrowserName().equals(chrome.getBrowserName())),74        argThat(factory -> factory instanceof DriverServiceSessionFactory && factory.test(chrome)));75    LocalNode node = builder.build();76    assertThat(node.isSupporting(chrome)).isTrue();77    assertThat(node.isSupporting(toPayload("cheese"))).isFalse();78  }79  @Test80  public void shouldDetectCorrectDriversOnWindows() {81    assumeTrue(Platform.getCurrent().is(Platform.WINDOWS));82    assumeFalse("We don't have driver servers in PATH when we run unit tests",83                Boolean.getBoolean("TRAVIS"));84    Config config = new MapConfig(ImmutableMap.of(85        "node", ImmutableMap.of("detect-drivers", "true")));86    new NodeOptions(config).configure(tracer, clientFactory, builder);87    LocalNode node = builder.build();88    assertThat(node.isSupporting(toPayload("chrome"))).isTrue();89    assertThat(node.isSupporting(toPayload("firefox"))).isTrue();90    assertThat(node.isSupporting(toPayload("internet explorer"))).isTrue();91    assertThat(node.isSupporting(toPayload("MicrosoftEdge"))).isTrue();92    assertThat(node.isSupporting(toPayload("safari"))).isFalse();93  }94  @Test95  public void shouldDetectCorrectDriversOnMac() {96    assumeTrue(Platform.getCurrent().is(Platform.MAC));97    assumeFalse("We don't have driver servers in PATH when we run unit tests",98                Boolean.getBoolean("TRAVIS"));99    Config config = new MapConfig(ImmutableMap.of(100        "node", ImmutableMap.of("detect-drivers", "true")));101    new NodeOptions(config).configure(tracer, clientFactory, builder);102    LocalNode node = builder.build();103    assertThat(node.isSupporting(toPayload("chrome"))).isTrue();104    assertThat(node.isSupporting(toPayload("firefox"))).isTrue();105    assertThat(node.isSupporting(toPayload("internet explorer"))).isFalse();106    assertThat(node.isSupporting(toPayload("MicrosoftEdge"))).isFalse();107    assertThat(node.isSupporting(toPayload("safari"))).isTrue();108  }109  @Test110  public void canAddMoreSessionFactoriesAfterDriverDetection() throws URISyntaxException {111    Config config = new MapConfig(ImmutableMap.of(112        "node", ImmutableMap.of("detect-drivers", "true")));113    new NodeOptions(config).configure(tracer, clientFactory, builder);114    Capabilities cheese = toPayload("cheese");115    URI uri = new URI("http://localhost:1234");116    class Handler extends Session implements HttpHandler {117      private Handler(Capabilities capabilities) {118        super(new SessionId(UUID.randomUUID()), uri, capabilities);119      }120      @Override121      public HttpResponse execute(HttpRequest req) throws UncheckedIOException {122        return new HttpResponse();123      }124    }125    builder.add(cheese, new TestSessionFactory((id, c) -> new Handler(c)));126    LocalNode node = builder.build();127    assertThat(node.isSupporting(toPayload("chrome"))).isTrue();128    assertThat(node.isSupporting(cheese)).isTrue();129  }130  @Test131  public void canConfigureNodeWithoutDriverDetection() {132    Config config = new MapConfig(ImmutableMap.of(133        "node", ImmutableMap.of("detect-drivers", "false")));134    new NodeOptions(config).configure(tracer, clientFactory, builderSpy);135    verifyNoInteractions(builderSpy);136  }137  @Test138  public void doNotDetectDriversByDefault() {139    Config config = new MapConfig(ImmutableMap.of());140    new NodeOptions(config).configure(tracer, clientFactory, builderSpy);141    verifyNoInteractions(builderSpy);142  }...Source:NewSessionCreationTest.java  
...127      new DriverServiceSessionFactory(128        tracer,129        clientFactory,130        info.getCanonicalCapabilities(),131        info::isSupporting,132        driverService));133  }134}...Source:Host.java  
...104    Lock read = lock.readLock();105    read.lock();106    try {107      long count = slots.stream()108          .filter(slot -> slot.isSupporting(caps))109          .filter(slot -> slot.getStatus() == AVAILABLE)110          .count();111      return count > 0;112    } finally {113      read.unlock();114    }115  }116  public float getLoad() {117    Lock read = lock.readLock();118    read.lock();119    try {120      float inUse = slots.parallelStream()121          .filter(slot -> slot.getStatus() != AVAILABLE)122          .count();123      return (inUse / (float) maxSessionCount) * 100f;124    } finally {125      read.unlock();126    }127  }128  public long getLastSessionCreated() {129    Lock read = lock.readLock();130    read.lock();131    try {132      return slots.parallelStream()133          .mapToLong(Slot::getLastSessionCreated)134          .max()135          .orElse(0);136    } finally {137      read.unlock();138    }139  }140  public Supplier<Session> reserve(Capabilities caps) {141    Lock write = lock.writeLock();142    write.lock();143    try {144      Slot toReturn = slots.stream()145          .filter(slot -> slot.isSupporting(caps))146          .filter(slot -> slot.getStatus() == AVAILABLE)147          .findFirst()148          .orElseThrow(() -> new SessionNotCreatedException("Unable to reserve an instance"));149      return toReturn.onReserve(caps);150    } finally {151      write.unlock();152    }153  }154  void refresh() {155    performHealthCheck.run();156  }157  @Override158  public int hashCode() {159    return node.hashCode();...Source:SessionSlot.java  
...131      LOG.log(Level.WARNING, "Unable to create session", e);132      return Either.left(new SessionNotCreatedException(e.getMessage()));133    }134  }135  public boolean isSupportingCdp() {136    return supportingCdp;137  }138  private boolean isSlotSupportingCdp(Capabilities stereotype) {139    return StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false)140      .filter(webDriverInfo -> webDriverInfo.isSupporting(stereotype))141      .anyMatch(WebDriverInfo::isSupportingCdp);142  }143}...Source:RemoteNode.java  
...66      }67    };68  }69  @Override70  public boolean isSupporting(Capabilities capabilities) {71    return this.capabilities.stream()72        .anyMatch(caps -> caps.getCapabilityNames().stream()73            .allMatch(name -> Objects.equals(74                caps.getCapability(name),75                capabilities.getCapability(name))));76  }77  @Override78  public Optional<Session> newSession(Capabilities capabilities) {79    Objects.requireNonNull(capabilities, "Capabilities for session are not set");80    HttpRequest req = new HttpRequest(POST, "/se/grid/node/session");81    req.setContent(JSON.toJson(capabilities).getBytes(UTF_8));82    HttpResponse res = client.apply(req);83    return Optional.ofNullable(Values.get(res, Session.class));84  }...Source:LocalDistributor.java  
...41    Capabilities caps = payload.stream()42        .findFirst()43        .orElseThrow(() -> new SessionNotCreatedException("No capabilities found"));44    return nodes.stream()45        .filter(node -> node.isSupporting(caps))46        .findFirst()47        .map(host -> host.newSession(caps))48        .filter(Optional::isPresent)49        .map(Optional::get)50        .orElseThrow(() -> new SessionNotCreatedException("Unable to create new session: " + caps));51  }52  @Override53  public void add(Node node) {54    nodes.add(node);55  }56  @Override57  public void remove(UUID nodeId) {58    nodes.removeIf(node -> nodeId.equals(node.getId()));59  }...isSupporting
Using AI Code Generation
1import org.openqa.selenium.Capabilities;2import org.openqa.selenium.ImmutableCapabilities;3import org.openqa.selenium.grid.config.Config;4import org.openqa.selenium.grid.config.MemoizedConfig;5import org.openqa.selenium.grid.config.TomlConfig;6import org.openqa.selenium.grid.data.Session;7import org.openqa.selenium.grid.node.Node;8import org.openqa.selenium.grid.node.local.LocalNode;9import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;10import org.openqa.selenium.grid.sessionmap.remote.RemoteSessionMap;11import org.openqa.selenium.grid.web.Routable;12import org.openqa.selenium.grid.web.Routes;13import org.openqa.selenium.grid.web.Values;14import org.openqa.selenium.internal.Require;15import org.openqa.selenium.json.Json;16import org.openqa.selenium.remote.Dialect;17import org.openqa.selenium.remote.http.HttpMethod;18import org.openqa.selenium.remote.http.HttpRequest;19import org.openqa.selenium.remote.http.HttpResponse;20import org.openqa.selenium.remote.tracing.Tracer;21import org.openqa.selenium.remote.tracing.TracerBuilder;22import java.io.IOException;23import java.net.URI;24import java.util.Objects;25import java.util.Set;26import java.util.logging.Logger;27public class CustomNode implements Node {28  private static final Logger LOG = Logger.getLogger(CustomNode.class.getName());29  private static final Json JSON = new Json();30  private final Tracer tracer;31  private final URI uri;32  private final Node delegate;33  public CustomNode(Tracer tracer, URI uri, Node delegate) {34    this.tracer = Require.nonNull("Tracer", tracer);35    this.uri = Require.nonNull("Node URI", uri);36    this.delegate = Require.nonNull("Delegate node", delegate);37  }38  public boolean isSupporting(Capabilities capabilities) {39    return delegate.isSupporting(capabilities);40  }41  public URI getUri() {42    return delegate.getUri();43  }44  public Set<Dialect> getSupportedW3CWireProtocolVersions() {45    return delegate.getSupportedW3CWireProtocolVersions();46  }47  public Set<Dialect> getSupportedOSSWireProtocolVersions() {48    return delegate.getSupportedOSSWireProtocolVersions();49  }50  public Session newSession(Capabilities capabilities) {51    return delegate.newSession(capabilities);52  }53  public void execute(HttpRequest req, HttpResponse resp) throws IOException {54    delegate.execute(req, resp);55  }isSupporting
Using AI Code Generation
1import org.openqa.selenium.grid.config.Config;2import org.openqa.selenium.grid.config.MemoizedConfig;3import org.openqa.selenium.grid.config.TomlConfig;4import org.openqa.selenium.grid.node.Node;5import org.openqa.selenium.grid.node.local.LocalNode;6import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;7import org.openqa.selenium.grid.web.config.WebServerOptions;8import org.openqa.selenium.remote.http.HttpClient;9import org.openqa.selenium.remote.http.HttpRequest;10import org.openqa.selenium.remote.http.HttpResponse;11import org.openqa.selenium.remote.tracing.Tracer;12import org.openqa.selenium.remote.tracing.config.TracerConfig;13import org.openqa.selenium.remote.tracing.jaeger.JaegerOptions;14import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryOptions;15import org.openqa.selenium.remote.tracing.zipkin.ZipkinOptions;16import java.io.IOException;17import java.nio.file.Paths;18import java.util.Map;19public class Main {20  public static void main(String[] args) throws IOException {21    Config config = new TomlConfig(Paths.get("config.toml"));22    config = new MemoizedConfig(config);23    Tracer tracer = TracerConfig.create(config).getTracer();24    Node node = new LocalNode(25      HttpClient.Factory.createDefault(),26      new WebServerOptions(config),27      new SessionMapOptions(config));28    HttpRequest request = new HttpRequest(HttpRequest.POST, "/session/node/supports");29    request.setContent("{\"capabilities\": {\"alwaysMatch\": {\"browserName\": \"chrome\"}}}");30    HttpResponse response = node.execute(request);31    System.out.println(response);32  }33}isSupporting
Using AI Code Generation
1package com.test;2import org.openqa.selenium.Capabilities;3import org.openqa.selenium.ImmutableCapabilities;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebDriverException;6import org.openqa.selenium.grid.config.Config;7import org.openqa.selenium.grid.config.MemoizedConfig;8import org.openqa.selenium.grid.node.Node;9import org.openqa.selenium.grid.node.local.LocalNode;10import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;11import org.openqa.selenium.grid.web.Values;12import org.openqa.selenium.remote.SessionId;13import org.openqa.selenium.remote.http.HttpClient;14import org.openqa.selenium.remote.tracing.Tracer;15import org.openqa.selenium.remote.tracing.TracerProvider;16import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;17import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerProvider;18import java.net.URI;19import java.net.URISyntaxException;20import java.nio.file.Paths;21import java.time.Duration;22import java.util.Optional;23import java.util.function.Function;24public class Test {25    public static void main(String[] args) throws URISyntaxException {26        TracerProvider tracerProvider = new OpenTelemetryTracerProvider();27        Tracer tracer = new OpenTelemetryTracer(tracerProvider.get("Test"));28        Config config = new MemoizedConfig(Paths.get("C:\\Users\\abc\\IdeaProjects\\SeleniumGrid\\src\\main\\resources\\config.json"));29        SessionMapOptions sessionMapOptions = new SessionMapOptions(config);30        HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();31        Node node = new LocalNode(tracer, sessionMapOptions.getSessionMap(), clientFactory, uri);32        Capabilities capabilities = new ImmutableCapabilities("browserName", "chrome");33        System.out.println(node.isSupporting(capabilities));34    }35}isSupporting
Using AI Code Generation
1import org.openqa.selenium.grid.config.Config;2import org.openqa.selenium.grid.config.MapConfig;3import org.openqa.selenium.grid.node.local.LocalNode;4import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;5import org.openqa.selenium.grid.web.Routable;6import org.openqa.selenium.remote.http.HttpHandler;7import org.openqa.selenium.remote.tracing.Tracer;8import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;9import java.io.IOException;10import java.net.URL;11import java.util.logging.Logger;12public class Node {13  private static final Logger LOG = Logger.getLogger(Node.class.getName());14  private static final String DEFAULT_CONFIG = "config.json";15  public static void main(String[] args) throws IOException {16    final Tracer tracer = OpenTelemetryTracer.create();17    final Config config = new MapConfig();18    final SessionMapOptions sessionMapOptions = new SessionMapOptions(config);19    final LocalNode.Builder builder = LocalNode.builder(tracer, sessionMapOptions);20    if (args.length > 0) {21      URL url = new URL(args[0]);22      builder.add(configFrom(url));23    } else {24      builder.add(configFrom(DEFAULT_CONFIG));25    }26    final LocalNode node = builder.build();27    final HttpHandler handler = node.asHttpHandler();28    final Routable router = new Routable() {29      public String getRoute() {30        return "/wd/hub";31      }32      public HttpHandler getHandler() {33        return handler;34      }35    };36    Server<?> server = new Server<>(router);37    server.start();38    server.join();39  }40  private static Config configFrom(String path) throws IOException {41  }42  private static Config configFrom(URL url) throws IOException {43    return new JsonConfig(url);44  }45}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!!
