How to use SessionSlot class of org.openqa.selenium.grid.node.local package

Best Selenium code snippet using org.openqa.selenium.grid.node.local.SessionSlot

Source:LocalNode.java Github

copy

Full Screen

...62 public static final Json JSON = new Json();63 private final URI externalUri;64 private final HealthCheck healthCheck;65 private final int maxSessionCount;66 private final List<SessionSlot> factories;67 private final Cache<SessionId, SessionSlot> currentSessions;68 private final Regularly regularly;69 private LocalNode(70 Tracer tracer,71 EventBus bus,72 URI uri,73 HealthCheck healthCheck,74 int maxSessionCount,75 Ticker ticker,76 Duration sessionTimeout,77 List<SessionSlot> factories) {78 super(tracer, UUID.randomUUID(), uri);79 Preconditions.checkArgument(80 maxSessionCount > 0,81 "Only a positive number of sessions can be run: " + maxSessionCount);82 this.externalUri = Objects.requireNonNull(uri);83 this.healthCheck = Objects.requireNonNull(healthCheck);84 this.maxSessionCount = Math.min(maxSessionCount, factories.size());85 this.factories = ImmutableList.copyOf(factories);86 this.currentSessions = CacheBuilder.newBuilder()87 .expireAfterAccess(sessionTimeout)88 .ticker(ticker)89 .removalListener((RemovalListener<SessionId, SessionSlot>) notification -> {90 // If we were invoked explicitly, then return: we know what we're doing.91 if (!notification.wasEvicted()) {92 return;93 }94 killSession(notification.getValue());95 })96 .build();97 this.regularly = new Regularly("Local Node: " + externalUri);98 regularly.submit(currentSessions::cleanUp, Duration.ofSeconds(30), Duration.ofSeconds(30));99 bus.addListener(SESSION_CLOSED, event -> {100 try {101 this.stop(event.getData(SessionId.class));102 } catch (NoSuchSessionException ignore) {103 }104 });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 return factories.parallelStream().anyMatch(factory -> factory.test(capabilities));114 }115 @Override116 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {117 Objects.requireNonNull(sessionRequest, "Session request has not been set.");118 if (getCurrentSessionCount() >= maxSessionCount) {119 return Optional.empty();120 }121 Optional<ActiveSession> possibleSession = Optional.empty();122 SessionSlot slot = null;123 for (SessionSlot factory : factories) {124 if (!factory.isAvailable() || !factory.test(sessionRequest.getCapabilities())) {125 continue;126 }127 possibleSession = factory.apply(sessionRequest);128 if (possibleSession.isPresent()) {129 slot = factory;130 break;131 }132 }133 if (!possibleSession.isPresent()) {134 return Optional.empty();135 }136 ActiveSession session = possibleSession.get();137 currentSessions.put(session.getId(), slot);138 // The session we return has to look like it came from the node, since we might be dealing139 // with a webdriver implementation that only accepts connections from localhost140 Session externalSession = createExternalSession(session, externalUri);141 return Optional.of(new CreateSessionResponse(142 externalSession,143 getEncoder(session.getDownstreamDialect()).apply(externalSession)));144 }145 @Override146 protected boolean isSessionOwner(SessionId id) {147 Objects.requireNonNull(id, "Session ID has not been set");148 return currentSessions.getIfPresent(id) != null;149 }150 @Override151 public Session getSession(SessionId id) throws NoSuchSessionException {152 Objects.requireNonNull(id, "Session ID has not been set");153 SessionSlot slot = currentSessions.getIfPresent(id);154 if (slot == null) {155 throw new NoSuchSessionException("Cannot find session with id: " + id);156 }157 return createExternalSession(slot.getSession(), externalUri);158 }159 @Override160 public HttpResponse executeWebDriverCommand(HttpRequest req) {161 // True enough to be good enough162 SessionId id = getSessionId(req.getUri()).map(SessionId::new)163 .orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req));164 SessionSlot slot = currentSessions.getIfPresent(id);165 if (slot == null) {166 throw new NoSuchSessionException("Cannot find session with id: " + id);167 }168 HttpResponse toReturn = slot.execute(req);169 if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) {170 stop(id);171 }172 return toReturn;173 }174 @Override175 public void stop(SessionId id) throws NoSuchSessionException {176 Objects.requireNonNull(id, "Session ID has not been set");177 SessionSlot slot = currentSessions.getIfPresent(id);178 if (slot == null) {179 throw new NoSuchSessionException("Cannot find session with id: " + id);180 }181 killSession(slot);182 }183 private Session createExternalSession(ActiveSession other, URI externalUri) {184 return new Session(other.getId(), externalUri, other.getCapabilities());185 }186 private void killSession(SessionSlot slot) {187 currentSessions.invalidate(slot.getSession().getId());188 // Attempt to stop the session189 if (!slot.isAvailable()) {190 slot.stop();191 }192 }193 @Override194 public NodeStatus getStatus() {195 Map<Capabilities, Integer> stereotypes = factories.stream()196 .collect(groupingBy(SessionSlot::getStereotype, summingInt(caps -> 1)));197 ImmutableSet<NodeStatus.Active> activeSessions = currentSessions.asMap().values().stream()198 .map(slot -> new NodeStatus.Active(199 slot.getStereotype(),200 slot.getSession().getId(),201 slot.getSession().getCapabilities()))202 .collect(toImmutableSet());203 return new NodeStatus(204 getId(),205 externalUri,206 maxSessionCount,207 stereotypes,208 activeSessions);209 }210 @Override211 public HealthCheck getHealthCheck() {212 return healthCheck;213 }214 private Map<String, Object> toJson() {215 return ImmutableMap.of(216 "id", getId(),217 "uri", externalUri,218 "maxSessions", maxSessionCount,219 "capabilities", factories.stream()220 .map(SessionSlot::getStereotype)221 .collect(Collectors.toSet()));222 }223 public static Builder builder(224 Tracer tracer,225 EventBus bus,226 HttpClient.Factory httpClientFactory,227 URI uri) {228 return new Builder(tracer, bus, httpClientFactory, uri);229 }230 public static class Builder {231 private final Tracer tracer;232 private final EventBus bus;233 private final HttpClient.Factory httpClientFactory;234 private final URI uri;235 private final ImmutableList.Builder<SessionSlot> factories;236 private int maxCount = Runtime.getRuntime().availableProcessors() * 5;237 private Ticker ticker = Ticker.systemTicker();238 private Duration sessionTimeout = Duration.ofMinutes(5);239 private HealthCheck healthCheck;240 public Builder(241 Tracer tracer,242 EventBus bus,243 HttpClient.Factory httpClientFactory,244 URI uri) {245 this.tracer = Objects.requireNonNull(tracer);246 this.bus = Objects.requireNonNull(bus);247 this.httpClientFactory = Objects.requireNonNull(httpClientFactory);248 this.uri = Objects.requireNonNull(uri);249 this.factories = ImmutableList.builder();250 }251 public Builder add(Capabilities stereotype, SessionFactory factory) {252 Objects.requireNonNull(stereotype, "Capabilities must be set.");253 Objects.requireNonNull(factory, "Session factory must be set.");254 factories.add(new SessionSlot(bus, stereotype, factory));255 return this;256 }257 public Builder maximumConcurrentSessions(int maxCount) {258 Preconditions.checkArgument(259 maxCount > 0,260 "Only a positive number of sessions can be run: " + maxCount);261 this.maxCount = maxCount;262 return this;263 }264 public Builder sessionTimeout(Duration timeout) {265 sessionTimeout = timeout;266 return this;267 }268 public LocalNode build() {...

Full Screen

Full Screen

Source:SessionSlot.java Github

copy

Full Screen

...33import java.util.function.Function;34import java.util.function.Predicate;35import java.util.logging.Level;36import java.util.logging.Logger;37public class SessionSlot implements38 CommandHandler,39 Function<CreateSessionRequest, Optional<ActiveSession>>,40 Predicate<Capabilities> {41 public static final Logger LOG = Logger.getLogger(SessionSlot.class.getName());42 private final EventBus bus;43 private final Capabilities stereotype;44 private final SessionFactory factory;45 private ActiveSession currentSession;46 public SessionSlot(EventBus bus, Capabilities stereotype, SessionFactory factory) {47 this.bus = Objects.requireNonNull(bus);48 this.stereotype = ImmutableCapabilities.copyOf(Objects.requireNonNull(stereotype));49 this.factory = Objects.requireNonNull(factory);50 }51 public Capabilities getStereotype() {52 return stereotype;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 }...

Full Screen

Full Screen

SessionSlot

Using AI Code Generation

copy

Full Screen

1SessionSlot slot = new SessionSlot();2slot.setSessionId("session-id");3slot.setSessionInfo("session-info");4slot.setSessionUri("session-uri");5slot.setSessionStart(Instant.now());6slot.setSessionEnd(Instant.now());7slot.setInactivityTimeout(Duration.ofSeconds(10));8boolean hasCapacity()9boolean hasCapacity(Capabilities capabilities)10boolean hasCapacity(Capabilities capabilities, Set11boolean hasCapacity(Capabilities capabilities)12boolean hasCapacity(Capabilities capabilities, Set13void doGet(HttpServletRequest request, HttpServletResponse response)

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.

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