How to use remove method of org.openqa.selenium.grid.distributor.GridModel class

Best Selenium code snippet using org.openqa.selenium.grid.distributor.GridModel.remove

Source:GridModel.java Github

copy

Full Screen

...55 private final EventBus events;56 public GridModel(EventBus events, Secret registrationSecret) {57 this.events = Require.nonNull("Event bus", events);58 events.addListener(NodeDrainStarted.listener(nodeId -> setAvailability(nodeId, DRAINING)));59 events.addListener(NodeDrainComplete.listener(this::remove));60 events.addListener(NodeRemovedEvent.listener(this::remove));61 events.addListener(NodeStatusEvent.listener(status -> refresh(registrationSecret, status)));62 events.addListener(SessionClosedEvent.listener(this::release));63 }64 public GridModel add(NodeStatus node) {65 Require.nonNull("Node", node);66 Lock writeLock = lock.writeLock();67 writeLock.lock();68 try {69 // If we've already added the node, remove it.70 for (Set<NodeStatus> nodes : nodes.values()) {71 Iterator<NodeStatus> iterator = nodes.iterator();72 while (iterator.hasNext()) {73 NodeStatus next = iterator.next();74 // If the ID is the same, we're re-adding a node. If the URI is the same a node probably restarted75 if (next.getId().equals(node.getId()) || next.getUri().equals(node.getUri())) {76 LOG.info(String.format("Re-adding node with id %s and URI %s.", node.getId(), node.getUri()));77 iterator.remove();78 }79 }80 }81 // Nodes are initially added in the "down" state until something changes their availability82 nodes(DOWN).add(node);83 } finally {84 writeLock.unlock();85 }86 return this;87 }88 public GridModel refresh(Secret registrationSecret, NodeStatus status) {89 Require.nonNull("Node status", status);90 Secret statusSecret = status.getRegistrationSecret() == null ? null : new Secret(status.getRegistrationSecret());91 if (!Objects.equals(registrationSecret, statusSecret)) {92 LOG.severe(String.format("Node at %s failed to send correct registration secret. Node NOT refreshed.", status.getUri()));93 events.fire(new NodeRejectedEvent(status.getUri()));94 return this;95 }96 Lock writeLock = lock.writeLock();97 writeLock.lock();98 try {99 AvailabilityAndNode availabilityAndNode = findNode(status.getId());100 if (availabilityAndNode == null) {101 return this;102 }103 // if the node was marked as "down", keep it down until a healthcheck passes:104 // just because the node can hit the event bus doesn't mean it's reachable105 if (DOWN.equals(availabilityAndNode.availability)) {106 nodes(DOWN).remove(availabilityAndNode.status);107 nodes(DOWN).add(status);108 return this;109 }110 // But do trust the node if it tells us it's draining111 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);112 nodes(status.getAvailability()).add(status);113 return this;114 } finally {115 writeLock.unlock();116 }117 }118 public GridModel remove(NodeId id) {119 Require.nonNull("Node ID", id);120 Lock writeLock = lock.writeLock();121 writeLock.lock();122 try {123 AvailabilityAndNode availabilityAndNode = findNode(id);124 if (availabilityAndNode == null) {125 return this;126 }127 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);128 return this;129 } finally {130 writeLock.unlock();131 }132 }133 public Availability setAvailability(NodeId id, Availability availability) {134 Require.nonNull("Node ID", id);135 Require.nonNull("Availability", availability);136 Lock writeLock = lock.writeLock();137 writeLock.lock();138 try {139 AvailabilityAndNode availabilityAndNode = findNode(id);140 if (availabilityAndNode == null) {141 return DOWN;142 }143 if (availability.equals(availabilityAndNode.availability)) {144 return availability;145 }146 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);147 nodes(availability).add(availabilityAndNode.status);148 LOG.info(String.format(149 "Switching node %s (uri: %s) from %s to %s",150 id,151 availabilityAndNode.status.getUri(),152 availabilityAndNode.availability,153 availability));154 return availabilityAndNode.availability;155 } finally {156 writeLock.unlock();157 }158 }159 public boolean reserve(SlotId slotId) {160 Lock writeLock = lock.writeLock();161 writeLock.lock();162 try {163 AvailabilityAndNode node = findNode(slotId.getOwningNodeId());164 if (node == null) {165 LOG.warning(String.format("Asked to reserve slot on node %s, but unable to find node", slotId.getOwningNodeId()));166 return false;167 }168 if (!UP.equals(node.availability)) {169 LOG.warning(String.format(170 "Asked to reserve a slot on node %s, but not is %s",171 slotId.getOwningNodeId(),172 node.availability));173 return false;174 }175 Optional<Slot> maybeSlot = node.status.getSlots().stream()176 .filter(slot -> slotId.equals(slot.getId()))177 .findFirst();178 if (!maybeSlot.isPresent()) {179 LOG.warning(String.format(180 "Asked to reserve slot on node %s, but no slot with id %s found",181 node.status.getId(),182 slotId));183 return false;184 }185 reserve(node.status, maybeSlot.get());186 return true;187 } finally {188 writeLock.unlock();189 }190 }191 public Set<NodeStatus> getSnapshot() {192 Lock readLock = this.lock.readLock();193 readLock.lock();194 try {195 ImmutableSet.Builder<NodeStatus> snapshot = ImmutableSet.builder();196 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {197 entry.getValue().stream()198 .map(status -> rewrite(status, entry.getKey()))199 .forEach(snapshot::add);200 }201 return snapshot.build();202 } finally {203 readLock.unlock();204 }205 }206 private Set<NodeStatus> nodes(Availability availability) {207 return nodes.computeIfAbsent(availability, ignored -> new HashSet<>());208 }209 private AvailabilityAndNode findNode(NodeId id) {210 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {211 for (NodeStatus nodeStatus : entry.getValue()) {212 if (id.equals(nodeStatus.getId())) {213 return new AvailabilityAndNode(entry.getKey(), nodeStatus);214 }215 }216 }217 return null;218 }219 private NodeStatus rewrite(NodeStatus status, Availability availability) {220 return new NodeStatus(221 status.getId(),222 status.getUri(),223 status.getMaxSessionCount(),224 status.getSlots(),225 availability,226 status.getRegistrationSecret() == null ? null : new Secret(status.getRegistrationSecret()));227 }228 private void release(SessionId id) {229 if (id == null) {230 return;231 }232 Lock writeLock = lock.writeLock();233 writeLock.lock();234 try {235 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {236 for (NodeStatus node : entry.getValue()) {237 for (Slot slot : node.getSlots()) {238 if (!slot.getSession().isPresent()) {239 continue;240 }241 if (id.equals(slot.getSession().get().getId())) {242 Slot released = new Slot(243 slot.getId(),244 slot.getStereotype(),245 slot.getLastStarted(),246 Optional.empty());247 amend(entry.getKey(), node, released);248 return;249 }250 }251 }252 }253 } finally {254 writeLock.unlock();255 }256 }257 private void reserve(NodeStatus status, Slot slot) {258 Instant now = Instant.now();259 Slot reserved = new Slot(260 slot.getId(),261 slot.getStereotype(),262 now,263 Optional.of(new Session(264 RESERVED,265 status.getUri(),266 slot.getStereotype(),267 slot.getStereotype(),268 now)));269 amend(UP, status, reserved);270 }271 public void setSession(SlotId slotId, Session session) {272 Require.nonNull("Slot ID", slotId);273 AvailabilityAndNode node = findNode(slotId.getOwningNodeId());274 if (node == null) {275 LOG.warning("Grid model and reality have diverged. Unable to find node " + slotId.getOwningNodeId());276 return;277 }278 Optional<Slot> maybeSlot = node.status.getSlots().stream()279 .filter(slot -> slotId.equals(slot.getId()))280 .findFirst();281 if (!maybeSlot.isPresent()) {282 LOG.warning("Grid model and reality have diverged. Unable to find slot " + slotId);283 return;284 }285 Slot slot = maybeSlot.get();286 Optional<Session> maybeSession = slot.getSession();287 if (!maybeSession.isPresent()) {288 LOG.warning("Grid model and reality have diverged. Slot is not reserved. " + slotId);289 return;290 }291 Session current = maybeSession.get();292 if (!RESERVED.equals(current.getId())) {293 LOG.warning("Gid model and reality have diverged. Slot has session and is not reserved. " + slotId);294 return;295 }296 Slot updated = new Slot(297 slot.getId(),298 slot.getStereotype(),299 session == null ? slot.getLastStarted() : session.getStartTime(),300 Optional.ofNullable(session));301 amend(node.availability, node.status, updated);302 }303 private void amend(Availability availability, NodeStatus status, Slot slot) {304 Set<Slot> newSlots = new HashSet<>(status.getSlots());305 newSlots.removeIf(s -> s.getId().equals(slot.getId()));306 newSlots.add(slot);307 nodes(availability).remove(status);308 nodes(availability).add(new NodeStatus(309 status.getId(),310 status.getUri(),311 status.getMaxSessionCount(),312 newSlots,313 status.getAvailability(),314 status.getRegistrationSecret() == null ? null : new Secret(status.getRegistrationSecret())));315 }316 private static class AvailabilityAndNode {317 public final Availability availability;318 public final NodeStatus status;319 public AvailabilityAndNode(Availability availability, NodeStatus status) {320 this.availability = availability;321 this.status = status;...

Full Screen

Full Screen

Source:LocalDistributor.java Github

copy

Full Screen

...93 this.nodes = new HashMap<>();94 this.registrationSecret = Require.nonNull("Registration secret", registrationSecret);95 bus.addListener(NodeStatusEvent.listener(this::register));96 bus.addListener(NodeStatusEvent.listener(model::refresh));97 bus.addListener(NodeDrainComplete.listener(this::remove));98 }99 public static Distributor create(Config config) {100 Tracer tracer = new LoggingOptions(config).getTracer();101 EventBus bus = new EventBusOptions(config).getEventBus();102 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);103 SessionMap sessions = new SessionMapOptions(config).getSessionMap();104 BaseServerOptions serverOptions = new BaseServerOptions(config);105 return new LocalDistributor(tracer, bus, clientFactory, sessions, serverOptions.getRegistrationSecret());106 }107 @Override108 public boolean isReady() {109 try {110 return ImmutableSet.of(bus, sessions).parallelStream()111 .map(HasReadyState::isReady)112 .reduce(true, Boolean::logicalAnd);113 } catch (RuntimeException e) {114 return false;115 }116 }117 private void register(NodeStatus status) {118 Require.nonNull("Node", status);119 Lock writeLock = lock.writeLock();120 writeLock.lock();121 try {122 if (nodes.containsKey(status.getId())) {123 return;124 }125 Set<Capabilities> capabilities = status.getSlots().stream()126 .map(Slot::getStereotype)127 .map(ImmutableCapabilities::copyOf)128 .collect(toImmutableSet());129 // A new node! Add this as a remote node, since we've not called add130 RemoteNode remoteNode = new RemoteNode(131 tracer,132 clientFactory,133 status.getId(),134 status.getUri(),135 registrationSecret,136 capabilities);137 add(remoteNode);138 } finally {139 writeLock.unlock();140 }141 }142 @Override143 public LocalDistributor add(Node node) {144 Require.nonNull("Node", node);145 LOG.info(String.format("Added node %s at %s.", node.getId(), node.getUri()));146 nodes.put(node.getId(), node);147 model.add(node.getStatus());148 // Extract the health check149 Runnable runnableHealthCheck = asRunnableHealthCheck(node);150 allChecks.put(node.getId(), runnableHealthCheck);151 hostChecker.submit(runnableHealthCheck, Duration.ofMinutes(5), Duration.ofSeconds(30));152 bus.fire(new NodeAddedEvent(node.getId()));153 return this;154 }155 private Runnable asRunnableHealthCheck(Node node) {156 HealthCheck healthCheck = node.getHealthCheck();157 NodeId id = node.getId();158 return () -> {159 HealthCheck.Result result;160 try {161 result = healthCheck.check();162 } catch (Exception e) {163 LOG.log(Level.WARNING, "Unable to process node " + id, e);164 result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");165 }166 Lock writeLock = lock.writeLock();167 writeLock.lock();168 try {169 model.setAvailability(id, result.getAvailability());170 } finally {171 writeLock.unlock();172 }173 };174 }175 @Override176 public boolean drain(NodeId nodeId) {177 Node node = nodes.get(nodeId);178 if (node == null) {179 LOG.info("Asked to drain unregistered node " + nodeId);180 return false;181 }182 Lock writeLock = lock.writeLock();183 writeLock.lock();184 try {185 node.drain();186 model.setAvailability(nodeId, DRAINING);187 } finally {188 writeLock.unlock();189 }190 return node.isDraining();191 }192 public void remove(NodeId nodeId) {193 Lock writeLock = lock.writeLock();194 writeLock.lock();195 try {196 model.remove(nodeId);197 Runnable runnable = allChecks.remove(nodeId);198 if (runnable != null) {199 hostChecker.remove(runnable);200 }201 } finally {202 writeLock.unlock();203 bus.fire(new NodeRemovedEvent(nodeId));204 }205 }206 @Override207 public DistributorStatus getStatus() {208 Lock readLock = this.lock.readLock();209 readLock.lock();210 try {211 return new DistributorStatus(model.getSnapshot());212 } finally {213 readLock.unlock();...

Full Screen

Full Screen

remove

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.distributor.GridModel;2import org.openqa.selenium.grid.distributor.local.LocalDistributor;3import org.openqa.selenium.grid.node.local.LocalNode;4import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;5import org.openqa.selenium.net.PortProber;6import org.openqa.selenium.remote.http.HttpClient;7import org.openqa.selenium.remote.http.HttpClientFactory;8import org.openqa.selenium.remote.tracing.Tracer;9import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;10import java.net.URI;11import java.net.URISyntaxException;12import java.time.Duration;13import java.util.UUID;14public class RemoveNode {15 public static void main(String[] args) throws URISyntaxException {16 Tracer tracer = new OpenTelemetryTracer();17 HttpClientFactory clientFactory = HttpClient.Factory.createDefault().createClientFactory(tracer);18 LocalSessionMap sessions = new LocalSessionMap(tracer);19 LocalDistributor distributor = new LocalDistributor(tracer, sessions, clientFactory);20 LocalNode node = new LocalNode(tracer, clientFactory, distributor, sessions, PortProber.findFreePort());21 GridModel model = new GridModel(tracer, sessions, distributor, node);22 model.remove(node.getId());23 }24}25[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ selenium-grid ---26public void add(Node node) {27 Objects.requireNonNull(node, "Node to add must be set.");28 nodes.put(node.getId(), node);29}30import org.openqa.selenium.grid.distributor.GridModel;31import org.openqa.selenium.grid.distributor.local.LocalDistributor;32import org.openqa.selenium.grid.node.local.LocalNode;33import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;34import org.openqa.selenium.net.PortProber;35import org.openqa.selenium.remote.http.HttpClient;36import org.openqa.selenium.remote.http.HttpClientFactory;37import org.openqa.selenium.remote.tracing.Tracer;38import org.openqa.selenium.remote.tracing.opentelemetry

Full Screen

Full Screen

remove

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.distributor.GridModel;2import org.openqa.selenium.grid.node.local.LocalNode;3import org.openqa.selenium.grid.config.Config;4import org.openqa.selenium.grid.config.MapConfig;5import org.openqa.selenium.grid.distributor.local.LocalDistributor;6import org.openqa.selenium.grid.distributor.local.StickyStrategy;7import org.openqa.selenium.grid.node.remote.RemoteNode;8import org.openqa.selenium.net.Host;9import org.openqa.selenium.remote.http.HttpClient;10import org.openqa.selenium.remote.http.HttpClient.Factory;11import org.openqa.selenium.remote.http.HttpClientOptions;12import org.openqa.selenium.remote.tracing.Tracer;13import org.openqa.selenium.remote.tracing.global.GlobalTracer;14import java.net.URI;15import java.net.URISyntaxException;16import java.util.Map;17import java.util.HashMap;18import java.util.logging.Level;19import java.util.logging.Logger;20public class RemoveNodeExample {21 public static void main(String[] args) throws URISyntaxException {22 Config config = new MapConfig(new HashMap<>());23 Tracer tracer = GlobalTracer.get();24 GridModel model = GridModel.create(config, tracer);25 LocalDistributor distributor = new LocalDistributor(tracer, model, new StickyStrategy(tracer));26 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();27 Factory clientFactory = HttpClient.Factory.createDefault();28 HttpClientOptions clientOptions = new HttpClientOptions();29 HttpClient client = clientFactory.createClient(clientOptions);30 RemoteNode node = new RemoteNode(tracer, uri, client);31 model.add(node);32 model.remove(node);33 }34}35import org.openqa.selenium.grid.config.Config;36import org.openqa.selenium.grid.config.FileConfig;37import org.openqa.selenium.grid.distributor.GridModel;38import org.openqa.selenium.grid.node.local.LocalNode;39import org.openqa.selenium.grid.distributor.local.LocalDistributor;40import org.openqa.selenium.grid.distributor

Full Screen

Full Screen

remove

Using AI Code Generation

copy

Full Screen

1package com.seleniumeasy;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import java.util.List;7import java.util.concurrent.TimeUnit;8public class RemoveElement {9 public static void main(String[] args) throws InterruptedException {10 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Srikanth\\Downloads\\chromedriver_win32\\chromedriver.exe");11 WebDriver driver = new ChromeDriver();12 driver.manage().window().maximize();13 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);14 list.get(1).click();15 Thread.sleep(3000);16 driver.close();17 }18}19package com.seleniumeasy;20import org.openqa.selenium.By;21import org.openqa.selenium.WebDriver;22import org.openqa.selenium.WebElement;23import org.openqa.selenium.chrome.ChromeDriver;24import java.util.List;25import java.util.concurrent.TimeUnit;26public class RemoveElement {27 public static void main(String[] args) throws InterruptedException {28 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Srikanth\\Downloads\\chromedriver_win32\\chromedriver.exe");29 WebDriver driver = new ChromeDriver();30 driver.manage().window().maximize();31 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);32 list.get(1).click();

Full Screen

Full Screen

remove

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.distributor.local.LocalDistributor;2import org.openqa.selenium.grid.session.remote.RemoteSession;3import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;4import org.openqa.selenium.grid.sessionmap.remote.RemoteSessionMap;5import org.openqa.selenium.grid.web.Routable;6import org.openqa.selenium.grid.web.Routes;7import org.openqa.selenium.remote.http.HttpMethod;8import org.openqa.selenium.remote.http.HttpRequest;9import org.openqa.selenium.remote.http.HttpResponse;10import java.net.URI;11import java.net.URISyntaxException;12import java.util.Objects;13import java.util.UUID;14import java.util.function.Predicate;15public class GridModelRemoveSession implements Routable {16 private final LocalDistributor distributor;17 private final Predicate<HttpRequest> predicate;18 public GridModelRemoveSession(LocalDistributor distributor) {19 this.distributor = Objects.requireNonNull(distributor);20 this.predicate = new Predicate<HttpRequest>() {21 public boolean test(HttpRequest request) {22 return request.getMethod() == HttpMethod.DELETE;23 }24 };25 }26 public void execute(HttpRequest req, HttpResponse resp) throws URISyntaxException {27 URI uri = new URI(req.getUri());28 String[] path = uri.getPath().split("/");29 if (path.length != 3) {30 resp.setStatus(400);31 return;32 }33 UUID sessionId = UUID.fromString(path[2]);34 RemoteSession remoteSession = new RemoteSession(sessionId, distributor.getUri());35 RemoteSessionMap sessionMap = new RemoteSessionMap(new SessionMapOptions());36 sessionMap.remove(remoteSession);37 resp.setStatus(200);38 }39 public Predicate<HttpRequest> getPredicate() {40 return predicate;41 }42 public static Routes getRoutes(LocalDistributor distributor) {43 return new Routes(new GridModelRemoveSession(distributor));44 }45}46import org.openqa.selenium.grid.distributor.local.LocalDistributor;47import org.openqa.selenium.grid.session.remote.RemoteSession;48import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;49import org.openqa.selenium.grid.sessionmap.remote.RemoteSessionMap;50import org.openqa.selenium.grid.web.Routable;51import org.openqa.selenium.grid.web.Routes;52import org.openqa.selenium.remote.http.HttpMethod;53import org.openqa.selenium.remote.http.HttpRequest;54import org.openqa.selenium.remote.http.HttpResponse;55import

Full Screen

Full Screen

Selenium 4 Tutorial:

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.

Chapters:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful