How to use complete method of org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue class

Best Selenium code snippet using org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue.complete

Source:LocalDistributor.java Github

copy

Full Screen

...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}...

Full Screen

Full Screen

Source:LocalNewSessionQueueTest.java Github

copy

Full Screen

...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);...

Full Screen

Full Screen

Source:RemoteNewSessionQueue.java Github

copy

Full Screen

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

Full Screen

Full Screen

complete

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.config.Config;2import org.openqa.selenium.grid.config.MapConfig;3import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;4import java.net.URI;5import java.net.URISyntaxException;6import java.util.HashMap;7import java.util.Map;8public class RemoteNewSessionQueueExample {9 public static void main(String[] args) throws URISyntaxException {10 Map<String, String> configMap = new HashMap<>();11 Config config = new MapConfig(configMap);12 RemoteNewSessionQueue queue = new RemoteNewSessionQueue(config);13 }14}15public class RemoteNewSessionQueue implements NewSessionQueue {16 private final URI server;17 private final HttpClient.Factory clientFactory;18 public RemoteNewSessionQueue(Config config) {19 this(config.get("server").map(URI::create).orElseThrow(() -> new ConfigException("Missing server")),20 HttpClient.Factory.createDefault());21 }22 public RemoteNewSessionQueue(URI server, HttpClient.Factory clientFactory) {23 this.server = requireNonNull(server);24 this.clientFactory = requireNonNull(clientFactory);25 }26 public void add(HttpRequest request) {27 clientFactory.createClient(server)28 .execute(new HttpRequest("POST", server.resolve("/se/grid/node/session")))29 .discardContent();30 }31 public void complete(URI uri, String id) {32 clientFactory.createClient(uri)33 .execute(new HttpRequest("DELETE", uri.resolve(String.format("/session/%s", id))))34 .discardContent();35 }36}37package org.openqa.selenium.grid.sessionqueue.remote;38import org.openqa.selenium.grid.config.Config;39import org.openqa.selenium.grid.config.ConfigException;40import org.openqa.selenium.grid.config.MemoizedConfig;41import org.openqa.selenium.grid.config.MemoizedConfig.ValueSupplier;42import org.openqa.selenium.grid.config.Role;43import org.openqa.selenium.grid.data.Session;44import org.openqa.selenium.grid.log.LoggingOptions;45import org.openqa.selenium.grid.server.BaseServerOptions;46import org.openqa.selenium.grid.server.Server;47import org.openqa.selenium.grid.server.ServerFlags;48import org.openqa.selenium.grid.server.ServerSecrets;49import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;50import org.openqa.selenium.grid.sessionqueue.NewSessionQueues;51import org.openqa.selenium

Full Screen

Full Screen

complete

Using AI Code Generation

copy

Full Screen

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.data.SessionId;6import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;7import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;8import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;9import org.openqa.selenium.remote.http.HttpClient;10import org.openqa.selenium.remote.http.HttpRequest;11import org.openqa.selenium.remote.http.HttpResponse;12import org.openqa.selenium.remote.tracing.Tracer;13import java.net.URI;14import java.util.Map;15import java.util.Objects;16import java.util.concurrent.CompletableFuture;17public class NewSessionQueueExample {18 public static void main(String[] args) {19 Config config = new TomlConfig("config.toml");20 Tracer tracer = Tracer.getDefault();21 NewSessionQueue sessionQueue = new LocalNewSessionQueue(tracer, config);22 Session newSession = Session.create(23 new SessionId("session-id"),24 null);25 sessionQueue.add(newSession);26 CompletableFuture<Session> session = sessionQueue.getNewSession();27 sessionQueue.complete(session);28 Map<String, Object> rawConfig = Map.of("foo", "bar");29 Config mapConfig = new MapConfig(rawConfig);30 NewSessionQueue sessionQueueWithMapConfig = new LocalNewSessionQueue(tracer, mapConfig);31 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();32 NewSessionQueue remoteSessionQueue = new RemoteNewSessionQueue(33 remoteSessionQueue.add(newSession);

Full Screen

Full Screen

complete

Using AI Code Generation

copy

Full Screen

1 public void complete(String id, Session session) {2 try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {3 HttpPost request = new HttpPost(String.format("%s/session/%s", this.uri, id));4 request.setEntity(new StringEntity(this.mapper.writeValueAsString(session), ContentType.APPLICATION_JSON));5 httpClient.execute(request);6 } catch (IOException e) {7 throw new UncheckedIOException(e);8 }9 }10}

Full Screen

Full Screen

complete

Using AI Code Generation

copy

Full Screen

1package com.seleniumgrid;2import java.net.URI;3import java.util.List;4import java.util.Objects;5import java.util.Optional;6import java.util.concurrent.CompletableFuture;7import java.util.concurrent.CompletionStage;8import java.util.concurrent.ConcurrentHashMap;9import java.util.concurrent.ConcurrentMap;10import java.util.concurrent.Executor;11import java.util.concurrent.Executors;12import java.util.function.Supplier;13import java.util.logging.Logger;14import java.util.stream.Collectors;15import java.util.stream.Stream;16import org.openqa.selenium.Capabilities;17import org.openqa.selenium.grid.data.Session;18import org.openqa.selenium.grid.sessionqueue.NewSessionQueuer;19import org.openqa.selenium.internal.Require;20import org.openqa.selenium.json.Json;21import org.openqa.selenium.remote.http.HttpClient;22import org.openqa.selenium.remote.http.HttpMethod;23import org.openqa.selenium.remote.http.HttpRequest;24import org.openqa.selenium.remote.http.HttpResponse;25public class RemoteNewSessionQueue implements NewSessionQueuer {26 private static final Logger LOG = Logger.getLogger(RemoteNewSessionQueue.class.getName());27 private final Json json;28 private final HttpClient client;29 private final Executor executor;30 private final ConcurrentMap<String, CompletableFuture<Session>> sessions = new ConcurrentHashMap<>();31 private final URI uri;32 public RemoteNewSessionQueue(Json json, HttpClient client, Executor executor, URI uri) {33 this.json = Require.nonNull("JSON parser", json);34 this.client = Require.nonNull("HTTP client", client);35 this.executor = Require.nonNull("Executor", executor);36 this.uri = Require.nonNull("URI", uri);37 }38 public CompletionStage<Session> add(Capabilities capabilities) {39 Require.nonNull("Capabilities", capabilities);40 HttpRequest request = new HttpRequest(HttpMethod.POST, uri);41 request.setContent(json.toJson(capabilities));42 CompletableFuture<HttpResponse> response = client.execute(request, true);43 CompletableFuture<Session> toReturn = new CompletableFuture<>();44 response.thenAccept(resp -> {45 if (resp.getStatus() != 200) {46 toReturn.completeExceptionally(new RuntimeException("Unable to add session to queue"));47 return;48 }49 Session session = json.toType(resp.getContentString(), Session.class);50 sessions.put(session.getId(), toReturn);51 toReturn.complete(session);52 });53 return toReturn;54 }55 public CompletionStage<Session> get(String id) {56 Require.nonNull("Session ID", id);57 return Optional.ofNullable(sessions.get(id))58 .orElseGet(() -> {

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