Best Selenium code snippet using org.openqa.selenium.grid.sessionqueue.NewSessionQueue.complete
Source:LocalDistributor.java
...513 .count();514 if (unmatchableCount == request.getDesiredCapabilities().size()) {515 SessionNotCreatedException exception = new SessionNotCreatedException(516 "No nodes support the capabilities in the request");517 sessionQueue.complete(request.getRequestId(), Either.left(exception));518 }519 }520 }521 private void handleNewSessionRequest(SessionRequest sessionRequest) {522 RequestId reqId = sessionRequest.getRequestId();523 try (Span span = TraceSessionRequest.extract(tracer, sessionRequest).createSpan("distributor.poll_queue")) {524 Map<String, EventAttributeValue> attributeMap = new HashMap<>();525 attributeMap.put(526 AttributeKey.LOGGER_CLASS.getKey(),527 EventAttribute.setValue(getClass().getName()));528 span.setAttribute(AttributeKey.REQUEST_ID.getKey(), reqId.toString());529 attributeMap.put(530 AttributeKey.REQUEST_ID.getKey(),531 EventAttribute.setValue(reqId.toString()));532 attributeMap.put("request", EventAttribute.setValue(sessionRequest.toString()));533 Either<SessionNotCreatedException, CreateSessionResponse> response = newSession(sessionRequest);534 if (response.isLeft() && response.left() instanceof RetrySessionRequestException) {535 try(Span childSpan = span.createSpan("distributor.retry")) {536 LOG.info("Retrying");537 boolean retried = sessionQueue.retryAddToQueue(sessionRequest);538 attributeMap.put("request.retry_add", EventAttribute.setValue(retried));539 childSpan.addEvent("Retry adding to front of queue. No slot available.", attributeMap);540 if (retried) {541 return;542 }543 childSpan.addEvent("retrying_request", attributeMap);544 }545 }546 sessionQueue.complete(reqId, response);547 }548 }549 }550}...
Source:LocalNewSessionQueueTest.java
...176 "value", ImmutableMap.of(177 "sessionId", sessionId,178 "capabilities", capabilities)))179 .getBytes(UTF_8));180 queue.complete(reqId, Either.right(sessionResponse));181 }));182 HttpResponse httpResponse = queue.addToQueue(sessionRequest);183 assertThat(isPresent.get()).isTrue();184 assertEquals(httpResponse.getStatus(), HTTP_OK);185 }186 @Test187 public void shouldBeAbleToAddToQueueAndGetErrorResponse() {188 bus.addListener(NewSessionRequestEvent.listener(reqId ->189 queue.complete(reqId, Either.left(new SessionNotCreatedException("Error")))));190 HttpResponse httpResponse = queue.addToQueue(sessionRequest);191 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);192 }193 @Test194 public void shouldBeAbleToRemoveFromQueue() {195 Optional<SessionRequest> httpRequest = queue.remove(new RequestId(UUID.randomUUID()));196 assertFalse(httpRequest.isPresent());197 }198 @Test199 public void shouldBeClearQueue() {200 RequestId requestId = new RequestId(UUID.randomUUID());201 localQueue.injectIntoQueue(sessionRequest);202 int count = queue.clearQueue();203 assertEquals(count, 1);204 assertFalse(queue.remove(requestId).isPresent());205 }206 @Test207 public void shouldBeAbleToGetQueueContents() {208 localQueue.injectIntoQueue(sessionRequest);209 List<Set<Capabilities>> response = queue.getQueueContents()210 .stream()211 .map(SessionRequestCapability::getDesiredCapabilities)212 .collect(Collectors.toList());213 assertThat(response).hasSize(1);214 assertEquals(Set.of(CAPS), response.get(0));215 }216 @Test217 public void shouldBeClearQueueAndFireRejectedEvent() throws InterruptedException {218 AtomicBoolean result = new AtomicBoolean(false);219 RequestId requestId = sessionRequest.getRequestId();220 CountDownLatch latch = new CountDownLatch(1);221 bus.addListener(222 NewSessionRejectedEvent.listener(223 response -> {224 result.set(response.getRequestId().equals(requestId));225 latch.countDown();226 }));227 localQueue.injectIntoQueue(sessionRequest);228 queue.remove(requestId);229 queue.retryAddToQueue(sessionRequest);230 int count = queue.clearQueue();231 assertThat(latch.await(2, SECONDS)).isTrue();232 assertThat(result.get()).isTrue();233 assertEquals(count, 1);234 assertFalse(queue.remove(requestId).isPresent());235 }236 @Test237 public void removingARequestIdThatDoesNotExistInTheQueueShouldNotBeAnError() {238 localQueue.injectIntoQueue(sessionRequest);239 Optional<SessionRequest> httpRequest = queue.remove(new RequestId(UUID.randomUUID()));240 assertFalse(httpRequest.isPresent());241 }242 @Test243 public void shouldBeAbleToAddAgainToQueue() {244 localQueue.injectIntoQueue(sessionRequest);245 Optional<SessionRequest> removed = queue.remove(sessionRequest.getRequestId());246 assertThat(removed).isPresent();247 boolean added = queue.retryAddToQueue(sessionRequest);248 assertTrue(added);249 }250 @Test251 public void shouldBeAbleToRetryRequest() {252 AtomicBoolean isPresent = new AtomicBoolean(false);253 AtomicBoolean retrySuccess = new AtomicBoolean(false);254 AtomicInteger count = new AtomicInteger(0);255 bus.addListener(256 NewSessionRequestEvent.listener(257 reqId -> {258 // Keep a count of event fired259 count.incrementAndGet();260 Optional<SessionRequest> sessionRequest = this.queue.remove(reqId);261 isPresent.set(sessionRequest.isPresent());262 if (count.get() == 1) {263 retrySuccess.set(queue.retryAddToQueue(sessionRequest.get()));264 }265 // Only if it was retried after an interval, the count is 2266 if (count.get() == 2) {267 ImmutableCapabilities capabilities =268 new ImmutableCapabilities("browserName", "edam");269 try {270 SessionId sessionId = new SessionId("123");271 Session session =272 new Session(273 sessionId,274 new URI("http://example.com"),275 CAPS,276 capabilities,277 Instant.now());278 CreateSessionResponse sessionResponse =279 new CreateSessionResponse(280 session,281 JSON.toJson(282 ImmutableMap.of(283 "value",284 ImmutableMap.of(285 "sessionId", sessionId,286 "capabilities", capabilities)))287 .getBytes(UTF_8));288 queue.complete(reqId, Either.right(sessionResponse));289 } catch (URISyntaxException e) {290 throw new RuntimeException(e);291 }292 }293 }));294 HttpResponse httpResponse = queue.addToQueue(sessionRequest);295 assertThat(isPresent.get()).isTrue();296 assertThat(retrySuccess.get()).isTrue();297 assertEquals(httpResponse.getStatus(), HTTP_OK);298 }299 @Test(timeout = 5000)300 public void shouldBeAbleToHandleMultipleSessionRequestsAtTheSameTime() {301 bus.addListener(NewSessionRequestEvent.listener(reqId -> {302 queue.remove(reqId);303 ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");304 try {305 SessionId sessionId = new SessionId(UUID.randomUUID());306 Session session =307 new Session(308 sessionId,309 new URI("http://example.com"),310 CAPS,311 capabilities,312 Instant.now());313 CreateSessionResponse sessionResponse = new CreateSessionResponse(314 session,315 JSON.toJson(316 ImmutableMap.of(317 "value", ImmutableMap.of(318 "sessionId", sessionId,319 "capabilities", capabilities)))320 .getBytes(UTF_8));321 queue.complete(reqId, Either.right(sessionResponse));322 } catch (URISyntaxException e) {323 queue.complete(reqId, Either.left(new SessionNotCreatedException(e.getMessage())));324 }325 }));326 ExecutorService executor = Executors.newFixedThreadPool(2);327 Callable<HttpResponse> callable = () -> {328 SessionRequest sessionRequest = new SessionRequest(329 new RequestId(UUID.randomUUID()),330 Instant.now(),331 Set.of(W3C),332 Set.of(CAPS),333 Map.of(),334 Map.of());335 return queue.addToQueue(sessionRequest);336 };337 Future<HttpResponse> firstRequest = executor.submit(callable);...
Source:LocalDistributorTest.java
...380 throw new RuntimeException(e);381 }382 });383 // If the sessions are created serially, then we expect the first384 // session to take up to `delay` ms to complete, followed by the385 // second session.386 assertThat(System.currentTimeMillis() - start).isLessThan(delay * 2);387 }388 private class Handler extends Session implements HttpHandler {389 private Handler(Capabilities capabilities) {390 super(new SessionId(UUID.randomUUID()), uri, new ImmutableCapabilities(), capabilities, Instant.now());391 }392 @Override393 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {394 return new HttpResponse();395 }396 }397}...
Source:LocalNewSessionQueue.java
...58 * <p>59 * The lifecycle of a request can be described as:60 * <ol>61 * <li>User adds an item on to the queue using {@link #addToQueue(SessionRequest)}. This62 * will block until the request completes in some way.63 * <li>After being added, a {@link NewSessionRequestEvent} is fired. Listeners should use64 * this as an indication to call {@link #remove(RequestId)} to get the session request.65 * <li>If the session request is completed, then {@link #complete(RequestId, Either)} must66 * be called. This will not only ensure that {@link #addToQueue(SessionRequest)}67 * returns, but will also fire a {@link NewSessionRejectedEvent} if the session was68 * rejected. Positive completions of events are assumed to be notified on the event bus69 * by other listeners.70 * <li>If the request cannot be handled right now, call71 * {@link #retryAddToQueue(SessionRequest)} to return the session request to the front72 * of the queue.73 * </ol>74 * <p>75 * There is a background thread that will reap {@link SessionRequest}s that have timed out.76 * This means that a request can either complete by a listener calling77 * {@link #complete(RequestId, Either)} directly, or by being reaped by the thread.78 */79@ManagedService(objectName = "org.seleniumhq.grid:type=SessionQueue,name=LocalSessionQueue",80 description = "New session queue")81public class LocalNewSessionQueue extends NewSessionQueue implements Closeable {82 private final EventBus bus;83 private final SlotMatcher slotMatcher;84 private final Duration requestTimeout;85 private final Map<RequestId, Data> requests;86 private final Map<RequestId, TraceContext> contexts;87 private final Deque<SessionRequest> queue;88 private final ReadWriteLock lock = new ReentrantReadWriteLock();89 private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(r -> {90 Thread thread = new Thread(r);91 thread.setDaemon(true);92 thread.setName("Local New Session Queue");93 return thread;94 });95 public LocalNewSessionQueue(96 Tracer tracer,97 EventBus bus,98 SlotMatcher slotMatcher,99 Duration retryPeriod,100 Duration requestTimeout,101 Secret registrationSecret) {102 super(tracer, registrationSecret);103 this.slotMatcher = Require.nonNull("Slot matcher", slotMatcher);104 this.bus = Require.nonNull("Event bus", bus);105 Require.nonNull("Retry period", retryPeriod);106 if (retryPeriod.isNegative() || retryPeriod.isZero()) {107 throw new IllegalArgumentException("Retry period must be positive");108 }109 this.requestTimeout = Require.nonNull("Request timeout", requestTimeout);110 if (requestTimeout.isNegative() || requestTimeout.isZero()) {111 throw new IllegalArgumentException("Request timeout must be positive");112 }113 this.requests = new ConcurrentHashMap<>();114 this.queue = new ConcurrentLinkedDeque<>();115 this.contexts = new ConcurrentHashMap<>();116 service.scheduleAtFixedRate(this::timeoutSessions, retryPeriod.toMillis(), retryPeriod.toMillis(), MILLISECONDS);117 new JMXHelper().register(this);118 }119 public static NewSessionQueue create(Config config) {120 LoggingOptions loggingOptions = new LoggingOptions(config);121 Tracer tracer = loggingOptions.getTracer();122 EventBusOptions eventBusOptions = new EventBusOptions(config);123 SessionRequestOptions requestOptions = new SessionRequestOptions(config);124 SecretOptions secretOptions = new SecretOptions(config);125 SlotMatcher slotMatcher = new DistributorOptions(config).getSlotMatcher();126 return new LocalNewSessionQueue(127 tracer,128 eventBusOptions.getEventBus(),129 slotMatcher,130 requestOptions.getSessionRequestRetryInterval(),131 requestOptions.getSessionRequestTimeout(),132 secretOptions.getRegistrationSecret());133 }134 private void timeoutSessions() {135 Instant now = Instant.now();136 Lock readLock = lock.readLock();137 readLock.lock();138 Set<RequestId> ids;139 try {140 ids = requests.entrySet().stream()141 .filter(entry -> isTimedOut(now, entry.getValue()))142 .map(Map.Entry::getKey)143 .collect(Collectors.toSet());144 } finally {145 readLock.unlock();146 }147 Lock writeLock = lock.writeLock();148 try {149 for (RequestId id : ids) {150 failDueToTimeout(id);151 }152 } finally {153 writeLock.unlock();154 }155 }156 private boolean isTimedOut(Instant now, Data data) {157 return data.endTime.isBefore(now);158 }159 @Override160 public HttpResponse addToQueue(SessionRequest request) {161 Require.nonNull("New session request", request);162 Require.nonNull("Request id", request.getRequestId());163 TraceContext context = TraceSessionRequest.extract(tracer, request);164 try (Span span = context.createSpan("sessionqueue.add_to_queue")) {165 contexts.put(request.getRequestId(), context);166 Data data = injectIntoQueue(request);167 if (isTimedOut(Instant.now(), data)) {168 failDueToTimeout(request.getRequestId());169 }170 Either<SessionNotCreatedException, CreateSessionResponse> result;171 try {172 if (data.latch.await(requestTimeout.toMillis(), MILLISECONDS)) {173 result = data.result;174 } else {175 result = Either.left(new SessionNotCreatedException("New session request timed out"));176 }177 } catch (InterruptedException e) {178 Thread.currentThread().interrupt();179 result = Either.left(new SessionNotCreatedException("Interrupted when creating the session", e));180 } catch (RuntimeException e) {181 result = Either.left(new SessionNotCreatedException("An error occurred creating the session", e));182 }183 Lock writeLock = this.lock.writeLock();184 writeLock.lock();185 try {186 requests.remove(request.getRequestId());187 queue.remove(request);188 } finally {189 writeLock.unlock();190 }191 HttpResponse res = new HttpResponse();192 if (result.isRight()) {193 res.setContent(Contents.bytes(result.right().getDownstreamEncodedResponse()));194 } else {195 res.setStatus(HTTP_INTERNAL_ERROR)196 .setContent(Contents.asJson(Collections.singletonMap("value", result.left())));197 }198 return res;199 }200 }201 @VisibleForTesting202 Data injectIntoQueue(SessionRequest request) {203 Require.nonNull("Session request", request);204 Data data = new Data(request.getEnqueued());205 Lock writeLock = lock.writeLock();206 writeLock.lock();207 try {208 requests.put(request.getRequestId(), data);209 queue.addLast(request);210 } finally {211 writeLock.unlock();212 }213 bus.fire(new NewSessionRequestEvent(request.getRequestId()));214 return data;215 }216 @Override217 public boolean retryAddToQueue(SessionRequest request) {218 Require.nonNull("New session request", request);219 boolean added;220 TraceContext context = contexts.getOrDefault(request.getRequestId(), tracer.getCurrentContext());221 try (Span span = context.createSpan("sessionqueue.retry")) {222 Lock writeLock = lock.writeLock();223 writeLock.lock();224 try {225 if (!requests.containsKey(request.getRequestId())) {226 return false;227 }228 if (queue.contains(request)) {229 // No need to re-add this230 return true;231 } else {232 added = queue.offerFirst(request);233 }234 } finally {235 writeLock.unlock();236 }237 if (added) {238 bus.fire(new NewSessionRequestEvent(request.getRequestId()));239 }240 return added;241 }242 }243 @Override244 public Optional<SessionRequest> remove(RequestId reqId) {245 Require.nonNull("Request ID", reqId);246 Lock writeLock = lock.writeLock();247 writeLock.lock();248 try {249 Iterator<SessionRequest> iterator = queue.iterator();250 while (iterator.hasNext()) {251 SessionRequest req = iterator.next();252 if (reqId.equals(req.getRequestId())) {253 iterator.remove();254 return Optional.of(req);255 }256 }257 return Optional.empty();258 } finally {259 writeLock.unlock();260 }261 }262 @Override263 public Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes) {264 Require.nonNull("Stereotypes", stereotypes);265 Predicate<Capabilities> matchesStereotype =266 caps -> stereotypes.stream().anyMatch(stereotype -> slotMatcher.matches(stereotype, caps));267 Lock writeLock = lock.writeLock();268 writeLock.lock();269 try {270 Optional<SessionRequest> maybeRequest =271 queue.stream()272 .filter(req -> req.getDesiredCapabilities().stream().anyMatch(matchesStereotype))273 .findFirst();274 maybeRequest.ifPresent(req -> {275 this.remove(req.getRequestId());276 });277 return maybeRequest;278 } finally {279 writeLock.unlock();280 }281 }282 @Override283 public void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result) {284 Require.nonNull("New session request", reqId);285 Require.nonNull("Result", result);286 TraceContext context = contexts.getOrDefault(reqId, tracer.getCurrentContext());287 try (Span span = context.createSpan("sessionqueue.completed")) {288 Lock readLock = lock.readLock();289 readLock.lock();290 Data data;291 try {292 data = requests.get(reqId);293 } finally {294 readLock.unlock();295 }296 if (data == null) {297 return;298 }299 Lock writeLock = lock.writeLock();300 writeLock.lock();301 try {302 requests.remove(reqId);303 queue.removeIf(req -> reqId.equals(req.getRequestId()));304 contexts.remove(reqId);305 } finally {306 writeLock.unlock();307 }308 if (result.isLeft()) {309 bus.fire(new NewSessionRejectedEvent(new NewSessionErrorResponse(reqId, result.left().getMessage())));310 }311 data.setResult(result);312 }313 }314 @Override315 public int clearQueue() {316 Lock writeLock = lock.writeLock();317 writeLock.lock();318 try {319 int size = queue.size();320 queue.clear();321 requests.forEach((reqId, data) -> {322 data.setResult(Either.left(new SessionNotCreatedException("Request queue was cleared")));323 bus.fire(new NewSessionRejectedEvent(324 new NewSessionErrorResponse(reqId, "New session queue was forcibly cleared")));325 });326 requests.clear();327 return size;328 } finally {329 writeLock.unlock();330 }331 }332 @Override333 public List<SessionRequestCapability> getQueueContents() {334 Lock readLock = lock.readLock();335 readLock.lock();336 try {337 return queue.stream()338 .map(req ->339 new SessionRequestCapability(req.getRequestId(), req.getDesiredCapabilities()))340 .collect(Collectors.toList());341 } finally {342 readLock.unlock();343 }344 }345 @ManagedAttribute(name = "NewSessionQueueSize")346 public int getQueueSize() {347 return queue.size();348 }349 @Override350 public boolean isReady() {351 return true;352 }353 @Override354 public void close() throws IOException {355 service.shutdownNow();356 }357 private void failDueToTimeout(RequestId reqId) {358 complete(reqId, Either.left(new SessionNotCreatedException("Timed out creating session")));359 }360 private class Data {361 public final Instant endTime;362 public Either<SessionNotCreatedException, CreateSessionResponse> result;363 private boolean complete;364 private CountDownLatch latch = new CountDownLatch(1);365 public Data(Instant enqueued) {366 this.endTime = enqueued.plus(requestTimeout);367 this.result = Either.left(new SessionNotCreatedException("Session not created"));368 }369 public synchronized void setResult(Either<SessionNotCreatedException, CreateSessionResponse> result) {370 if (complete) {371 return;372 }373 this.result = result;374 complete = true;375 latch.countDown();376 }377 }378}...
Source:RemoteNewSessionQueue.java
...119 SessionRequest value = Values.get(response, SessionRequest.class);120 return Optional.ofNullable(value);121 }122 @Override123 public void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result) {124 Require.nonNull("Request ID", reqId);125 Require.nonNull("Result", result);126 HttpRequest upstream;127 if (result.isRight()) {128 upstream = new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/success", reqId))129 .setContent(Contents.asJson(result.right()));130 } else {131 upstream = new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/failure", reqId))132 .setContent(Contents.asJson(result.left().getRawMessage()));133 }134 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);135 client.with(addSecret).execute(upstream);136 }137 @Override...
Source:NewSessionQueue.java
...88 public abstract HttpResponse addToQueue(SessionRequest request);89 public abstract boolean retryAddToQueue(SessionRequest request);90 public abstract Optional<SessionRequest> remove(RequestId reqId);91 public abstract Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes);92 public abstract void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result);93 public abstract int clearQueue();94 public abstract List<SessionRequestCapability> getQueueContents();95 @Override96 public boolean matches(HttpRequest req) {97 return routes.matches(req);98 }99 @Override100 public HttpResponse execute(HttpRequest req) {101 return routes.execute(req);102 }103}...
Source:SessionNotCreated.java
...43 try (Span span = newSpanAsChildOf(tracer, req, "sessionqueue.created_bad")) {44 HTTP_REQUEST.accept(span, req);45 String message = Contents.fromJson(req, String.class);46 SessionNotCreatedException exception = new SessionNotCreatedException(message);47 queue.complete(requestId, Either.left(exception));48 HttpResponse res = new HttpResponse();49 HTTP_RESPONSE.accept(span, res);50 return res;51 }52 }53}...
Source:SessionCreated.java
...42 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {43 try (Span span = newSpanAsChildOf(tracer, req, "sessionqueue.created_ok")) {44 HTTP_REQUEST.accept(span, req);45 CreateSessionResponse response = Contents.fromJson(req, CreateSessionResponse.class);46 queue.complete(requestId, Either.right(response));47 HttpResponse res = new HttpResponse();48 HTTP_RESPONSE.accept(span, res);49 return res;50 }51 }52}...
complete
Using AI Code Generation
1import org.openqa.selenium.grid.config.Config;2import org.openqa.selenium.grid.config.MapConfig;3import org.openqa.selenium.grid.config.TomlConfig;4import org.openqa.selenium.grid.data.Session;5import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;6import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;7import org.openqa.selenium.remote.http.HttpClient;8import org.openqa.selenium.remote.tracing.Tracer;9import org.openqa.selenium.remote.tracing.distributed.DistributedTracer;10import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryOptions;11import java.util.concurrent.TimeUnit;12public class CompleteMethod {13 public static void main(String[] args) {14 Tracer tracer = new DistributedTracer(15 OpenTelemetryOptions.builder().readFrom(new MapConfig()).build());16 Config config = new TomlConfig("config.toml");17 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();18 NewSessionQueue queue = new LocalNewSessionQueue(tracer, clientFactory, config);19 Session session = queue.poll();20 queue.complete(session);21 }22}
complete
Using AI Code Generation
1import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;2import org.openqa.selenium.grid.sessionqueue.config.SessionQueueOptions;3import org.openqa.selenium.grid.sessionqueue.config.SessionQueueOptions.SessionQueueOptionsProto;4import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;5import org.openqa.selenium.remote.http.HttpClient;6import org.openqa.selenium.remote.tracing.Tracer;7import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;8public class Test {9 public static void main(String[] args) {10 Tracer tracer = OpenTelemetryTracer.create();11 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();12 SessionQueueOptions options = SessionQueueOptions.from(new SessionQueueOptionsProto());13 NewSessionQueue queue = LocalNewSessionQueue.create(tracer, clientFactory, options);14 queue.complete("session-id");15 }16}
complete
Using AI Code Generation
1package org.openqa.selenium.grid.sessionqueue;2import java.util.concurrent.CompletableFuture;3import java.util.concurrent.CompletionStage;4import org.openqa.selenium.grid.data.Session;5import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;6import org.openqa.selenium.internal.Require;7import org.openqa.selenium.remote.http.HttpRequest;8public class NewSessionQueue {9 private final NewSessionQueue newSessionQueue;10 public NewSessionQueue(NewSessionQueue newSessionQueue) {11 this.newSessionQueue = Require.nonNull("New Session Queue", newSessionQueue);12 }13 public CompletionStage<Session> add(HttpRequest req) {14 return newSessionQueue.add(req);15 }16 public static NewSessionQueue create() {17 return new NewSessionQueue(new LocalNewSessionQueue());18 }19}20import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;21import java.util.concurrent.CompletableFuture;22public class Test {23 public static void main(String[] args) {24 NewSessionQueue sessionQueue = NewSessionQueue.create();25 CompletableFuture<String> completableFuture = new CompletableFuture<>();26 sessionQueue.add(null).whenComplete((session, throwable) -> {27 if (throwable != null) {28 completableFuture.completeExceptionally(throwable);29 } else {30 completableFuture.complete(session.getId().toString());31 }32 });33 }34}35[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ grid ---36[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ grid ---37[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ grid ---
complete
Using AI Code Generation
1package org.openqa.selenium.grid.sessionqueue;2import java.util.List;3import java.util.UUID;4import org.openqa.selenium.grid.data.Session;5public class NewSessionQueue {6public List<Session> getSessions() {7return null;8}9public void add(Session session) {10}11public void remove(UUID id) {12}13public Session complete() {14return null;15}16}
complete
Using AI Code Generation
1 public void complete(SessionId sessionId) {2 synchronized (this) {3 if (sessions.remove(sessionId)) {4 notifyAll();5 }6 }7 }8}9package org.openqa.selenium.grid.sessionqueue;10import org.openqa.selenium.SessionNotCreatedException;11import org.openqa.selenium.grid.data.Session;12import org.openqa.selenium.grid.data.SessionId;13import org.openqa.selenium.grid.data.Slot;14import org.openqa.selenium.grid.data.SlotId;15import org.openqa.selenium.grid.node.Node;16import org.openqa.selenium.grid.node.NodeId;17import org.openqa.selenium.grid.node.local.LocalNode;18import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;19import org.openqa.selenium.grid.sessionqueue.local.LocalSessionQueue;20import org.openqa.selenium.internal.Require;21import org.openqa.selenium.remote.http.HttpClient;22import org.openqa.selenium.remote.http.HttpRequest;23import org.openqa.selenium.remote.http.HttpResponse;24import org.openqa.selenium.remote.tracing.DefaultTestTracer;25import org.openqa.selenium.remote.tracing.Tracer;26import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;27import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerFactory;28import org.openqa.selenium.testing.drivers.Browser;29import org.openqa.selenium.testing.drivers.WebDriverBuilder;30import org.openqa.selenium.testing.drivers.WebDriverBuilder.DriverOptions;31import org.openqa.selenium.testing.drivers.WebDriverBuilder.Environment;32import org.openqa.selenium.testing.drivers.WebDriverBuilder.GridOptions;33import org.openqa.selenium.testing.drivers.WebDriverBuilder.Platform;34import org.openqa.selenium.testing.drivers.WebDriverBuilder.SauceOptions;35import org.openqa.selenium.testing.drivers.WebDriverBuilder.SeleniumServerOptions;36import org.openqa.selenium.testing.drivers.WebDriverBuilder.SeleniumStandaloneOptions;37import org.openqa.selenium.testing.drivers.WebDriverBuilder.WebDriverOptions;38import org.openqa.selenium.testing.drivers.WebDriverBuilder.WebDriverType;39import org.openqa.selenium.testing.drivers.WebDriverBuilder.WebDriverVersion;40import org.openqa.selenium.testing.drivers.WebDriverBuilder.WebserverOptions;41import org.openqa.selenium.testing.drivers.WebDriverBuilder.WebserverType;42import org.openqa.selenium.testing.junit4.TestBase;43import org.openqa.selenium.testing.junit4.WebDriverBuilderHolder;44import org.openqa.selenium.testing.JUnit4TestBase;45import org.openqa.selenium.testing.drivers.Browser;46import org.openqa.selenium.testing.drivers.WebDriverBuilder;47import org.openqa.selenium.testing.dr
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!!