Best Selenium code snippet using org.openqa.selenium.grid.data.Slot.getSession
Source:LocalDistributor.java
...160 Tracer tracer = new LoggingOptions(config).getTracer();161 EventBus bus = new EventBusOptions(config).getEventBus();162 DistributorOptions distributorOptions = new DistributorOptions(config);163 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);164 SessionMap sessions = new SessionMapOptions(config).getSessionMap();165 SecretOptions secretOptions = new SecretOptions(config);166 NewSessionQueue sessionQueue = new NewSessionQueueOptions(config).getSessionQueue(167 "org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue");168 return new LocalDistributor(169 tracer,170 bus,171 clientFactory,172 sessions,173 sessionQueue,174 distributorOptions.getSlotSelector(),175 secretOptions.getRegistrationSecret(),176 distributorOptions.getHealthCheckInterval(),177 distributorOptions.shouldRejectUnsupportedCaps());178 }179 @Override180 public boolean isReady() {181 try {182 return ImmutableSet.of(bus, sessions).parallelStream()183 .map(HasReadyState::isReady)184 .reduce(true, Boolean::logicalAnd);185 } catch (RuntimeException e) {186 return false;187 }188 }189 private void register(NodeStatus status) {190 Require.nonNull("Node", status);191 Lock writeLock = lock.writeLock();192 writeLock.lock();193 try {194 if (nodes.containsKey(status.getId())) {195 return;196 }197 Set<Capabilities> capabilities = status.getSlots().stream()198 .map(Slot::getStereotype)199 .map(ImmutableCapabilities::copyOf)200 .collect(toImmutableSet());201 // A new node! Add this as a remote node, since we've not called add202 RemoteNode remoteNode = new RemoteNode(203 tracer,204 clientFactory,205 status.getId(),206 status.getUri(),207 registrationSecret,208 capabilities);209 add(remoteNode);210 } finally {211 writeLock.unlock();212 }213 }214 @Override215 public LocalDistributor add(Node node) {216 Require.nonNull("Node", node);217 LOG.info(String.format("Added node %s at %s.", node.getId(), node.getUri()));218 nodes.put(node.getId(), node);219 model.add(node.getStatus());220 // Extract the health check221 Runnable runnableHealthCheck = asRunnableHealthCheck(node);222 allChecks.put(node.getId(), runnableHealthCheck);223 hostChecker.submit(runnableHealthCheck, healthcheckInterval, Duration.ofSeconds(30));224 bus.fire(new NodeAddedEvent(node.getId()));225 return this;226 }227 private Runnable asRunnableHealthCheck(Node node) {228 HealthCheck healthCheck = node.getHealthCheck();229 NodeId id = node.getId();230 return () -> {231 HealthCheck.Result result;232 try {233 result = healthCheck.check();234 } catch (Exception e) {235 LOG.log(Level.WARNING, "Unable to process node " + id, e);236 result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");237 }238 Lock writeLock = lock.writeLock();239 writeLock.lock();240 try {241 model.setAvailability(id, result.getAvailability());242 } finally {243 writeLock.unlock();244 }245 };246 }247 @Override248 public boolean drain(NodeId nodeId) {249 Node node = nodes.get(nodeId);250 if (node == null) {251 LOG.info("Asked to drain unregistered node " + nodeId);252 return false;253 }254 Lock writeLock = lock.writeLock();255 writeLock.lock();256 try {257 node.drain();258 model.setAvailability(nodeId, DRAINING);259 } finally {260 writeLock.unlock();261 }262 return node.isDraining();263 }264 public void remove(NodeId nodeId) {265 Lock writeLock = lock.writeLock();266 writeLock.lock();267 try {268 model.remove(nodeId);269 Runnable runnable = allChecks.remove(nodeId);270 if (runnable != null) {271 hostChecker.remove(runnable);272 }273 } finally {274 writeLock.unlock();275 }276 }277 @Override278 public DistributorStatus getStatus() {279 Lock readLock = this.lock.readLock();280 readLock.lock();281 try {282 return new DistributorStatus(model.getSnapshot());283 } finally {284 readLock.unlock();285 }286 }287 @Beta288 public void refresh() {289 List<Runnable> allHealthChecks = new ArrayList<>();290 Lock readLock = this.lock.readLock();291 readLock.lock();292 try {293 allHealthChecks.addAll(allChecks.values());294 } finally {295 readLock.unlock();296 }297 allHealthChecks.parallelStream().forEach(Runnable::run);298 }299 protected Set<NodeStatus> getAvailableNodes() {300 Lock readLock = this.lock.readLock();301 readLock.lock();302 try {303 return model.getSnapshot().stream()304 .filter(node -> !DOWN.equals(node.getAvailability()))305 .collect(toImmutableSet());306 } finally {307 readLock.unlock();308 }309 }310 @Override311 public Either<SessionNotCreatedException, CreateSessionResponse> newSession(SessionRequest request)312 throws SessionNotCreatedException {313 Require.nonNull("Requests to process", request);314 Span span = tracer.getCurrentContext().createSpan("distributor.new_session");315 Map<String, EventAttributeValue> attributeMap = new HashMap<>();316 try {317 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),318 EventAttribute.setValue(getClass().getName()));319 attributeMap.put("request.payload", EventAttribute.setValue(request.getDesiredCapabilities().toString()));320 String sessionReceivedMessage = "Session request received by the distributor";321 span.addEvent(sessionReceivedMessage, attributeMap);322 LOG.info(String.format("%s: \n %s", sessionReceivedMessage, request.getDesiredCapabilities()));323 // If there are no capabilities at all, something is horribly wrong324 if (request.getDesiredCapabilities().isEmpty()) {325 SessionNotCreatedException exception =326 new SessionNotCreatedException("No capabilities found in session request payload");327 EXCEPTION.accept(attributeMap, exception);328 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),329 EventAttribute.setValue("Unable to create session. No capabilities found: " +330 exception.getMessage()));331 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);332 return Either.left(exception);333 }334 boolean retry = false;335 SessionNotCreatedException lastFailure = new SessionNotCreatedException("Unable to create new session");336 for (Capabilities caps : request.getDesiredCapabilities()) {337 if (!isSupported(caps)) {338 continue;339 }340 // Try and find a slot that we can use for this session. While we341 // are finding the slot, no other session can possibly be started.342 // Therefore, spend as little time as possible holding the write343 // lock, and release it as quickly as possible. Under no344 // circumstances should we try to actually start the session itself345 // in this next block of code.346 SlotId selectedSlot = reserveSlot(request.getRequestId(), caps);347 if (selectedSlot == null) {348 LOG.info(String.format("Unable to find slot for request %s. May retry: %s ", request.getRequestId(), caps));349 retry = true;350 continue;351 }352 CreateSessionRequest singleRequest = new CreateSessionRequest(353 request.getDownstreamDialects(),354 caps,355 request.getMetadata());356 try {357 CreateSessionResponse response = startSession(selectedSlot, singleRequest);358 sessions.add(response.getSession());359 model.setSession(selectedSlot, response.getSession());360 SessionId sessionId = response.getSession().getId();361 Capabilities sessionCaps = response.getSession().getCapabilities();362 String sessionUri = response.getSession().getUri().toString();363 SESSION_ID.accept(span, sessionId);364 CAPABILITIES.accept(span, sessionCaps);365 SESSION_ID_EVENT.accept(attributeMap, sessionId);366 CAPABILITIES_EVENT.accept(attributeMap, sessionCaps);367 span.setAttribute(SESSION_URI.getKey(), sessionUri);368 attributeMap.put(SESSION_URI.getKey(), EventAttribute.setValue(sessionUri));369 String sessionCreatedMessage = "Session created by the distributor";370 span.addEvent(sessionCreatedMessage, attributeMap);371 LOG.info(String.format("%s. Id: %s, Caps: %s", sessionCreatedMessage, sessionId, sessionCaps));372 return Either.right(response);373 } catch (SessionNotCreatedException e) {374 model.setSession(selectedSlot, null);375 lastFailure = e;376 }...
Source:GraphqlHandlerTest.java
...258 distributor.add(node);259 wait.until(obj -> distributor.getStatus().hasCapacity());260 Either<SessionNotCreatedException, CreateSessionResponse> response = distributor.newSession(sessionRequest);261 if (response.isRight()) {262 Session session = response.right().getSession();263 assertThat(session).isNotNull();264 GraphqlHandler handler = new GraphqlHandler(tracer, distributor, queue, publicUri, version);265 Map<String, Object> topLevel = executeQuery(handler,266 "{ grid { sessionCount } }");267 assertThat(topLevel).isEqualTo(268 singletonMap(269 "data", singletonMap(270 "grid", singletonMap(271 "sessionCount", 1L ))));272 } else {273 fail("Session creation failed", response.left());274 }275 }276 @Test277 public void shouldBeAbleToGetSessionInfo() throws URISyntaxException {278 String nodeUrl = "http://localhost:5556";279 URI nodeUri = new URI(nodeUrl);280 Node node = LocalNode.builder(tracer, events, nodeUri, publicUri, registrationSecret)281 .add(caps, new TestSessionFactory((id, caps) -> new org.openqa.selenium.grid.data.Session(282 id,283 nodeUri,284 stereotype,285 caps,286 Instant.now()))).build();287 distributor.add(node);288 wait.until(obj -> distributor.getStatus().hasCapacity());289 Either<SessionNotCreatedException, CreateSessionResponse> response = distributor.newSession(sessionRequest);290 if (response.isRight()) {291 Session session = response.right().getSession();292 assertThat(session).isNotNull();293 String sessionId = session.getId().toString();294 Set<Slot> slots = distributor.getStatus().getNodes().stream().findFirst().get().getSlots();295 Slot slot = slots.stream().findFirst().get();296 org.openqa.selenium.grid.graphql.Session graphqlSession =297 new org.openqa.selenium.grid.graphql.Session(298 sessionId,299 session.getCapabilities(),300 session.getStartTime(),301 session.getUri(),302 node.getId().toString(),303 node.getUri(),304 slot);305 String query = String.format(306 "{ session (id: \"%s\") { id, capabilities, startTime, uri } }", sessionId);307 GraphqlHandler handler = new GraphqlHandler(tracer, distributor, queue, publicUri, version);308 Map<String, Object> result = executeQuery(handler, query);309 assertThat(result).describedAs(result.toString()).isEqualTo(310 singletonMap(311 "data", singletonMap(312 "session", ImmutableMap.of(313 "id", sessionId,314 "capabilities", graphqlSession.getCapabilities(),315 "startTime", graphqlSession.getStartTime(),316 "uri", graphqlSession.getUri().toString()))));317 } else {318 fail("Session creation failed", response.left());319 }320 }321 @Test322 public void shouldBeAbleToGetNodeInfoForSession() throws URISyntaxException {323 String nodeUrl = "http://localhost:5556";324 URI nodeUri = new URI(nodeUrl);325 Node node = LocalNode.builder(tracer, events, nodeUri, publicUri, registrationSecret)326 .add(caps, new TestSessionFactory((id, caps) -> new org.openqa.selenium.grid.data.Session(327 id,328 nodeUri,329 stereotype,330 caps,331 Instant.now()))).build();332 distributor.add(node);333 wait.until(obj -> distributor.getStatus().hasCapacity());334 Either<SessionNotCreatedException, CreateSessionResponse> response = distributor.newSession(sessionRequest);335 if (response.isRight()) {336 Session session = response.right().getSession();337 assertThat(session).isNotNull();338 String sessionId = session.getId().toString();339 Set<Slot> slots = distributor.getStatus().getNodes().stream().findFirst().get().getSlots();340 Slot slot = slots.stream().findFirst().get();341 org.openqa.selenium.grid.graphql.Session graphqlSession =342 new org.openqa.selenium.grid.graphql.Session(343 sessionId,344 session.getCapabilities(),345 session.getStartTime(),346 session.getUri(),347 node.getId().toString(),348 node.getUri(),349 slot);350 String query = String.format("{ session (id: \"%s\") { nodeId, nodeUri } }", sessionId);351 GraphqlHandler handler = new GraphqlHandler(tracer, distributor, queue, publicUri, version);352 Map<String, Object> result = executeQuery(handler, query);353 assertThat(result).describedAs(result.toString()).isEqualTo(354 singletonMap(355 "data", singletonMap(356 "session", ImmutableMap.of(357 "nodeId", graphqlSession.getNodeId(),358 "nodeUri", graphqlSession.getNodeUri().toString()))));359 } else {360 fail("Session creation failed", response.left());361 }362 }363 @Test364 public void shouldBeAbleToGetSlotInfoForSession() throws URISyntaxException {365 String nodeUrl = "http://localhost:5556";366 URI nodeUri = new URI(nodeUrl);367 Node node = LocalNode.builder(tracer, events, nodeUri, publicUri, registrationSecret)368 .add(caps, new TestSessionFactory((id, caps) -> new org.openqa.selenium.grid.data.Session(369 id,370 nodeUri,371 stereotype,372 caps,373 Instant.now()))).build();374 distributor.add(node);375 wait.until(obj -> distributor.getStatus().hasCapacity());376 Either<SessionNotCreatedException, CreateSessionResponse> response = distributor.newSession(sessionRequest);377 if (response.isRight()) {378 Session session = response.right().getSession();379 assertThat(session).isNotNull();380 String sessionId = session.getId().toString();381 Set<Slot> slots = distributor.getStatus().getNodes().stream().findFirst().get().getSlots();382 Slot slot = slots.stream().findFirst().get();383 org.openqa.selenium.grid.graphql.Session graphqlSession =384 new org.openqa.selenium.grid.graphql.Session(385 sessionId,386 session.getCapabilities(),387 session.getStartTime(),388 session.getUri(),389 node.getId().toString(),390 node.getUri(),391 slot);392 org.openqa.selenium.grid.graphql.Slot graphqlSlot = graphqlSession.getSlot();393 String query = String.format(394 "{ session (id: \"%s\") { slot { id, stereotype, lastStarted } } }", sessionId);395 GraphqlHandler handler = new GraphqlHandler(tracer, distributor, queue, publicUri, version);396 Map<String, Object> result = executeQuery(handler, query);397 assertThat(result).describedAs(result.toString()).isEqualTo(398 singletonMap(399 "data", singletonMap(400 "session", singletonMap(401 "slot", ImmutableMap.of(402 "id", graphqlSlot.getId(),403 "stereotype", graphqlSlot.getStereotype(),404 "lastStarted", graphqlSlot.getLastStarted())))));405 } else {406 fail("Session creation failed", response.left());407 }408 }409 @Test410 public void shouldBeAbleToGetSessionDuration() throws URISyntaxException {411 String nodeUrl = "http://localhost:5556";412 URI nodeUri = new URI(nodeUrl);413 Node node = LocalNode.builder(tracer, events, nodeUri, publicUri, registrationSecret)414 .add(caps, new TestSessionFactory((id, caps) -> new org.openqa.selenium.grid.data.Session(415 id,416 nodeUri,417 stereotype,418 caps,419 Instant.now()))).build();420 distributor.add(node);421 wait.until(obj -> distributor.getStatus().hasCapacity());422 Either<SessionNotCreatedException, CreateSessionResponse> response = distributor.newSession(sessionRequest);423 if (response.isRight()) {424 Session session = response.right().getSession();425 assertThat(session).isNotNull();426 String sessionId = session.getId().toString();427 String query = String.format("{ session (id: \"%s\") { sessionDurationMillis } }", sessionId);428 GraphqlHandler handler = new GraphqlHandler(tracer, distributor, queue, publicUri, version);429 Map<String, Object> result = executeQuery(handler, query);430 assertThat(result)431 .containsOnlyKeys("data")432 .extracting("data").asInstanceOf(MAP).containsOnlyKeys("session")433 .extracting("session").asInstanceOf(MAP).containsOnlyKeys("sessionDurationMillis");434 } else {435 fail("Session creation failed", response.left());436 }437 }438 @Test...
Source:LocalNode.java
...19import static java.util.stream.Collectors.groupingBy;20import static java.util.stream.Collectors.summingInt;21import static org.openqa.selenium.grid.data.SessionClosedEvent.SESSION_CLOSED;22import static org.openqa.selenium.grid.node.CapabilityResponseEncoder.getEncoder;23import static org.openqa.selenium.remote.HttpSessionId.getSessionId;24import static org.openqa.selenium.remote.http.HttpMethod.DELETE;25import com.google.common.annotations.VisibleForTesting;26import com.google.common.base.Preconditions;27import com.google.common.base.Ticker;28import com.google.common.cache.Cache;29import com.google.common.cache.CacheBuilder;30import com.google.common.cache.RemovalListener;31import com.google.common.collect.ImmutableList;32import com.google.common.collect.ImmutableMap;33import com.google.common.collect.ImmutableSet;34import org.openqa.selenium.Capabilities;35import org.openqa.selenium.NoSuchSessionException;36import org.openqa.selenium.concurrent.Regularly;37import org.openqa.selenium.events.EventBus;38import org.openqa.selenium.grid.component.HealthCheck;39import org.openqa.selenium.grid.data.CreateSessionRequest;40import org.openqa.selenium.grid.data.CreateSessionResponse;41import org.openqa.selenium.grid.data.NodeStatus;42import org.openqa.selenium.grid.data.Session;43import org.openqa.selenium.grid.node.ActiveSession;44import org.openqa.selenium.grid.node.Node;45import org.openqa.selenium.grid.node.SessionFactory;46import org.openqa.selenium.json.Json;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.remote.tracing.Span;53import java.io.IOException;54import java.io.UncheckedIOException;55import java.net.URI;56import java.time.Clock;57import java.time.Duration;58import java.util.List;59import java.util.Map;60import java.util.Objects;61import java.util.Optional;62import java.util.UUID;63import java.util.stream.Collectors;64public class LocalNode extends Node {65 public static final Json JSON = new Json();66 private final URI externalUri;67 private final HealthCheck healthCheck;68 private final int maxSessionCount;69 private final List<SessionSlot> factories;70 private final Cache<SessionId, SessionSlot> currentSessions;71 private final Regularly regularly;72 private LocalNode(73 DistributedTracer tracer,74 EventBus bus,75 URI uri,76 HealthCheck healthCheck,77 int maxSessionCount,78 Ticker ticker,79 Duration sessionTimeout,80 List<SessionSlot> factories) {81 super(tracer, UUID.randomUUID(), uri);82 Preconditions.checkArgument(83 maxSessionCount > 0,84 "Only a positive number of sessions can be run: " + maxSessionCount);85 this.externalUri = Objects.requireNonNull(uri);86 this.healthCheck = Objects.requireNonNull(healthCheck);87 this.maxSessionCount = Math.min(maxSessionCount, factories.size());88 this.factories = ImmutableList.copyOf(factories);89 this.currentSessions = CacheBuilder.newBuilder()90 .expireAfterAccess(sessionTimeout)91 .ticker(ticker)92 .removalListener((RemovalListener<SessionId, SessionSlot>) notification -> {93 // If we were invoked explicitly, then return: we know what we're doing.94 if (!notification.wasEvicted()) {95 return;96 }97 try (Span span = tracer.createSpan("node.evict-session", null)) {98 killSession(span, notification.getValue());99 }100 })101 .build();102 this.regularly = new Regularly("Local Node: " + externalUri);103 regularly.submit(currentSessions::cleanUp, Duration.ofSeconds(30), Duration.ofSeconds(30));104 bus.addListener(SESSION_CLOSED, event -> {105 try {106 this.stop(event.getData(SessionId.class));107 } catch (NoSuchSessionException ignore) {}108 });109 }110 @VisibleForTesting111 public int getCurrentSessionCount() {112 // It seems wildly unlikely we'll overflow an int113 return Math.toIntExact(currentSessions.size());114 }115 @Override116 public boolean isSupporting(Capabilities capabilities) {117 try (Span span = tracer.createSpan("node.is-supporting", tracer.getActiveSpan())) {118 span.addTag("capabilities", capabilities);119 boolean toReturn = factories.parallelStream().anyMatch(factory -> factory.test(capabilities));120 span.addTag("match-made", toReturn);121 return toReturn;122 }123 }124 @Override125 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {126 try (Span span = tracer.createSpan("node.new-session", tracer.getActiveSpan())) {127 Objects.requireNonNull(sessionRequest, "Session request has not been set.");128 span.addTag("capabilities", sessionRequest.getCapabilities());129 if (getCurrentSessionCount() >= maxSessionCount) {130 span.addTag("result", "session count exceeded");131 return Optional.empty();132 }133 Optional<ActiveSession> possibleSession = Optional.empty();134 SessionSlot slot = null;135 for (SessionSlot factory : factories) {136 if (!factory.isAvailable() || !factory.test(sessionRequest.getCapabilities())) {137 continue;138 }139 possibleSession = factory.apply(sessionRequest);140 if (possibleSession.isPresent()) {141 slot = factory;142 break;143 }144 }145 if (!possibleSession.isPresent()) {146 span.addTag("result", "No possible session detected");147 return Optional.empty();148 }149 ActiveSession session = possibleSession.get();150 span.addTag("session.id", session.getId());151 span.addTag("session.capabilities", session.getCapabilities());152 span.addTag("session.uri", session.getUri());153 currentSessions.put(session.getId(), slot);154 // The session we return has to look like it came from the node, since we might be dealing155 // with a webdriver implementation that only accepts connections from localhost156 Session externalSession = createExternalSession(session, externalUri);157 return Optional.of(new CreateSessionResponse(158 externalSession,159 getEncoder(session.getDownstreamDialect()).apply(externalSession)));160 }161 }162 @Override163 protected boolean isSessionOwner(SessionId id) {164 try (Span span = tracer.createSpan("node.is-session-owner", tracer.getActiveSpan())) {165 Objects.requireNonNull(id, "Session ID has not been set");166 span.addTag("session.id", id);167 boolean toReturn = currentSessions.getIfPresent(id) != null;168 span.addTag("result", toReturn);169 return toReturn;170 }171 }172 @Override173 public Session getSession(SessionId id) throws NoSuchSessionException {174 Objects.requireNonNull(id, "Session ID has not been set");175 try (Span span = tracer.createSpan("node.get-session", tracer.getActiveSpan())) {176 span.addTag("session.id", id);177 SessionSlot slot = currentSessions.getIfPresent(id);178 if (slot == null) {179 span.addTag("result", false);180 throw new NoSuchSessionException("Cannot find session with id: " + id);181 }182 span.addTag("session.capabilities", slot.getSession().getCapabilities());183 span.addTag("session.uri", slot.getSession().getUri());184 return createExternalSession(slot.getSession(), externalUri);185 }186 }187 @Override188 public void executeWebDriverCommand(HttpRequest req, HttpResponse resp) {189 try (Span span = tracer.createSpan("node.webdriver-command", tracer.getActiveSpan())) {190 span.addTag("http.method", req.getMethod());191 span.addTag("http.url", req.getUri());192 // True enough to be good enough193 SessionId id = getSessionId(req.getUri()).map(SessionId::new)194 .orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req));195 span.addTag("session.id", id);196 SessionSlot slot = currentSessions.getIfPresent(id);197 if (slot == null) {198 span.addTag("result", "Session not found");199 throw new NoSuchSessionException("Cannot find session with id: " + id);200 }201 span.addTag("session.capabilities", slot.getSession().getCapabilities());202 span.addTag("session.uri", slot.getSession().getUri());203 try {204 slot.execute(req, resp);205 } catch (IOException e) {206 throw new UncheckedIOException(e);207 }208 if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) {209 stop(id);210 }211 }212 }213 @Override214 public void stop(SessionId id) throws NoSuchSessionException {215 try (Span span = tracer.createSpan("node.stop-session", tracer.getActiveSpan())) {216 Objects.requireNonNull(id, "Session ID has not been set");217 SessionSlot slot = currentSessions.getIfPresent(id);218 if (slot == null) {219 throw new NoSuchSessionException("Cannot find session with id: " + id);220 }221 killSession(span, slot);222 }223 }224 private Session createExternalSession(ActiveSession other, URI externalUri) {225 return new Session(other.getId(), externalUri, other.getCapabilities());226 }227 private void killSession(Span span, SessionSlot slot) {228 span.addTag("session.id", slot.getSession().getId());229 span.addTag("session.capabilities", slot.getSession().getCapabilities());230 span.addTag("session.uri", slot.getSession().getUri());231 currentSessions.invalidate(slot.getSession().getId());232 // Attempt to stop the session233 if (!slot.isAvailable()) {234 slot.stop();235 }236 }237 @Override238 public NodeStatus getStatus() {239 Map<Capabilities, Integer> stereotypes = factories.stream()240 .collect(groupingBy(SessionSlot::getStereotype, summingInt(caps -> 1)));241 ImmutableSet<NodeStatus.Active> activeSessions = currentSessions.asMap().values().stream()242 .map(slot -> new NodeStatus.Active(243 slot.getStereotype(),244 slot.getSession().getId(),245 slot.getSession().getCapabilities()))246 .collect(toImmutableSet());247 return new NodeStatus(248 getId(),249 externalUri,250 maxSessionCount,251 stereotypes,252 activeSessions);253 }254 @Override255 public HealthCheck getHealthCheck() {256 return healthCheck;257 }258 private Map<String, Object> toJson() {259 return ImmutableMap.of(...
Source:Distributor.java
...209 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);210 return exception;211 })212 .get();213 sessions.add(sessionResponse.getSession());214 SessionId sessionId = sessionResponse.getSession().getId();215 Capabilities caps = sessionResponse.getSession().getCapabilities();216 String sessionUri = sessionResponse.getSession().getUri().toString();217 SESSION_ID.accept(span, sessionId);218 CAPABILITIES.accept(span, caps);219 SESSION_ID_EVENT.accept(attributeMap, sessionId);220 CAPABILITIES_EVENT.accept(attributeMap, caps);221 span.setAttribute(AttributeKey.SESSION_URI.getKey(), sessionUri);222 attributeMap.put(AttributeKey.SESSION_URI.getKey(), EventAttribute.setValue(sessionUri));223 return sessionResponse;224 } catch (SessionNotCreatedException e) {225 span.setAttribute("error", true);226 span.setStatus(Status.ABORTED);227 EXCEPTION.accept(attributeMap, e);228 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),229 EventAttribute.setValue("Unable to create session: " + e.getMessage()));230 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);...
Source:GridModel.java
...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;282 }283 Session current = maybeSession.get();284 if (!RESERVED.equals(current.getId())) {285 LOG.warning("Gid model and reality have diverged. Slot has session and is not reserved. " + slotId);286 return;287 }288 Slot updated = new Slot(289 slot.getId(),290 slot.getStereotype(),291 session == null ? slot.getLastStarted() : session.getStartTime(),292 Optional.ofNullable(session));...
Source:LocalNodeTest.java
...71 ImmutableSet.of(W3C),72 stereotype,73 ImmutableMap.of()))74 .orElseThrow(() -> new AssertionError("Unable to create session"));75 session = sessionResponse.getSession();76 }77 @Test78 public void shouldThrowIfSessionIsNotPresent() {79 assertThatExceptionOfType(NoSuchSessionException.class)80 .isThrownBy(() -> node.getSession(new SessionId("12345")));81 }82 @Test83 public void canRetrieveActiveSessionById() {84 assertThat(node.getSession(session.getId())).isEqualTo(session);85 }86 @Test87 public void isOwnerOfAnActiveSession() {88 assertThat(node.isSessionOwner(session.getId())).isTrue();89 }90 @Test91 public void canStopASession() {92 node.stop(session.getId());93 assertThatExceptionOfType(NoSuchSessionException.class)94 .isThrownBy(() -> node.getSession(session.getId()));95 }96 @Test97 public void isNotOwnerOfAStoppedSession() {98 node.stop(session.getId());99 assertThat(node.isSessionOwner(session.getId())).isFalse();100 }101 @Test102 public void cannotAcceptNewSessionsWhileDraining() {103 node.drain();104 assertThat(node.isDraining()).isTrue();105 node.stop(session.getId()); //stop the default session106 Capabilities stereotype = new ImmutableCapabilities("cheese", "brie");107 Optional<CreateSessionResponse> sessionResponse = node.newSession(108 new CreateSessionRequest(109 ImmutableSet.of(W3C),110 stereotype,111 ImmutableMap.of()));112 assertThat(sessionResponse).isEmpty();113 }114 @Test115 public void canReturnStatusInfo() {116 NodeStatus status = node.getStatus();117 assertThat(status.getSlots().stream()118 .filter(slot -> slot.getSession().isPresent())119 .map(slot -> slot.getSession().get())120 .filter(s -> s.getId().equals(session.getId()))).isNotEmpty();121 node.stop(session.getId());122 status = node.getStatus();123 assertThat(status.getSlots().stream()124 .filter(slot -> slot.getSession().isPresent())125 .map(slot -> slot.getSession().get())126 .filter(s -> s.getId().equals(session.getId()))).isEmpty();127 }128 @Test129 public void nodeStatusInfoIsImmutable() {130 NodeStatus status = node.getStatus();131 assertThat(status.getSlots().stream()132 .filter(slot -> slot.getSession().isPresent())133 .map(slot -> slot.getSession().get())134 .filter(s -> s.getId().equals(session.getId()))).isNotEmpty();135 node.stop(session.getId());136 assertThat(status.getSlots().stream()137 .filter(slot -> slot.getSession().isPresent())138 .map(slot -> slot.getSession().get())139 .filter(s -> s.getId().equals(session.getId()))).isNotEmpty();140 }141 @Test142 public void shouldBeAbleToCreateSessionsConcurrently() throws Exception {143 Tracer tracer = DefaultTestTracer.createTracer();144 EventBus bus = new GuavaEventBus();145 URI uri = new URI("http://localhost:1234");146 Capabilities caps = new ImmutableCapabilities("browserName", "cheese");147 class VerifyingHandler extends Session implements HttpHandler {148 private VerifyingHandler(SessionId id, Capabilities capabilities) {149 super(id, uri, new ImmutableCapabilities(), capabilities, Instant.now());150 }151 @Override152 public HttpResponse execute(HttpRequest req) {153 Optional<SessionId> id = HttpSessionId.getSessionId(req.getUri()).map(SessionId::new);154 assertThat(id).isEqualTo(Optional.of(getId()));155 return new HttpResponse();156 }157 }158 Node node = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)159 .add(caps, new TestSessionFactory(VerifyingHandler::new))160 .add(caps, new TestSessionFactory(VerifyingHandler::new))161 .add(caps, new TestSessionFactory(VerifyingHandler::new))162 .build();163 List<Callable<SessionId>> callables = new ArrayList<>();164 for (int i = 0; i < 3; i++) {165 callables.add(() -> {166 CreateSessionResponse res = node.newSession(167 new CreateSessionRequest(168 ImmutableSet.of(W3C),169 caps,170 ImmutableMap.of()))171 .orElseThrow(() -> new AssertionError("Unable to create session"));172 assertThat(res.getSession().getCapabilities().getBrowserName()).isEqualTo("cheese");173 return res.getSession().getId();174 });175 }176 List<Future<SessionId>> futures = Executors.newFixedThreadPool(3).invokeAll(callables);177 for (Future<SessionId> future : futures) {178 SessionId id = future.get(2, SECONDS);179 // Now send a random command.180 HttpResponse res = node.execute(new HttpRequest(GET, String.format("/session/%s/url", id)));181 assertThat(res.isSuccessful()).isTrue();182 }183 }184}...
Source:Grid.java
...69 for (NodeStatus status : distributorStatus.get().getNodes()) {70 Map<Capabilities, Integer> stereotypes = new HashMap<>();71 Map<org.openqa.selenium.grid.data.Session, Slot> sessions = new HashMap<>();72 for (Slot slot : status.getSlots()) {73 slot.getSession().ifPresent(session -> sessions.put(session, slot));74 int count = stereotypes.getOrDefault(slot.getStereotype(), 0);75 count++;76 stereotypes.put(slot.getStereotype(), count);77 }78 OsInfo osInfo = new OsInfo(79 status.getOsInfo().get("arch"),80 status.getOsInfo().get("name"),81 status.getOsInfo().get("version"));82 toReturn.add(new Node(83 status.getId(),84 status.getUri(),85 status.getAvailability(),86 status.getMaxSessionCount(),87 status.getSlots().size(),88 stereotypes,89 sessions,90 status.getVersion(),91 osInfo));92 }93 return toReturn.build();94 }95 public int getNodeCount() {96 return distributorStatus.get().getNodes().size();97 }98 public int getSessionCount() {99 return distributorStatus.get().getNodes().stream()100 .map(NodeStatus::getSlots)101 .flatMap(Collection::stream)102 .filter(slot -> slot.getSession().isPresent())103 .mapToInt(slot -> 1)104 .sum();105 }106 public int getTotalSlots() {107 return distributorStatus.get().getNodes().stream()108 .mapToInt(status -> status.getSlots().size())109 .sum();110 }111 public int getMaxSession() {112 return distributorStatus.get().getNodes().stream()113 .mapToInt(NodeStatus::getMaxSessionCount)114 .sum();115 }116 public int getSessionQueueSize() {117 return queueInfoList.size();118 }119 public List<String> getSessionQueueRequests() {120 // TODO: The Grid UI expects there to be a single capability per new session request, which is not correct121 return queueInfoList.stream()122 .map(set -> set.isEmpty() ? new ImmutableCapabilities() : set.iterator().next())123 .map(JSON::toJson)124 .collect(Collectors.toList());125 }126 public List<Session> getSessions() {127 List<Session> sessions = new ArrayList<>();128 for (NodeStatus status : distributorStatus.get().getNodes()) {129 for (Slot slot : status.getSlots()) {130 if (slot.getSession().isPresent()) {131 org.openqa.selenium.grid.data.Session session = slot.getSession().get();132 sessions.add(133 new org.openqa.selenium.grid.graphql.Session(134 session.getId().toString(),135 session.getCapabilities(),136 session.getStartTime(),137 session.getUri(),138 status.getId().toString(),139 status.getUri(),140 slot)141 );142 }143 }144 }145 return sessions;...
Source:SessionData.java
...56 }57 private SessionInSlot findSession(String sessionId, Set<NodeStatus> nodeStatuses) {58 for (NodeStatus status : nodeStatuses) {59 for (Slot slot : status.getSlots()) {60 Optional<org.openqa.selenium.grid.data.Session> session = slot.getSession();61 if (session.isPresent() && sessionId.equals(session.get().getId().toString())) {62 return new SessionInSlot(session.get(), status, slot);63 }64 }65 }66 return null;67 }68 private static class SessionInSlot {69 private final org.openqa.selenium.grid.data.Session session;70 private final NodeStatus node;71 private final Slot slot;72 SessionInSlot(org.openqa.selenium.grid.data.Session session, NodeStatus node, Slot slot) {73 this.session = session;74 this.node = node;...
getSession
Using AI Code Generation
1package org.openqa.selenium.grid.data;2import org.openqa.selenium.Capabilities;3import org.openqa.selenium.ImmutableCapabilities;4import org.openqa.selenium.internal.Require;5import org.openqa.selenium.json.JsonInput;6import java.net.URI;7import java.util.Map;8import java.util.Objects;9public class Slot {10 private final URI uri;11 private final Session session;12 private final Capabilities capabilities;13 private final SlotStatus status;14 public Slot(URI uri, Session session, Capabilities capabilities, SlotStatus status) {15 this.uri = uri;16 this.session = session;17 this.capabilities = capabilities;18 this.status = status;19 }20 public URI getUri() {21 return uri;22 }23 public Session getSession() {24 return session;25 }26 public Capabilities getCapabilities() {27 return capabilities;28 }29 public SlotStatus getStatus() {30 return status;31 }32 public boolean equals(Object o) {33 if (!(o instanceof Slot)) {34 return false;35 }36 Slot that = (Slot) o;37 return Objects.equals(this.uri, that.uri) &&38 Objects.equals(this.session, that.session) &&39 Objects.equals(this.capabilities, that.capabilities) &&40 Objects.equals(this.status, that.status);41 }42 public int hashCode() {43 return Objects.hash(uri, session, capabilities, status);44 }45 public String toString() {46 return String.format(47 "Slot{uri=%s, session=%s, capabilities=%s, status=%s}",48 uri, session, capabilities, status);49 }50 public static Slot fromJson(JsonInput input) {51 Require.nonNull("Input to parse", input);52 URI uri = null;53 Session session = null;54 Map<String, Object> capabilities = null;55 SlotStatus status = null;56 input.beginObject();57 while (input.hasNext()) {58 switch (input.nextName()) {59 uri = URI.create(input.nextString());60 break;61 session = Session.fromJson(input);62 break;63 capabilities = input.read(Map.class);64 break;65 status = SlotStatus.valueOf(input.nextString());66 break;67 input.skipValue();68 break;69 }70 }71 input.endObject();72 return new Slot(uri, session, new ImmutableCapabilities(capabilities
getSession
Using AI Code Generation
1import org.openqa.selenium.grid.data.Session;2import org.openqa.selenium.grid.data.Slot;3import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;4import org.openqa.selenium.grid.sessionmap.remote.RemoteSessionMap;5import org.openqa.selenium.remote.NewSessionPayload;6import org.openqa.selenium.remote.tracing.DefaultTestTracer;7import org.openqa.selenium.remote.tracing.Tracer;8import java.net.URI;9import java.net.URISyntaxException;10import java.util.UUID;11public class SessionMapDemo {12 public static void main(String[] args) throws URISyntaxException {13 Tracer tracer = DefaultTestTracer.createTracer();14 SessionMapOptions sessionMapOptions = new SessionMapOptions();15 RemoteSessionMap remoteSessionMap = new RemoteSessionMap(tracer, sessionMapOptions);16 UUID uuid = UUID.randomUUID();17 Session session = remoteSessionMap.getSession(slot);18 NewSessionPayload payload = session.getPayload();19 System.out.println(payload);20 }21}
getSession
Using AI Code Generation
1String sessionId = ((RemoteWebDriver)driver).getSessionId().toString();2Session session = ((RemoteWebDriver)driver).getSession();3Capabilities sessionCap = ((RemoteWebDriver)driver).getSession().getCapabilities();4String sessionId = ((RemoteWebDriver)driver).getSessionId().toString();5Session session = ((RemoteWebDriver)driver).getSession();6Capabilities sessionCap = ((RemoteWebDriver)driver).getSession().getCapabilities();7String sessionId = ((RemoteWebDriver)driver).getSessionId().toString();8Session session = ((RemoteWebDriver)driver).getSession();9Capabilities sessionCap = ((RemoteWebDriver)driver).getSession().getCapabilities();10String sessionId = ((RemoteWebDriver)driver).getSessionId().toString();11Session session = ((RemoteWebDriver)driver).getSession();12Capabilities sessionCap = ((RemoteWebDriver)driver).getSession().getCapabilities();13String sessionId = ((RemoteWebDriver)driver).getSessionId().toString();14Session session = ((RemoteWebDriver)driver).getSession();15Capabilities sessionCap = ((RemoteWebDriver)driver).getSession().getCapabilities();16String sessionId = ((RemoteWebDriver)driver).getSessionId().toString();17Session session = ((RemoteWebDriver)driver).getSession();18Capabilities sessionCap = ((RemoteWebDriver)driver).getSession().getCapabilities();19String sessionId = ((RemoteWebDriver)driver).getSessionId().toString();20Session session = ((RemoteWebDriver)driver).getSession();
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!!