How to use NodeId class of org.openqa.selenium.grid.data package

Best Selenium code snippet using org.openqa.selenium.grid.data.NodeId

Source:GridModel.java Github

copy

Full Screen

...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.NodeRemovedEvent;25import org.openqa.selenium.grid.data.NodeStatus;26import org.openqa.selenium.grid.data.NodeStatusEvent;27import org.openqa.selenium.grid.data.Session;28import org.openqa.selenium.grid.data.SessionClosedEvent;29import org.openqa.selenium.grid.data.Slot;30import org.openqa.selenium.grid.data.SlotId;31import org.openqa.selenium.grid.security.Secret;32import org.openqa.selenium.internal.Require;33import org.openqa.selenium.remote.SessionId;34import java.time.Instant;35import java.util.HashSet;36import java.util.Iterator;37import java.util.Map;38import java.util.Optional;39import java.util.Set;40import java.util.concurrent.ConcurrentHashMap;41import java.util.concurrent.locks.Lock;42import java.util.concurrent.locks.ReadWriteLock;43import java.util.concurrent.locks.ReentrantReadWriteLock;44import java.util.logging.Logger;45import static org.openqa.selenium.grid.data.Availability.DOWN;46import static org.openqa.selenium.grid.data.Availability.DRAINING;47import static org.openqa.selenium.grid.data.Availability.UP;48public class GridModel {49 private static final Logger LOG = Logger.getLogger(GridModel.class.getName());50 private static final SessionId RESERVED = new SessionId("reserved");51 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);52 private final Map<Availability, Set<NodeStatus>> nodes = new ConcurrentHashMap<>();53 private final EventBus events;54 public GridModel(EventBus events, Secret registrationSecret) {55 this.events = Require.nonNull("Event bus", events);56 Require.nonNull("Registration secret", registrationSecret);57 events.addListener(NodeDrainStarted.listener(nodeId -> setAvailability(nodeId, DRAINING)));58 events.addListener(NodeDrainComplete.listener(this::remove));59 events.addListener(NodeRemovedEvent.listener(this::remove));60 events.addListener(NodeStatusEvent.listener(status -> refresh(status)));61 events.addListener(SessionClosedEvent.listener(this::release));62 }63 public GridModel add(NodeStatus node) {64 Require.nonNull("Node", node);65 Lock writeLock = lock.writeLock();66 writeLock.lock();67 try {68 // If we've already added the node, remove it.69 for (Set<NodeStatus> nodes : nodes.values()) {70 Iterator<NodeStatus> iterator = nodes.iterator();71 while (iterator.hasNext()) {72 NodeStatus next = iterator.next();73 // If the ID is the same, we're re-adding a node. If the URI is the same a node probably restarted74 if (next.getId().equals(node.getId()) || next.getUri().equals(node.getUri())) {75 LOG.info(String.format("Re-adding node with id %s and URI %s.", node.getId(), node.getUri()));76 iterator.remove();77 }78 }79 }80 // Nodes are initially added in the "down" state until something changes their availability81 nodes(DOWN).add(node);82 } finally {83 writeLock.unlock();84 }85 return this;86 }87 public GridModel refresh(NodeStatus status) {88 Require.nonNull("Node status", status);89 Lock writeLock = lock.writeLock();90 writeLock.lock();91 try {92 AvailabilityAndNode availabilityAndNode = findNode(status.getId());93 if (availabilityAndNode == null) {94 return this;95 }96 // if the node was marked as "down", keep it down until a healthcheck passes:97 // just because the node can hit the event bus doesn't mean it's reachable98 if (DOWN.equals(availabilityAndNode.availability)) {99 nodes(DOWN).remove(availabilityAndNode.status);100 nodes(DOWN).add(status);101 return this;102 }103 // But do trust the node if it tells us it's draining104 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);105 nodes(status.getAvailability()).add(status);106 return this;107 } finally {108 writeLock.unlock();109 }110 }111 public GridModel remove(NodeId id) {112 Require.nonNull("Node ID", id);113 Lock writeLock = lock.writeLock();114 writeLock.lock();115 try {116 AvailabilityAndNode availabilityAndNode = findNode(id);117 if (availabilityAndNode == null) {118 return this;119 }120 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);121 return this;122 } finally {123 writeLock.unlock();124 }125 }126 public Availability setAvailability(NodeId id, Availability availability) {127 Require.nonNull("Node ID", id);128 Require.nonNull("Availability", availability);129 Lock writeLock = lock.writeLock();130 writeLock.lock();131 try {132 AvailabilityAndNode availabilityAndNode = findNode(id);133 if (availabilityAndNode == null) {134 return DOWN;135 }136 if (availability.equals(availabilityAndNode.availability)) {137 return availability;138 }139 nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);140 nodes(availability).add(availabilityAndNode.status);141 LOG.info(String.format(142 "Switching node %s (uri: %s) from %s to %s",143 id,144 availabilityAndNode.status.getUri(),145 availabilityAndNode.availability,146 availability));147 return availabilityAndNode.availability;148 } finally {149 writeLock.unlock();150 }151 }152 public boolean reserve(SlotId slotId) {153 Lock writeLock = lock.writeLock();154 writeLock.lock();155 try {156 AvailabilityAndNode node = findNode(slotId.getOwningNodeId());157 if (node == null) {158 LOG.warning(String.format("Asked to reserve slot on node %s, but unable to find node", slotId.getOwningNodeId()));159 return false;160 }161 if (!UP.equals(node.availability)) {162 LOG.warning(String.format(163 "Asked to reserve a slot on node %s, but not is %s",164 slotId.getOwningNodeId(),165 node.availability));166 return false;167 }168 Optional<Slot> maybeSlot = node.status.getSlots().stream()169 .filter(slot -> slotId.equals(slot.getId()))170 .findFirst();171 if (!maybeSlot.isPresent()) {172 LOG.warning(String.format(173 "Asked to reserve slot on node %s, but no slot with id %s found",174 node.status.getId(),175 slotId));176 return false;177 }178 reserve(node.status, maybeSlot.get());179 return true;180 } finally {181 writeLock.unlock();182 }183 }184 public Set<NodeStatus> getSnapshot() {185 Lock readLock = this.lock.readLock();186 readLock.lock();187 try {188 ImmutableSet.Builder<NodeStatus> snapshot = ImmutableSet.builder();189 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {190 entry.getValue().stream()191 .map(status -> rewrite(status, entry.getKey()))192 .forEach(snapshot::add);193 }194 return snapshot.build();195 } finally {196 readLock.unlock();197 }198 }199 private Set<NodeStatus> nodes(Availability availability) {200 return nodes.computeIfAbsent(availability, ignored -> new HashSet<>());201 }202 private AvailabilityAndNode findNode(NodeId id) {203 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {204 for (NodeStatus nodeStatus : entry.getValue()) {205 if (id.equals(nodeStatus.getId())) {206 return new AvailabilityAndNode(entry.getKey(), nodeStatus);207 }208 }209 }210 return null;211 }212 private NodeStatus rewrite(NodeStatus status, Availability availability) {213 return new NodeStatus(214 status.getId(),215 status.getUri(),216 status.getMaxSessionCount(),217 status.getSlots(),218 availability);219 }220 private void release(SessionId id) {221 if (id == null) {222 return;223 }224 Lock writeLock = lock.writeLock();225 writeLock.lock();226 try {227 for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {228 for (NodeStatus node : entry.getValue()) {229 for (Slot slot : node.getSlots()) {230 if (!slot.getSession().isPresent()) {231 continue;232 }233 if (id.equals(slot.getSession().get().getId())) {234 Slot released = new Slot(235 slot.getId(),236 slot.getStereotype(),237 slot.getLastStarted(),238 Optional.empty());239 amend(entry.getKey(), node, released);240 return;241 }242 }243 }244 }245 } finally {246 writeLock.unlock();247 }248 }249 private void reserve(NodeStatus status, Slot slot) {250 Instant now = Instant.now();251 Slot reserved = new Slot(252 slot.getId(),253 slot.getStereotype(),254 now,255 Optional.of(new Session(256 RESERVED,257 status.getUri(),258 slot.getStereotype(),259 slot.getStereotype(),260 now)));261 amend(UP, status, reserved);262 }263 public void setSession(SlotId slotId, Session session) {264 Require.nonNull("Slot ID", slotId);265 AvailabilityAndNode node = findNode(slotId.getOwningNodeId());266 if (node == null) {267 LOG.warning("Grid model and reality have diverged. Unable to find node " + slotId.getOwningNodeId());268 return;269 }270 Optional<Slot> maybeSlot = node.status.getSlots().stream()271 .filter(slot -> slotId.equals(slot.getId()))272 .findFirst();273 if (!maybeSlot.isPresent()) {274 LOG.warning("Grid model and reality have diverged. Unable to find slot " + slotId);275 return;276 }277 Slot slot = maybeSlot.get();278 Optional<Session> maybeSession = slot.getSession();279 if (!maybeSession.isPresent()) {280 LOG.warning("Grid model and reality have diverged. Slot is not reserved. " + slotId);281 return;...

Full Screen

Full Screen

Source:LocalDistributor.java Github

copy

Full Screen

...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 {237 readLock.unlock();238 }239 }240 @Override241 protected Supplier<CreateSessionResponse> reserve(SlotId slotId, CreateSessionRequest request) {242 Require.nonNull("Slot ID", slotId);243 Require.nonNull("New Session request", request);244 Lock writeLock = this.lock.writeLock();245 writeLock.lock();246 try {247 Node node = nodes.get(slotId.getOwningNodeId());248 if (node == null) {249 return () -> {250 throw new SessionNotCreatedException("Unable to find node");251 };252 }253 model.reserve(slotId);254 return () -> {255 Optional<CreateSessionResponse> response = node.newSession(request);256 if (!response.isPresent()) {257 model.setSession(slotId, null);258 throw new SessionNotCreatedException("Unable to create session for " + request);259 }260 model.setSession(slotId, response.get().getSession());261 return response.get();...

Full Screen

Full Screen

Source:Host.java Github

copy

Full Screen

...22import org.openqa.selenium.grid.data.Availability;23import org.openqa.selenium.grid.data.CreateSessionRequest;24import org.openqa.selenium.grid.data.CreateSessionResponse;25import org.openqa.selenium.grid.data.DistributorStatus;26import org.openqa.selenium.grid.data.NodeId;27import org.openqa.selenium.grid.data.NodeStatus;28import org.openqa.selenium.grid.data.Session;29import org.openqa.selenium.grid.node.HealthCheck;30import org.openqa.selenium.grid.node.Node;31import org.openqa.selenium.internal.Require;32import org.openqa.selenium.remote.SessionId;33import java.net.URI;34import java.util.HashMap;35import java.util.HashSet;36import java.util.Map;37import java.util.Objects;38import java.util.Set;39import java.util.concurrent.locks.Lock;40import java.util.concurrent.locks.ReadWriteLock;41import java.util.concurrent.locks.ReentrantReadWriteLock;42import java.util.function.Supplier;43import java.util.logging.Logger;44import static com.google.common.collect.ImmutableSet.toImmutableSet;45import static org.openqa.selenium.grid.data.Availability.DOWN;46import static org.openqa.selenium.grid.data.Availability.DRAINING;47import static org.openqa.selenium.grid.data.Availability.UP;48import static org.openqa.selenium.grid.data.SessionClosedEvent.SESSION_CLOSED;49import static org.openqa.selenium.grid.distributor.model.Slot.Status.ACTIVE;50import static org.openqa.selenium.grid.distributor.model.Slot.Status.AVAILABLE;51public class Host {52 private static final Logger LOG = Logger.getLogger("Selenium Host");53 private final Node node;54 private final NodeId nodeId;55 private final URI uri;56 private final Runnable performHealthCheck;57 // Used any time we need to read or modify the mutable state of this host58 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);59 private Availability status;60 private Set<Slot> slots;61 private int maxSessionCount;62 public Host(EventBus bus, Node node) {63 this.node = Require.nonNull("Node", node);64 this.nodeId = node.getId();65 this.uri = node.getUri();66 this.status = DOWN;67 this.slots = ImmutableSet.of();68 HealthCheck healthCheck = node.getHealthCheck();69 this.performHealthCheck = () -> {70 HealthCheck.Result result = healthCheck.check();71 Availability current = result.isAlive() ? UP : DOWN;72 Availability previous = setHostStatus(current);73 //If the node has been set to maintenance mode, set the status here as draining74 if (node.isDraining() || previous == DRAINING) {75 // We want to continue to allow the node to drain.76 setHostStatus(DRAINING);77 return;78 }79 if (current != previous) {80 LOG.info(String.format(81 "Changing status of node %s from %s to %s. Reason: %s",82 node.getId(),83 previous,84 current,85 result.getMessage()));86 }87 };88 bus.addListener(SESSION_CLOSED, event -> {89 SessionId id = event.getData(SessionId.class);90 this.slots.forEach(slot -> slot.onEnd(id));91 });92 update(node.getStatus());93 }94 public void update(NodeStatus status) {95 Require.nonNull("Node status", status);96 Lock writeLock = lock.writeLock();97 writeLock.lock();98 try {99 this.slots = status.getSlots().stream()100 .map(slot -> new Slot(node, slot.getStereotype(), slot.getSession().isPresent() ? ACTIVE : AVAILABLE))101 .collect(toImmutableSet());102 // By definition, we can never have more sessions than we have slots available103 this.maxSessionCount = Math.min(this.slots.size(), status.getMaxSessionCount());104 } finally {105 writeLock.unlock();106 }107 }108 public NodeId getId() {109 return nodeId;110 }111 public DistributorStatus.NodeSummary asSummary() {112 Map<Capabilities, Integer> stereotypes = new HashMap<>();113 Map<Capabilities, Integer> used = new HashMap<>();114 Set<Session> activeSessions = new HashSet<>();115 slots.forEach(slot -> {116 stereotypes.compute(slot.getStereotype(), (key, curr) -> curr == null ? 1 : curr + 1);117 if (slot.getStatus() != AVAILABLE) {118 used.compute(slot.getStereotype(), (key, curr) -> curr == null ? 1 : curr + 1);119 activeSessions.add(slot.getCurrentSession());120 }121 });122 return new DistributorStatus.NodeSummary(...

Full Screen

Full Screen

Source:Distributor.java Github

copy

Full Screen

...17package org.openqa.selenium.grid.distributor;18import org.openqa.selenium.SessionNotCreatedException;19import org.openqa.selenium.grid.data.CreateSessionResponse;20import org.openqa.selenium.grid.data.DistributorStatus;21import org.openqa.selenium.grid.data.NodeId;22import org.openqa.selenium.grid.data.Session;23import org.openqa.selenium.grid.data.SessionRequest;24import org.openqa.selenium.grid.node.Node;25import org.openqa.selenium.grid.security.RequiresSecretFilter;26import org.openqa.selenium.grid.security.Secret;27import org.openqa.selenium.internal.Either;28import org.openqa.selenium.internal.Require;29import org.openqa.selenium.json.Json;30import org.openqa.selenium.remote.http.HttpClient;31import org.openqa.selenium.remote.http.HttpRequest;32import org.openqa.selenium.remote.http.HttpResponse;33import org.openqa.selenium.remote.http.Routable;34import org.openqa.selenium.remote.http.Route;35import org.openqa.selenium.remote.tracing.SpanDecorator;36import org.openqa.selenium.remote.tracing.Tracer;37import org.openqa.selenium.status.HasReadyState;38import java.io.UncheckedIOException;39import java.util.Map;40import java.util.UUID;41import java.util.function.Predicate;42import static org.openqa.selenium.remote.http.Route.delete;43import static org.openqa.selenium.remote.http.Route.get;44import static org.openqa.selenium.remote.http.Route.post;45/**46 * Responsible for being the central place where the {@link Node}s47 * on which {@link Session}s run48 * are determined.49 * <p>50 * This class responds to the following URLs:51 * <table summary="HTTP commands the Distributor understands">52 * <tr>53 * <th>Verb</th>54 * <th>URL Template</th>55 * <th>Meaning</th>56 * </tr>57 * <tr>58 * <td>POST</td>59 * <td>/session</td>60 * <td>This is exactly the same as the New Session command61 * from the WebDriver spec.</td>62 * </tr>63 * <tr>64 * <td>POST</td>65 * <td>/se/grid/distributor/node</td>66 * <td>Adds a new {@link Node} to this distributor.67 * Please read the javadocs for {@link Node} for68 * how the Node should be serialized.</td>69 * </tr>70 * <tr>71 * <td>DELETE</td>72 * <td>/se/grid/distributor/node/{nodeId}</td>73 * <td>Remove the {@link Node} identified by {@code nodeId}74 * from this distributor. It is expected75 * that any sessions running on the Node are allowed to complete:76 * this simply means that no new77 * sessions will be scheduled on this Node.</td>78 * </tr>79 * </table>80 */81public abstract class Distributor implements HasReadyState, Predicate<HttpRequest>, Routable {82 private final Route routes;83 protected final Tracer tracer;84 protected Distributor(85 Tracer tracer,86 HttpClient.Factory httpClientFactory,87 Secret registrationSecret) {88 this.tracer = Require.nonNull("Tracer", tracer);89 Require.nonNull("HTTP client factory", httpClientFactory);90 Require.nonNull("Registration secret", registrationSecret);91 RequiresSecretFilter requiresSecret = new RequiresSecretFilter(registrationSecret);92 Json json = new Json();93 routes = Route.combine(94 post("/se/grid/distributor/node")95 .to(() ->96 new AddNode(tracer, this, json, httpClientFactory, registrationSecret))97 .with(requiresSecret),98 post("/se/grid/distributor/node/{nodeId}/drain")99 .to((Map<String, String> params) ->100 new DrainNode(this, new NodeId(UUID.fromString(params.get("nodeId")))))101 .with(requiresSecret),102 delete("/se/grid/distributor/node/{nodeId}")103 .to(params ->104 new RemoveNode(this, new NodeId(UUID.fromString(params.get("nodeId")))))105 .with(requiresSecret),106 post("/se/grid/distributor/session")107 .to(() -> new CreateSession(this))108 .with(requiresSecret),109 get("/se/grid/distributor/status")110 .to(() -> new GetDistributorStatus(this))111 .with(new SpanDecorator(tracer, req -> "distributor.status")));112 }113 public abstract Either<SessionNotCreatedException, CreateSessionResponse> newSession(SessionRequest request)114 throws SessionNotCreatedException;115 public abstract Distributor add(Node node);116 public abstract boolean drain(NodeId nodeId);117 public abstract void remove(NodeId nodeId);118 public abstract DistributorStatus getStatus();119 @Override120 public boolean test(HttpRequest httpRequest) {121 return matches(httpRequest);122 }123 @Override124 public boolean matches(HttpRequest req) {125 return routes.matches(req);126 }127 @Override128 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {129 return routes.execute(req);130 }131}...

Full Screen

Full Screen

Source:RemoteDistributor.java Github

copy

Full Screen

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

Full Screen

Full Screen

NodeId

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.NodeId;2import org.openqa.selenium.grid.data.Session;3import org.openqa.selenium.grid.data.SessionId;4import org.openqa.selenium.remote.http.HttpClient;5import org.openqa.selenium.remote.http.HttpRequest;6import org.openqa.selenium.remote.http.HttpResponse;7import java.net.URI;8import java.util.Optional;9public class NodeIdExample {10 public static void main(String[] args) {11 HttpRequest request = new HttpRequest("GET", "/se/grid/admin/HubStatisticsServlet");12 HttpResponse response = client.execute(request);13 String responseBody = response.getContentString();14 String nodeId = responseBody.split("nodeId=")[1].split(",")[0];15 NodeId id = new NodeId(nodeId);16 System.out.println("Node Id: " + id);17 }18}19import org.openqa.selenium.grid.data.Node;20import org.openqa.selenium.grid.data.NodeId;21import org.openqa.selenium.grid.data.Session;22import org.openqa.selenium.grid.data.SessionId;23import org.openqa.selenium.remote.http.HttpClient;24import org.openqa.selenium.remote.http.HttpRequest;25import org.openqa.selenium.remote.http.HttpResponse;26import java.net.URI;27import java.util.Optional;28public class NodeDetailsExample {29 public static void main(String[] args) {30 NodeId id = new NodeId("3a3e3c3b-3a3d-3b3c-3a3d-3a3e3b3c3d3e");31 Node node = client.execute(new HttpRequest("GET", "/se/grid/admin/HubStatisticsServlet")).getBody(Node.class);32 System.out.println("Node

Full Screen

Full Screen
copy
1private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {2 int subLength = prefix.length();3 return EntryStream.of(input)4 .mapKeys(key -> key.substring(subLength))5 .mapValues(AttributeType::GetByName)6 .toMap();7}8
Full Screen
copy
1Stream.of(input).toMap(e -> e.getKey().substring(subLength), 2 e -> AttributeType.GetByName(e.getValue()));3
Full Screen
copy
1private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {2 int subLength = prefix.length();3 return input.entrySet().stream()4 .collect(Collectors.toMap(5 entry -> entry.getKey().substring(subLength), 6 entry -> AttributeType.GetByName(entry.getValue())));7}8
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.

Most used methods in NodeId

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful