How to use getSession method of org.openqa.selenium.grid.node.Node class

Best Selenium code snippet using org.openqa.selenium.grid.node.Node.getSession

Source:LocalNode.java Github

copy

Full Screen

...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.grid.web.WebDriverUrls.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 -> this.stop(event.getData(SessionId.class)));105 }106 @VisibleForTesting107 public int getCurrentSessionCount() {108 // It seems wildly unlikely we'll overflow an int109 return Math.toIntExact(currentSessions.size());110 }111 @Override112 public boolean isSupporting(Capabilities capabilities) {113 try (Span span = tracer.createSpan("node.is-supporting", tracer.getActiveSpan())) {114 span.addTag("capabilities", capabilities);115 boolean toReturn = factories.parallelStream().anyMatch(factory -> factory.test(capabilities));116 span.addTag("match-made", toReturn);117 return toReturn;118 }119 }120 @Override121 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {122 try (Span span = tracer.createSpan("node.new-session", tracer.getActiveSpan())) {123 Objects.requireNonNull(sessionRequest, "Session request has not been set.");124 span.addTag("capabilities", sessionRequest.getCapabilities());125 if (getCurrentSessionCount() >= maxSessionCount) {126 span.addTag("result", "session count exceeded");127 return Optional.empty();128 }129 Optional<ActiveSession> possibleSession = Optional.empty();130 SessionSlot slot = null;131 for (SessionSlot factory : factories) {132 if (!factory.isAvailable() || !factory.test(sessionRequest.getCapabilities())) {133 continue;134 }135 possibleSession = factory.apply(sessionRequest);136 if (possibleSession.isPresent()) {137 slot = factory;138 break;139 }140 }141 if (!possibleSession.isPresent()) {142 span.addTag("result", "No possible session detected");143 return Optional.empty();144 }145 ActiveSession session = possibleSession.get();146 span.addTag("session.id", session.getId());147 span.addTag("session.capabilities", session.getCapabilities());148 span.addTag("session.uri", session.getUri());149 currentSessions.put(session.getId(), slot);150 // The session we return has to look like it came from the node, since we might be dealing151 // with a webdriver implementation that only accepts connections from localhost152 Session externalSession = createExternalSession(session, externalUri);153 return Optional.of(new CreateSessionResponse(154 externalSession,155 getEncoder(session.getDownstreamDialect()).apply(externalSession)));156 }157 }158 @Override159 protected boolean isSessionOwner(SessionId id) {160 try (Span span = tracer.createSpan("node.is-session-owner", tracer.getActiveSpan())) {161 Objects.requireNonNull(id, "Session ID has not been set");162 span.addTag("session.id", id);163 boolean toReturn = currentSessions.getIfPresent(id) != null;164 span.addTag("result", toReturn);165 return toReturn;166 }167 }168 @Override169 public Session getSession(SessionId id) throws NoSuchSessionException {170 Objects.requireNonNull(id, "Session ID has not been set");171 try (Span span = tracer.createSpan("node.get-session", tracer.getActiveSpan())) {172 span.addTag("session.id", id);173 SessionSlot slot = currentSessions.getIfPresent(id);174 if (slot == null) {175 span.addTag("result", false);176 throw new NoSuchSessionException("Cannot find session with id: " + id);177 }178 span.addTag("session.capabilities", slot.getSession().getCapabilities());179 span.addTag("session.uri", slot.getSession().getUri());180 return createExternalSession(slot.getSession(), externalUri);181 }182 }183 @Override184 public void executeWebDriverCommand(HttpRequest req, HttpResponse resp) {185 try (Span span = tracer.createSpan("node.webdriver-command", tracer.getActiveSpan())) {186 span.addTag("http.method", req.getMethod());187 span.addTag("http.url", req.getUri());188 // True enough to be good enough189 SessionId id = getSessionId(req)190 .orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req));191 span.addTag("session.id", id);192 SessionSlot slot = currentSessions.getIfPresent(id);193 if (slot == null) {194 span.addTag("result", "Session not found");195 throw new NoSuchSessionException("Cannot find session with id: " + id);196 }197 span.addTag("session.capabilities", slot.getSession().getCapabilities());198 span.addTag("session.uri", slot.getSession().getUri());199 if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) {200 stop(id);201 return;202 }203 try {204 slot.execute(req, resp);205 } catch (IOException e) {206 throw new UncheckedIOException(e);207 }208 }209 }210 @Override211 public void stop(SessionId id) throws NoSuchSessionException {212 try (Span span = tracer.createSpan("node.stop-session", tracer.getActiveSpan())) {213 Objects.requireNonNull(id, "Session ID has not been set");214 SessionSlot slot = currentSessions.getIfPresent(id);215 if (slot == null) {216 throw new NoSuchSessionException("Cannot find session with id: " + id);217 }218 killSession(span, slot);219 }220 }221 private Session createExternalSession(ActiveSession other, URI externalUri) {222 return new Session(other.getId(), externalUri, other.getCapabilities());223 }224 private void killSession(Span span, SessionSlot slot) {225 span.addTag("session.id", slot.getSession().getId());226 span.addTag("session.capabilities", slot.getSession().getCapabilities());227 span.addTag("session.uri", slot.getSession().getUri());228 currentSessions.invalidate(slot.getSession().getId());229 // Attempt to stop the session230 if (!slot.isAvailable()) {231 slot.stop();232 }233 }234 @Override235 public NodeStatus getStatus() {236 Map<Capabilities, Integer> stereotypes = factories.stream()237 .collect(groupingBy(SessionSlot::getStereotype, summingInt(caps -> 1)));238 ImmutableSet<NodeStatus.Active> activeSessions = currentSessions.asMap().values().stream()239 .map(slot -> new NodeStatus.Active(240 slot.getStereotype(),241 slot.getSession().getId(),242 slot.getSession().getCapabilities()))243 .collect(toImmutableSet());244 return new NodeStatus(245 getId(),246 externalUri,247 maxSessionCount,248 stereotypes,249 activeSessions);250 }251 @Override252 public HealthCheck getHealthCheck() {253 return healthCheck;254 }255 private Map<String, Object> toJson() {256 return ImmutableMap.of(...

Full Screen

Full Screen

Source:SessionSlot.java Github

copy

Full Screen

...53 }54 public boolean isAvailable() {55 return currentSession == null;56 }57 public ActiveSession getSession() {58 if (isAvailable()) {59 throw new NoSuchSessionException("Session is not running");60 }61 return currentSession;62 }63 public void stop() {64 if (isAvailable()) {65 return;66 }67 SessionId id = currentSession.getId();68 currentSession.stop();69 currentSession = null;70 bus.fire(new SessionClosedEvent(id));71 }...

Full Screen

Full Screen

getSession

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.node.Node;2import org.openqa.selenium.remote.NewSessionPayload;3import org.openqa.selenium.remote.SessionId;4Node node = new Node();5NewSessionPayload payload = new NewSessionPayload();6SessionId sessionId = node.getSession(payload);7import org.openqa.selenium.grid.node.httpd.NewSessionHandler;8import org.openqa.selenium.remote.NewSessionPayload;9import org.openqa.selenium.remote.SessionId;10NewSessionHandler newSessionHandler = new NewSessionHandler();11NewSessionPayload payload = new NewSessionPayload();12SessionId sessionId = newSessionHandler.getSession(payload);13import org.openqa.selenium.grid.node.httpd.NewSessionQueue;14import org.openqa.selenium.remote.NewSessionPayload;15import org.openqa.selenium.remote.SessionId;16NewSessionQueue newSessionQueue = new NewSessionQueue();17NewSessionPayload payload = new NewSessionPayload();18SessionId sessionId = newSessionQueue.getSession(payload);19import org.openqa.selenium.grid.node.httpd.NewSessionResponse;20import org.openqa.selenium.remote.NewSessionPayload;21import org.openqa.selenium.remote.SessionId;22NewSessionResponse newSessionResponse = new NewSessionResponse();23NewSessionPayload payload = new NewSessionPayload();24SessionId sessionId = newSessionResponse.getSession(payload);25import org.openqa.selenium.grid.node.httpd.NewSessionRequest;26import org.openqa.selenium.remote.NewSessionPayload;27import org.openqa.selenium.remote.SessionId;28NewSessionRequest newSessionRequest = new NewSessionRequest();29NewSessionPayload payload = new NewSessionPayload();30SessionId sessionId = newSessionRequest.getSession(payload);31import org.openqa.selenium.grid.node.httpd.NewSessionFilter;32import org.openqa.selenium.remote.NewSessionPayload;33import org.openqa.selenium.remote.SessionId;34NewSessionFilter newSessionFilter = new NewSessionFilter();35NewSessionPayload payload = new NewSessionPayload();36SessionId sessionId = newSessionFilter.getSession(payload);37import org.openqa.selenium.grid.node.httpd.NewSessionQueue;38import org.openqa.selenium.remote.NewSessionPayload;39import org.openqa.selenium.remote.SessionId;

Full Screen

Full Screen

getSession

Using AI Code Generation

copy

Full Screen

1SessionId session = ((RemoteWebDriver)driver).getSessionId();2SessionInfo sessionInfo = node.getSession(session);3SessionId session = ((RemoteWebDriver)driver).getSessionId();4SessionInfo sessionInfo = node.getSession(session);5SessionId session = ((RemoteWebDriver)driver).getSessionId();6SessionInfo sessionInfo = node.getSession(session);7SessionId session = ((RemoteWebDriver)driver).getSessionId();8SessionInfo sessionInfo = node.getSession(session);9SessionId session = ((RemoteWebDriver)driver).getSessionId();10SessionInfo sessionInfo = node.getSession(session);11SessionId session = ((RemoteWebDriver)driver).getSessionId();12SessionInfo sessionInfo = node.getSession(session);

Full Screen

Full Screen

getSession

Using AI Code Generation

copy

Full Screen

1public String getSessionId() {2 return getSession().getId().toString();3}4public String getSlotId() {5 return getSlot().getId().toString();6}7[java]{}[/java]8[java]{}[/java]9[java]{}[/java]10[java]{}[/java]11[java]{}[/java]12[java]{}[/java]13[java]{}[/java]14[java]{}[/java]15[java]{}[/java]16[java]{}[/java]17[java]{}[/java]18[java]{}[/java

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

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

Run Selenium automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful