Best Selenium code snippet using org.openqa.selenium.grid.data.DistributorStatus
Source:LocalDistributorTest.java
...23import org.openqa.selenium.events.EventBus;24import org.openqa.selenium.events.local.GuavaEventBus;25import org.openqa.selenium.grid.data.CreateSessionResponse;26import org.openqa.selenium.grid.data.DefaultSlotMatcher;27import org.openqa.selenium.grid.data.DistributorStatus;28import org.openqa.selenium.grid.data.NodeStatus;29import org.openqa.selenium.grid.data.NodeStatusEvent;30import org.openqa.selenium.grid.data.RequestId;31import org.openqa.selenium.grid.data.Session;32import org.openqa.selenium.grid.distributor.Distributor;33import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;34import org.openqa.selenium.grid.node.Node;35import org.openqa.selenium.grid.node.local.LocalNode;36import org.openqa.selenium.grid.security.Secret;37import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;38import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;39import org.openqa.selenium.grid.data.SessionRequest;40import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;41import org.openqa.selenium.grid.testing.TestSessionFactory;42import org.openqa.selenium.internal.Either;43import org.openqa.selenium.remote.HttpSessionId;44import org.openqa.selenium.remote.SessionId;45import org.openqa.selenium.remote.http.HttpClient;46import org.openqa.selenium.remote.http.HttpHandler;47import org.openqa.selenium.remote.http.HttpRequest;48import org.openqa.selenium.remote.http.HttpResponse;49import org.openqa.selenium.remote.tracing.DefaultTestTracer;50import org.openqa.selenium.remote.tracing.Tracer;51import java.io.UncheckedIOException;52import java.net.URI;53import java.net.URISyntaxException;54import java.time.Duration;55import java.time.Instant;56import java.util.ArrayList;57import java.util.List;58import java.util.Map;59import java.util.Optional;60import java.util.Set;61import java.util.UUID;62import java.util.concurrent.Callable;63import java.util.concurrent.Executors;64import java.util.concurrent.Future;65import java.util.concurrent.TimeUnit;66import static org.assertj.core.api.Assertions.assertThat;67import static org.assertj.core.api.Assertions.fail;68import static org.openqa.selenium.grid.data.Availability.DRAINING;69import static org.openqa.selenium.remote.Dialect.W3C;70import static org.openqa.selenium.remote.http.HttpMethod.GET;71public class LocalDistributorTest {72 private final Secret registrationSecret = new Secret("bavarian smoked");73 private Tracer tracer;74 private EventBus bus;75 private HttpClient.Factory clientFactory;76 private URI uri;77 private Node localNode;78 @Before79 public void setUp() throws URISyntaxException {80 tracer = DefaultTestTracer.createTracer();81 bus = new GuavaEventBus();82 clientFactory = HttpClient.Factory.createDefault();83 Capabilities caps = new ImmutableCapabilities("browserName", "cheese");84 uri = new URI("http://localhost:1234");85 localNode = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)86 .add(caps, new TestSessionFactory((id, c) -> new Handler(c)))87 .maximumConcurrentSessions(2)88 .build();89 }90 @Test91 public void testAddNodeToDistributor() {92 NewSessionQueue queue = new LocalNewSessionQueue(93 tracer,94 bus,95 new DefaultSlotMatcher(),96 Duration.ofSeconds(2),97 Duration.ofSeconds(2),98 registrationSecret);99 Distributor distributor = new LocalDistributor(100 tracer,101 bus,102 clientFactory,103 new LocalSessionMap(tracer, bus),104 queue,105 new DefaultSlotSelector(),106 registrationSecret,107 Duration.ofMinutes(5),108 false);109 distributor.add(localNode);110 DistributorStatus status = distributor.getStatus();111 //Check the size112 final Set<NodeStatus> nodes = status.getNodes();113 assertThat(nodes.size()).isEqualTo(1);114 //Check a couple attributes115 NodeStatus distributorNode = nodes.iterator().next();116 assertThat(distributorNode.getId()).isEqualByComparingTo(localNode.getId());117 assertThat(distributorNode.getUri()).isEqualTo(uri);118 }119 @Test120 public void testShouldNotAddNodeWithWrongSecret() {121 Secret secret = new Secret("my_secret");122 NewSessionQueue queue = new LocalNewSessionQueue(123 tracer,124 bus,125 new DefaultSlotMatcher(),126 Duration.ofSeconds(2),127 Duration.ofSeconds(2),128 registrationSecret);129 Distributor secretDistributor = new LocalDistributor(130 tracer,131 bus,132 clientFactory,133 new LocalSessionMap(tracer, bus),134 queue,135 new DefaultSlotSelector(),136 secret,137 Duration.ofMinutes(5),138 false);139 bus.fire(new NodeStatusEvent(localNode.getStatus()));140 DistributorStatus status = secretDistributor.getStatus();141 //Check the size142 final Set<NodeStatus> nodes = status.getNodes();143 assertThat(nodes.size()).isEqualTo(0);144 }145 @Test146 public void testRemoveNodeFromDistributor() {147 NewSessionQueue queue = new LocalNewSessionQueue(148 tracer,149 bus,150 new DefaultSlotMatcher(),151 Duration.ofSeconds(2),152 Duration.ofSeconds(2),153 registrationSecret);154 Distributor distributor = new LocalDistributor(155 tracer,156 bus,157 clientFactory,158 new LocalSessionMap(tracer, bus),159 queue,160 new DefaultSlotSelector(),161 registrationSecret,162 Duration.ofMinutes(5),163 false);164 distributor.add(localNode);165 //Check the size166 DistributorStatus statusBefore = distributor.getStatus();167 final Set<NodeStatus> nodesBefore = statusBefore.getNodes();168 assertThat(nodesBefore.size()).isEqualTo(1);169 //Recheck the status--should be zero170 distributor.remove(localNode.getId());171 DistributorStatus statusAfter = distributor.getStatus();172 final Set<NodeStatus> nodesAfter = statusAfter.getNodes();173 assertThat(nodesAfter.size()).isEqualTo(0);174 }175 @Test176 public void testAddSameNodeTwice() {177 NewSessionQueue queue = new LocalNewSessionQueue(178 tracer,179 bus,180 new DefaultSlotMatcher(),181 Duration.ofSeconds(2),182 Duration.ofSeconds(2),183 registrationSecret);184 Distributor distributor = new LocalDistributor(185 tracer,186 bus,187 clientFactory,188 new LocalSessionMap(tracer, bus),189 queue,190 new DefaultSlotSelector(),191 registrationSecret,192 Duration.ofMinutes(5),193 false);194 distributor.add(localNode);195 distributor.add(localNode);196 DistributorStatus status = distributor.getStatus();197 //Should only be one node after dupe check198 final Set<NodeStatus> nodes = status.getNodes();199 assertThat(nodes.size()).isEqualTo(1);200 }201 @Test202 public void shouldBeAbleToAddMultipleSessionsConcurrently() throws Exception {203 NewSessionQueue queue = new LocalNewSessionQueue(204 tracer,205 bus,206 new DefaultSlotMatcher(),207 Duration.ofSeconds(2),208 Duration.ofSeconds(2),209 registrationSecret);210 LocalDistributor distributor = new LocalDistributor(211 tracer,212 bus,213 clientFactory,214 new LocalSessionMap(tracer, bus),215 queue,216 new DefaultSlotSelector(),217 registrationSecret,218 Duration.ofMinutes(5),219 false);220 // Add one node to ensure that everything is created in that.221 Capabilities caps = new ImmutableCapabilities("browserName", "cheese");222 class VerifyingHandler extends Session implements HttpHandler {223 private VerifyingHandler(SessionId id, Capabilities capabilities) {224 super(id, uri, new ImmutableCapabilities(), capabilities, Instant.now());225 }226 @Override227 public HttpResponse execute(HttpRequest req) {228 Optional<SessionId> id = HttpSessionId.getSessionId(req.getUri()).map(SessionId::new);229 assertThat(id).isEqualTo(Optional.of(getId()));230 return new HttpResponse();231 }232 }233 // Only use one node.234 Node node = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)235 .add(caps, new TestSessionFactory(VerifyingHandler::new))236 .add(caps, new TestSessionFactory(VerifyingHandler::new))237 .add(caps, new TestSessionFactory(VerifyingHandler::new))238 .maximumConcurrentSessions(3)239 .build();240 distributor.add(node);241 SessionRequest sessionRequest =242 new SessionRequest(243 new RequestId(UUID.randomUUID()),244 Instant.now(),245 Set.of(W3C),246 Set.of(new ImmutableCapabilities("browserName", "cheese")),247 Map.of(),248 Map.of());249 List<Callable<SessionId>> callables = new ArrayList<>();250 for (int i = 0; i < 3; i++) {251 callables.add(() -> {252 Either<SessionNotCreatedException, CreateSessionResponse> result =253 distributor.newSession(sessionRequest);254 if (result.isRight()) {255 CreateSessionResponse res = result.right();256 assertThat(res.getSession().getCapabilities().getBrowserName()).isEqualTo("cheese");257 return res.getSession().getId();258 } else {259 fail("Session creation failed", result.left());260 }261 return null;262 });263 }264 List<Future<SessionId>> futures = Executors.newFixedThreadPool(3).invokeAll(callables);265 for (Future<SessionId> future : futures) {266 SessionId id = future.get(2, TimeUnit.SECONDS);267 // Now send a random command.268 HttpResponse res = node.execute(new HttpRequest(GET, String.format("/session/%s/url", id)));269 assertThat(res.isSuccessful()).isTrue();270 }271 }272 @Test273 public void testDrainNodeFromDistributor() {274 NewSessionQueue queue = new LocalNewSessionQueue(275 tracer,276 bus,277 new DefaultSlotMatcher(),278 Duration.ofSeconds(2),279 Duration.ofSeconds(2),280 registrationSecret);281 Distributor distributor = new LocalDistributor(282 tracer,283 bus,284 clientFactory,285 new LocalSessionMap(tracer, bus),286 queue,287 new DefaultSlotSelector(),288 registrationSecret,289 Duration.ofMinutes(5),290 false);291 distributor.add(localNode);292 assertThat(localNode.isDraining()).isFalse();293 //Check the size - there should be one node294 DistributorStatus statusBefore = distributor.getStatus();295 Set<NodeStatus> nodesBefore = statusBefore.getNodes();296 assertThat(nodesBefore.size()).isEqualTo(1);297 NodeStatus nodeBefore = nodesBefore.iterator().next();298 assertThat(nodeBefore.getAvailability()).isNotEqualTo(DRAINING);299 distributor.drain(localNode.getId());300 assertThat(localNode.isDraining()).isTrue();301 //Recheck the status - there should still be no node, it is removed302 DistributorStatus statusAfter = distributor.getStatus();303 Set<NodeStatus> nodesAfter = statusAfter.getNodes();304 assertThat(nodesAfter.size()).isEqualTo(0);305 }306 @Test307 public void testDrainNodeFromNode() {308 assertThat(localNode.isDraining()).isFalse();309 NewSessionQueue queue = new LocalNewSessionQueue(310 tracer,311 bus,312 new DefaultSlotMatcher(),313 Duration.ofSeconds(2),314 Duration.ofSeconds(2),315 registrationSecret);316 Distributor distributor = new LocalDistributor(...
Source:LocalDistributor.java
...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 }...
Source:AddingNodesTest.java
...28import org.openqa.selenium.events.EventBus;29import org.openqa.selenium.grid.component.HealthCheck;30import org.openqa.selenium.grid.data.CreateSessionRequest;31import org.openqa.selenium.grid.data.CreateSessionResponse;32import org.openqa.selenium.grid.data.DistributorStatus;33import org.openqa.selenium.grid.data.NodeStatus;34import org.openqa.selenium.grid.data.NodeStatusEvent;35import org.openqa.selenium.grid.data.Session;36import org.openqa.selenium.grid.data.SessionClosedEvent;37import org.openqa.selenium.grid.distributor.local.LocalDistributor;38import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;39import org.openqa.selenium.grid.node.CapabilityResponseEncoder;40import org.openqa.selenium.grid.node.Node;41import org.openqa.selenium.grid.node.local.LocalNode;42import org.openqa.selenium.events.local.GuavaEventBus;43import org.openqa.selenium.grid.testing.TestSessionFactory;44import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;45import org.openqa.selenium.grid.web.CombinedHandler;46import org.openqa.selenium.grid.web.RoutableHttpClientFactory;47import org.openqa.selenium.remote.SessionId;48import org.openqa.selenium.remote.http.HttpClient;49import org.openqa.selenium.remote.http.HttpRequest;50import org.openqa.selenium.remote.http.HttpResponse;51import org.openqa.selenium.remote.tracing.DistributedTracer;52import org.openqa.selenium.support.ui.FluentWait;53import org.openqa.selenium.support.ui.Wait;54import java.net.MalformedURLException;55import java.net.URI;56import java.net.URISyntaxException;57import java.net.URL;58import java.time.Duration;59import java.util.HashSet;60import java.util.Objects;61import java.util.Optional;62import java.util.Set;63import java.util.UUID;64import java.util.function.Function;65public class AddingNodesTest {66 private static final Capabilities CAPS = new ImmutableCapabilities("cheese", "gouda");67 private Distributor distributor;68 private DistributedTracer tracer;69 private EventBus bus;70 private HttpClient.Factory clientFactory;71 private Wait<Object> wait;72 private URL externalUrl;73 private CombinedHandler handler;74 @Before75 public void setUpDistributor() throws MalformedURLException {76 tracer = DistributedTracer.builder().build();77 bus = new GuavaEventBus();78 handler = new CombinedHandler();79 externalUrl = new URL("http://example.com");80 clientFactory = new RoutableHttpClientFactory(81 externalUrl,82 handler,83 HttpClient.Factory.createDefault());84 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);85 Distributor local = new LocalDistributor(tracer, bus, clientFactory, sessions);86 handler.addHandler(local);87 distributor = new RemoteDistributor(tracer, clientFactory, externalUrl);88 wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(2));89 }90 @Test91 public void shouldBeAbleToRegisterALocalNode() throws URISyntaxException {92 URI sessionUri = new URI("http://example:1234");93 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())94 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))95 .build();96 handler.addHandler(node);97 distributor.add(node);98 wait.until(obj -> distributor.getStatus().hasCapacity());99 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());100 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());101 }102 @Test103 public void shouldBeAbleToRegisterACustomNode() throws URISyntaxException {104 URI sessionUri = new URI("http://example:1234");105 Node node = new CustomNode(106 tracer,107 bus,108 UUID.randomUUID(),109 externalUrl.toURI(),110 c -> new Session(new SessionId(UUID.randomUUID()), sessionUri, c));111 handler.addHandler(node);112 distributor.add(node);113 wait.until(obj -> distributor.getStatus().hasCapacity());114 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());115 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());116 }117 @Test118 public void shouldBeAbleToRegisterNodesByListeningForEvents() throws URISyntaxException {119 URI sessionUri = new URI("http://example:1234");120 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())121 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))122 .build();123 handler.addHandler(node);124 bus.fire(new NodeStatusEvent(node.getStatus()));125 wait.until(obj -> distributor.getStatus().hasCapacity());126 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());127 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());128 }129 @Test130 public void distributorShouldUpdateStateOfExistingNodeWhenNodePublishesStateChange()131 throws URISyntaxException {132 URI sessionUri = new URI("http://example:1234");133 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())134 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))135 .build();136 handler.addHandler(node);137 bus.fire(new NodeStatusEvent(node.getStatus()));138 // Start empty139 wait.until(obj -> distributor.getStatus().hasCapacity());140 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());141 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());142 // Craft a status that makes it look like the node is busy, and post it on the bus.143 NodeStatus status = node.getStatus();144 NodeStatus crafted = new NodeStatus(145 status.getNodeId(),146 status.getUri(),147 status.getMaxSessionCount(),148 status.getStereotypes(),149 ImmutableSet.of(new NodeStatus.Active(CAPS, new SessionId(UUID.randomUUID()), CAPS)));150 bus.fire(new NodeStatusEvent(crafted));151 // We claimed the only slot is filled. Life is good.152 wait.until(obj -> !distributor.getStatus().hasCapacity());153 }154 static class CustomNode extends Node {...
Source:Grid.java
...18import com.google.common.base.Suppliers;19import com.google.common.collect.ImmutableList;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.ImmutableCapabilities;22import org.openqa.selenium.grid.data.DistributorStatus;23import org.openqa.selenium.grid.data.NodeStatus;24import org.openqa.selenium.grid.data.SessionRequestCapability;25import org.openqa.selenium.grid.data.Slot;26import org.openqa.selenium.grid.distributor.Distributor;27import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;28import org.openqa.selenium.internal.Require;29import org.openqa.selenium.json.Json;30import java.net.URI;31import java.util.ArrayList;32import java.util.Collection;33import java.util.HashMap;34import java.util.List;35import java.util.Map;36import java.util.Set;37import java.util.function.Supplier;38import java.util.stream.Collectors;39public class Grid {40 private static final Json JSON = new Json();41 private final URI uri;42 private final Supplier<DistributorStatus> distributorStatus;43 private final List<Set<Capabilities>> queueInfoList;44 private final String version;45 public Grid(46 Distributor distributor,47 NewSessionQueue newSessionQueue,48 URI uri,49 String version) {50 Require.nonNull("Distributor", distributor);51 this.uri = Require.nonNull("Grid's public URI", uri);52 NewSessionQueue sessionQueue = Require.nonNull("New session queue", newSessionQueue);53 this.queueInfoList = sessionQueue54 .getQueueContents()55 .stream()56 .map(SessionRequestCapability::getDesiredCapabilities)...
Source:RemoteDistributor.java
...17package org.openqa.selenium.grid.distributor.remote;18import org.openqa.selenium.SessionNotCreatedException;19import org.openqa.selenium.grid.data.CreateSessionRequest;20import org.openqa.selenium.grid.data.CreateSessionResponse;21import org.openqa.selenium.grid.data.DistributorStatus;22import org.openqa.selenium.grid.data.NodeId;23import org.openqa.selenium.grid.data.NodeStatus;24import org.openqa.selenium.grid.data.SlotId;25import org.openqa.selenium.grid.distributor.Distributor;26import org.openqa.selenium.grid.node.Node;27import org.openqa.selenium.grid.security.Secret;28import org.openqa.selenium.grid.sessionmap.NullSessionMap;29import org.openqa.selenium.grid.web.Values;30import org.openqa.selenium.internal.Require;31import org.openqa.selenium.remote.http.HttpClient;32import org.openqa.selenium.remote.http.HttpHandler;33import org.openqa.selenium.remote.http.HttpRequest;34import org.openqa.selenium.remote.http.HttpResponse;35import org.openqa.selenium.remote.tracing.HttpTracing;36import org.openqa.selenium.remote.tracing.Tracer;37import java.net.URL;38import java.util.Set;39import java.util.function.Supplier;40import java.util.logging.Logger;41import static org.openqa.selenium.remote.http.Contents.asJson;42import static org.openqa.selenium.remote.http.HttpMethod.DELETE;43import static org.openqa.selenium.remote.http.HttpMethod.GET;44import static org.openqa.selenium.remote.http.HttpMethod.POST;45public class RemoteDistributor extends Distributor {46 private static final Logger LOG = Logger.getLogger("Selenium Distributor (Remote)");47 private final HttpHandler client;48 public RemoteDistributor(Tracer tracer, HttpClient.Factory factory, URL url, Secret registrationSecret) {49 super(50 tracer,51 factory,52 (caps, nodes) -> {throw new UnsupportedOperationException("host selection");},53 new NullSessionMap(tracer),54 registrationSecret);55 this.client = factory.createClient(url);56 }57 @Override58 public boolean isReady() {59 try {60 return client.execute(new HttpRequest(GET, "/readyz")).isSuccessful();61 } catch (Exception e) {62 return false;63 }64 }65 @Override66 public CreateSessionResponse newSession(HttpRequest request)67 throws SessionNotCreatedException {68 HttpRequest upstream = new HttpRequest(POST, "/se/grid/distributor/session");69 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);70 upstream.setContent(request.getContent());71 HttpResponse response = client.execute(upstream);72 return Values.get(response, CreateSessionResponse.class);73 }74 @Override75 public RemoteDistributor add(Node node) {76 HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/node");77 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);78 request.setContent(asJson(node.getStatus()));79 HttpResponse response = client.execute(request);80 Values.get(response, Void.class);81 LOG.info(String.format("Added node %s.", node.getId()));82 return this;83 }84 @Override85 public boolean drain(NodeId nodeId) {86 Require.nonNull("Node ID", nodeId);87 HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/node/" + nodeId + "/drain");88 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);89 request.setContent(asJson(nodeId));90 HttpResponse response = client.execute(request);91 return Values.get(response, Boolean.class);92 }93 @Override94 public void remove(NodeId nodeId) {95 Require.nonNull("Node ID", nodeId);96 HttpRequest request = new HttpRequest(DELETE, "/se/grid/distributor/node/" + nodeId);97 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);98 HttpResponse response = client.execute(request);99 Values.get(response, Void.class);100 }101 @Override102 public DistributorStatus getStatus() {103 HttpRequest request = new HttpRequest(GET, "/se/grid/distributor/status");104 HttpTracing.inject(tracer, tracer.getCurrentContext(), request);105 HttpResponse response = client.execute(request);106 return Values.get(response, DistributorStatus.class);107 }108 @Override109 protected Set<NodeStatus> getAvailableNodes() {110 throw new UnsupportedOperationException("getModel is not required for remote sessions");111 }112 @Override113 protected Supplier<CreateSessionResponse> reserve(SlotId slot, CreateSessionRequest request) {114 throw new UnsupportedOperationException("reserve is not required for remote sessions");115 }116}...
Source:SessionData.java
...17package org.openqa.selenium.grid.graphql;18import com.google.common.base.Suppliers;19import graphql.schema.DataFetcher;20import graphql.schema.DataFetchingEnvironment;21import org.openqa.selenium.grid.data.DistributorStatus;22import org.openqa.selenium.grid.data.NodeStatus;23import org.openqa.selenium.grid.data.Slot;24import org.openqa.selenium.grid.distributor.Distributor;25import org.openqa.selenium.internal.Require;26import java.util.Optional;27import java.util.Set;28import java.util.function.Supplier;29public class SessionData implements DataFetcher {30 private final Supplier<DistributorStatus> distributorStatus;31 public SessionData(Distributor distributor) {32 distributorStatus = Suppliers.memoize(Require.nonNull("Distributor", distributor)::getStatus);33 }34 @Override35 public Object get(DataFetchingEnvironment environment) {36 String sessionId = environment.getArgument("id");37 if (sessionId.isEmpty()) {38 throw new SessionNotFoundException("Session id is empty. A valid session id is required.");39 }40 Set<NodeStatus> nodeStatuses = distributorStatus.get().getNodes();41 SessionInSlot currentSession = findSession(sessionId, nodeStatuses);42 if (currentSession != null) {43 org.openqa.selenium.grid.data.Session session = currentSession.session;44 return new org.openqa.selenium.grid.graphql.Session(...
DistributorStatus
Using AI Code Generation
1import org.openqa.selenium.grid.data.DistributorStatus;2import org.openqa.selenium.grid.data.DistributorStatus.Builder;3import org.openqa.selenium.grid.data.NodeStatus;4import org.openqa.selenium.grid.data.NodeStatusEvent;5import org.openqa.selenium.grid.data.NodeStatusEvent.NodeStatusEventSource;6import org.openqa.selenium.grid.data.NodeStatusEvent.NodeStatusEventType;7import org.openqa.selenium.grid.data.Session;8import org.openqa.selenium.grid.data.SessionRequest;9import org.openqa.selenium.grid.data.SessionRequestEvent;10import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestEventSource;11import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestEventType;12import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestFailure;13import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestSuccess;14import org.openqa.selenium.grid.data.SessionRequestFailureReason;15import org.openqa.selenium.grid.data.SessionRequestSuccessEvent;16import org.openqa.selenium.grid.data.SessionRequestSuccessEvent.SessionRequestSuccessEventSource;17import org.openqa.selenium.grid.data.SessionRequestSuccessEvent.SessionRequestSuccessEventType;18import org.openqa.selenium.grid.data.SessionStartedEvent;19import org.openqa.selenium.grid.data.SessionStartedEvent.SessionStartedEventSource;20import org.openqa.selenium.grid.data.SessionStartedEvent.SessionStartedEventType;21import org.openqa.selenium.grid.data.SessionTerminatedEvent;22import org.openqa.selenium.grid.data.SessionTerminatedEvent.SessionTerminatedEventSource;23import org.openqa.selenium.grid.data.SessionTerminatedEvent.SessionTerminatedEventType;24import org.openqa.selenium.grid.data.SessionTerminatedEvent.SessionTerminatedFailure;25import org.openqa.selenium.grid.data.SessionTerminatedEvent.SessionTerminatedSuccess;26import org.openqa.selenium.grid.data.SessionTerminatedFailureReason;27import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent;28import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent.SessionTerminatedSuccessEventSource;29import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent.SessionTerminatedSuccessEventType;30import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent.SessionTerminatedSuccessEventSuccess;31import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent.SessionTerminatedSuccessEventFailure;32import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent.SessionTerminatedSuccessEventFailure.SessionTerminatedSuccessEventFailureReason;33import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent.SessionTerminatedSuccessEventSuccess.SessionTerminatedSuccessEventSuccessReason;34import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent.SessionTerminatedSuccessEventType;35import org.openqa.selenium.grid.data.SessionTerminatedSuccessEvent.SessionTerminatedSuccessEventSuccess;36import org.openqa.selenium.grid.data.SessionTerminated
DistributorStatus
Using AI Code Generation
1DistributorStatus status = new DistributorStatus();2DistributorStatus.Builder builder = new DistributorStatus.Builder();3DistributorStatus.Builder builder = new DistributorStatus.Builder();4DistributorStatus status = new DistributorStatus();5DistributorStatus.Builder builder = new DistributorStatus.Builder();6DistributorStatus.Builder builder = new DistributorStatus.Builder();7DistributorStatus status = new DistributorStatus();8DistributorStatus.Builder builder = new DistributorStatus.Builder();9DistributorStatus.Builder builder = new DistributorStatus.Builder();10DistributorStatus status = new DistributorStatus();11DistributorStatus.Builder builder = new DistributorStatus.Builder();12DistributorStatus.Builder builder = new DistributorStatus.Builder();13DistributorStatus status = new DistributorStatus();14DistributorStatus.Builder builder = new DistributorStatus.Builder();15DistributorStatus.Builder builder = new DistributorStatus.Builder();16DistributorStatus status = new DistributorStatus();17DistributorStatus.Builder builder = new DistributorStatus.Builder();18DistributorStatus.Builder builder = new DistributorStatus.Builder();
DistributorStatus
Using AI Code Generation
1DistributorStatus distributorStatus = DistributorStatus.createDistributorStatus(1, 2, 3, 4);2System.out.println(distributorStatus.getUri());3System.out.println(distributorStatus.getSlots());4System.out.println(distributorStatus.getTotal());5System.out.println(distributorStatus.getUsed());6System.out.println(distributorStatus.getAvailable());7import org.openqa.selenium.grid.data.DistributorStatus;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.DefaultTestTracer;12import org.openqa.selenium.remote.tracer.Tracer;13public class DistributorStatusClassExample3 {14 public static void main(String[] args) {15 Tracer tracer = DefaultTestTracer.createTracer();16 HttpClient httpClient = new HttpClient() {17 public HttpResponse execute(HttpRequest httpRequest) throws IOException {18 return null;19 }20 };21 System.out.println(distributorStatus.getUri());22 System.out.println(distributorStatus.getSlots());23 System.out.println(distributorStatus.getTotal());24 System.out.println(distributorStatus.getUsed());25 System.out.println(distributorStatus.getAvailable());26 }27}28import org.openqa.selenium.grid.data.DistributorStatus;29import org.openqa.selenium.grid.data.NodeId;30import org.openqa.selenium.grid.data.NodeStatus;31import org.openqa.selenium.grid.data.Session;32import org.openqa.selenium.grid.data.SessionId;33import org.openqa.selenium.grid.data.Slot;34import org
DistributorStatus
Using AI Code Generation
1import org.openqa.selenium.grid.data.DistributorStatus; 2import org.openqa.selenium.grid.distributor.Distributor; 3import org.openqa.selenium.grid.distributor.local.LocalDistributor; 4import org.openqa.selenium.grid.server.AddWebDriverSpecHeaders; 5import org.openqa.selenium.grid.server.BaseServerOptions; 6import org.openqa.selenium.grid.server.Server; 7import org.openqa.selenium.grid.server.SeleniumServer; 8import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions; 9import org.openqa.selenium.grid.web.CommandHandler; 10import org.openqa.selenium.grid.web.Routable; 11import org.openqa.selenium.grid.web.Routes; 12import org.openqa.selenium.internal.Require; 13import org.openqa.selenium.remote.http.HttpMethod; 14import org.openqa.selenium.remote.http.HttpRequest; 15import org.openqa.selenium.remote.http.HttpResponse; 16import org.openqa.selenium.remote.http.Route;17import java.util.Objects; 18import java.util.function.Supplier;19public class DistributorServer implements Server { 20private final Supplier<Distributor> distributorFactory; 21private final Server delegate; 22public DistributorServer(BaseServerOptions options, 23Supplier<Distributor> distributorFactory) { 24Require.nonNull("Distributor factory", distributorFactory); 25Require.nonNull("Server options", options); 26this.distributorFactory = distributorFactory; 27this.delegate = new SeleniumServer(options, new DistributorHandlers(distributorFactory)); 28}
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!!