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

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

Source:GridModel.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.distributor.local;18import com.google.common.collect.ImmutableSet;19import org.openqa.selenium.events.EventBus;20import org.openqa.selenium.grid.data.Availability;21import org.openqa.selenium.grid.data.NodeDrainComplete;22import org.openqa.selenium.grid.data.NodeDrainStarted;23import org.openqa.selenium.grid.data.NodeId;24import org.openqa.selenium.grid.data.NodeRejectedEvent;25import org.openqa.selenium.grid.data.NodeRemovedEvent;26import org.openqa.selenium.grid.data.NodeStatus;27import org.openqa.selenium.grid.data.NodeStatusEvent;28import org.openqa.selenium.grid.data.Session;29import org.openqa.selenium.grid.data.SessionClosedEvent;30import org.openqa.selenium.grid.data.Slot;31import org.openqa.selenium.grid.data.SlotId;32import org.openqa.selenium.grid.security.Secret;33import org.openqa.selenium.internal.Require;34import org.openqa.selenium.remote.SessionId;35import java.time.Instant;36import java.util.HashSet;37import java.util.Iterator;38import java.util.Map;39import java.util.Objects;40import java.util.Optional;41import java.util.Set;42import java.util.concurrent.ConcurrentHashMap;43import java.util.concurrent.locks.Lock;44import java.util.concurrent.locks.ReadWriteLock;45import java.util.concurrent.locks.ReentrantReadWriteLock;46import java.util.logging.Logger;47import static org.openqa.selenium.grid.data.Availability.DOWN;48import static org.openqa.selenium.grid.data.Availability.DRAINING;49import static org.openqa.selenium.grid.data.Availability.UP;50public class GridModel {51 private static final Logger LOG = Logger.getLogger(GridModel.class.getName());52 private static final SessionId RESERVED = new SessionId("reserved");53 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);54 private final Map<Availability, Set<NodeStatus>> nodes = new ConcurrentHashMap<>();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;322 }...

Full Screen

Full Screen

Source:LocalDistributor.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.distributor.local;18import com.google.common.collect.ImmutableSet;19import org.openqa.selenium.Beta;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.ImmutableCapabilities;22import org.openqa.selenium.SessionNotCreatedException;23import org.openqa.selenium.concurrent.Regularly;24import org.openqa.selenium.events.EventBus;25import org.openqa.selenium.grid.config.Config;26import org.openqa.selenium.grid.data.CreateSessionRequest;27import org.openqa.selenium.grid.data.CreateSessionResponse;28import org.openqa.selenium.grid.data.DistributorStatus;29import org.openqa.selenium.grid.data.NodeAddedEvent;30import org.openqa.selenium.grid.data.NodeDrainComplete;31import org.openqa.selenium.grid.data.NodeId;32import org.openqa.selenium.grid.data.NodeRemovedEvent;33import org.openqa.selenium.grid.data.NodeStatus;34import org.openqa.selenium.grid.data.NodeStatusEvent;35import org.openqa.selenium.grid.data.Slot;36import org.openqa.selenium.grid.data.SlotId;37import org.openqa.selenium.grid.distributor.Distributor;38import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;39import org.openqa.selenium.grid.log.LoggingOptions;40import org.openqa.selenium.grid.node.HealthCheck;41import org.openqa.selenium.grid.node.Node;42import org.openqa.selenium.grid.node.remote.RemoteNode;43import org.openqa.selenium.grid.security.Secret;44import org.openqa.selenium.grid.server.BaseServerOptions;45import org.openqa.selenium.grid.server.EventBusOptions;46import org.openqa.selenium.grid.server.NetworkOptions;47import org.openqa.selenium.grid.sessionmap.SessionMap;48import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;49import org.openqa.selenium.internal.Require;50import org.openqa.selenium.remote.http.HttpClient;51import org.openqa.selenium.remote.tracing.Tracer;52import org.openqa.selenium.status.HasReadyState;53import java.time.Duration;54import java.util.ArrayList;55import java.util.HashMap;56import java.util.List;57import java.util.Map;58import java.util.Optional;59import java.util.Set;60import java.util.concurrent.locks.Lock;61import java.util.concurrent.locks.ReadWriteLock;62import java.util.concurrent.locks.ReentrantReadWriteLock;63import java.util.function.Supplier;64import java.util.logging.Level;65import java.util.logging.Logger;66import static com.google.common.collect.ImmutableSet.toImmutableSet;67import static org.openqa.selenium.grid.data.Availability.DOWN;68import static org.openqa.selenium.grid.data.Availability.DRAINING;69public class LocalDistributor extends Distributor {70 private static final Logger LOG = Logger.getLogger(LocalDistributor.class.getName());71 private final Tracer tracer;72 private final EventBus bus;73 private final HttpClient.Factory clientFactory;74 private final SessionMap sessions;75 private final Secret registrationSecret;76 private final Regularly hostChecker = new Regularly("distributor host checker");77 private final Map<NodeId, Runnable> allChecks = new HashMap<>();78 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);79 private final GridModel model;80 private final Map<NodeId, Node> nodes;81 public LocalDistributor(82 Tracer tracer,83 EventBus bus,84 HttpClient.Factory clientFactory,85 SessionMap sessions,86 Secret registrationSecret) {87 super(tracer, clientFactory, new DefaultSlotSelector(), sessions, registrationSecret);88 this.tracer = Require.nonNull("Tracer", tracer);89 this.bus = Require.nonNull("Event bus", bus);90 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);91 this.sessions = Require.nonNull("Session map", sessions);92 this.model = new GridModel(bus, registrationSecret);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();214 }215 }216 @Beta217 public void refresh() {218 List<Runnable> allHealthChecks = new ArrayList<>();219 Lock readLock = this.lock.readLock();220 readLock.lock();221 try {222 allHealthChecks.addAll(allChecks.values());223 } finally {224 readLock.unlock();225 }226 allHealthChecks.parallelStream().forEach(Runnable::run);227 }228 @Override229 protected Set<NodeStatus> getAvailableNodes() {230 Lock readLock = this.lock.readLock();231 readLock.lock();232 try {233 return model.getSnapshot().stream()234 .filter(node -> !DOWN.equals(node.getAvailability()))235 .collect(toImmutableSet());236 } finally {...

Full Screen

Full Screen

add

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.config.SessionMapOptions;5import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;6import org.openqa.selenium.grid.web.Routable;7import org.openqa.selenium.grid.web.Routes;8import org.openqa.selenium.remote.http.HttpClient;9import org.openqa.selenium.remote.tracing.DefaultTestTracer;10import org.openqa.selenium.remote.tracing.Tracer;11import java.net.URI;12import java.util.Map;13import java.util.Objects;14import java.util.function.Supplier;15public class Distributor {16 private final Supplier<HttpClient> clientFactory;17 private final Tracer tracer;18 private final LocalDistributor distributor;19 private final LocalSessionMap sessions;20 public Distributor(Supplier<HttpClient> clientFactory, Tracer tracer) {21 this.clientFactory = Objects.requireNonNull(clientFactory);22 this.tracer = Objects.requireNonNull(tracer);23 this.sessions = new LocalSessionMap(tracer, new SessionMapOptions());24 this.distributor = new LocalDistributor(tracer, sessions, clientFactory);25 }26 public void add(String id, URI uri) {27 LocalNode node = new LocalNode(tracer, clientFactory, uri);28 distributor.add(node);29 GridModel model = new GridModel(sessions, distributor);30 model.add(id, uri);31 }32 public Routes getRoutes() {33 return new Routes()34 .add(new DistributorRoutes(distributor));35 }36 private static class DistributorRoutes implements Routable {37 private final LocalDistributor distributor;38 private DistributorRoutes(LocalDistributor distributor) {39 this.distributor = Objects.requireNonNull(distributor);40 }41 public void configure(Routes routes) {42 .get("/status", (req, res) -> {43 res.setStatus(200);44 res.setContent("OK");45 })46 .post("/session", (req, res) -> {47 Map<String, Object> session = distributor.newSession(req);48 res.setStatus(200);49 res.setContent(session);50 });51 }52 }53 public static void main(String[] args) {54 Tracer tracer = DefaultTestTracer.createTracer();55 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();56 Distributor distributor = new Distributor(clientFactory

Full Screen

Full Screen

add

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.node.local.LocalNode.Builder;5import org.openqa.selenium.grid.server.BaseServerOptions;6import org.openqa.selenium.grid.server.Server;7import org.openqa.selenium.grid.web.Routable;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.opentelemetry.OpenTelemetryTracer;13import java.net.URI;14import java.util.Collections;15import java.util.List;16import java.util.Optional;17import java.util.concurrent.TimeUnit;18public class GridModelAddNodeExample {19 public static void main(String[] args) throws Exception {20 Tracer tracer = new OpenTelemetryTracer();21 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();22 Builder builder = LocalNode.builder(tracer, clientFactory);23 builder.add(new BaseServerOptions() {24 public URI getExternalUri() {25 }26 });27 builder.add(new BaseServerOptions() {28 public URI getExternalUri() {29 }30 });31 LocalNode node = builder.build();32 LocalDistributor distributor = LocalDistributor.builder(tracer, clientFactory).build();33 GridModel gridModel = new GridModel(distributor);34 gridModel.add(node);35 Server<?> server = Server.builder(tracer)36 .add(new BaseServerOptions() {37 public URI getExternalUri() {38 }39 })40 .add(new BaseServerOptions() {41 public URI getExternalUri() {42 }43 })44 .add(distributor)45 .build();46 server.start();

Full Screen

Full Screen

add

Using AI Code Generation

copy

Full Screen

1 public void add(GridNode node) {2 Objects.requireNonNull(node);3 this.nodes.add(node);4 this.listeners.forEach(listener -> listener.nodeAdded(node));5 }6 public void remove(GridNode node) {7 Objects.requireNonNull(node);8 if (this.nodes.remove(node)) {9 this.listeners.forEach(listener -> listener.nodeRemoved(node));10 }11 }12 public void addListener(GridModelListener listener) {13 Objects.requireNonNull(listener);14 this.listeners.add(listener);15 }16 public void removeListener(GridModelListener listener) {17 Objects.requireNonNull(listener);18 this.listeners.remove(listener);19 }20 public Collection<GridNode> getNodes() {21 return Collections.unmodifiableCollection(this.nodes);22 }23 public Collection<ActiveSession> getActiveSessions() {24 return Collections.unmodifiableCollection(this.sessions.values());25 }26 public ActiveSession getActiveSession(SessionId id) {27 Objects.requireNonNull(id);28 return this.sessions.get(id);29 }30 public void addActiveSession(ActiveSession session) {31 Objects.requireNonNull(session);32 this.sessions.put(session.getId(), session);33 this.listeners.forEach(listener -> listener.sessionAdded(session));34 }35 public void removeActiveSession(ActiveSession session) {36 Objects.requireNonNull(session);37 if (this.sessions.remove(session.getId()) != null) {38 this.listeners.forEach(listener -> listener.sessionRemoved(session));39 }40 }41}42To add a node to the grid, we need to call the add() method of the GridModel class. Similarly, to remove a node from the grid, we need to call the

Full Screen

Full Screen

add

Using AI Code Generation

copy

Full Screen

1 public void add(GridNode node) {2 Objects.requireNonNull(node);3 if (node.isDown()) {4 logger.info("Not adding a down node: {}", node);5 return;6 }7 if (node.isDraining()) {8 logger.info("Not adding a draining node: {}", node);9 return;10 }11 if (node.isDrained()) {12 logger.info("Not adding a drained node: {}", node);13 return;14 }15 if (node.isPending()) {16 logger.info("Not adding a pending node: {}", node);17 return;18 }19 if (node.isTerminated()) {20 logger.info("Not adding a terminated node: {}", node);21 return;22 }23 if (node.isTerminating()) {24 logger.info("Not adding a terminating node: {}", node);25 return;26 }27 if (node.isUnresponsive()) {28 logger.info("Not adding an unresponsive node: {}", node);29 return;30 }31 if (node.isLostContact()) {32 logger.info("Not adding a lost contact node: {}", node);33 return;34 }35 if (node.isRebooting()) {36 logger.info("Not adding a rebooting node: {}", node);37 return;38 }39 if (node.isShuttingDown()) {40 logger.info("Not adding a shutting down node: {}", node);41 return;42 }43 if (node.isStarting()) {44 logger.info("Not adding a starting node: {}", node);45 return;46 }47 if (node.isTimedOut()) {48 logger.info("Not adding a timed out node: {}", node);49 return;50 }51 if (node.isUnknown()) {52 logger.info("Not adding an unknown node: {}", node);53 return;54 }55 if (node.isUnstable()) {56 logger.info("Not adding an unstable node: {}", node);57 return;58 }59 if (node.isNotReachable()) {60 logger.info("Not adding a not reachable node: {}", node);61 return;62 }63 if (node.isIncompatible()) {64 logger.info("Not adding an incompatible node: {}", node);65 return;66 }67 if (node.isDisabled()) {68 logger.info("Not adding a disabled node: {}", node);69 return;70 }71 if (node.isMaxSessionsReached()) {72 logger.info("Not adding a max sessions reached

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