Best Selenium code snippet using org.openqa.selenium.grid.data.NewSessionRejectedEvent.listener
Source:LocalNewSessionQueueTest.java
...157 }158 @Test159 public void shouldBeAbleToAddToQueueAndGetValidResponse() {160 AtomicBoolean isPresent = new AtomicBoolean(false);161 bus.addListener(NewSessionRequestEvent.listener(reqId -> {162 isPresent.set(true);163 Capabilities capabilities = new ImmutableCapabilities("browserName", "chrome");164 SessionId sessionId = new SessionId("123");165 Session session =166 new Session(167 sessionId,168 URI.create("http://example.com"),169 CAPS,170 capabilities,171 Instant.now());172 CreateSessionResponse sessionResponse = new CreateSessionResponse(173 session,174 JSON.toJson(175 ImmutableMap.of(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);338 Future<HttpResponse> secondRequest = executor.submit(callable);339 try {340 HttpResponse firstResponse = firstRequest.get(30, SECONDS);341 HttpResponse secondResponse = secondRequest.get(30, SECONDS);342 String firstResponseContents = Contents.string(firstResponse);343 String secondResponseContents = Contents.string(secondResponse);344 assertEquals(firstResponse.getStatus(), HTTP_OK);345 assertEquals(secondResponse.getStatus(), HTTP_OK);346 assertNotEquals(firstResponseContents, secondResponseContents);347 } catch (InterruptedException | ExecutionException | TimeoutException e) {348 fail("Could not create session");349 }350 executor.shutdown();351 }352 @Test(timeout = 5000)353 public void shouldBeAbleToTimeoutARequestOnRetry() {354 final SessionRequest request = new SessionRequest(355 new RequestId(UUID.randomUUID()),356 LONG_AGO,357 Set.of(W3C),358 Set.of(CAPS),359 Map.of(),360 Map.of());361 AtomicInteger count = new AtomicInteger();362 bus.addListener(NewSessionRejectedEvent.listener(reqId -> {363 count.incrementAndGet();364 }));365 HttpResponse httpResponse = queue.addToQueue(request);366 assertEquals(1, count.get());367 assertEquals(HTTP_INTERNAL_ERROR, httpResponse.getStatus());368 }369 @Test(timeout = 10000)370 public void shouldBeAbleToTimeoutARequestOnRemove() throws InterruptedException {371 AtomicReference<RequestId> isPresent = new AtomicReference<>();372 CountDownLatch latch = new CountDownLatch(1);373 bus.addListener(374 NewSessionRejectedEvent.listener(375 response -> {376 isPresent.set(response.getRequestId());377 latch.countDown();378 }));379 SessionRequest sessionRequest = new SessionRequest(380 new RequestId(UUID.randomUUID()),381 LONG_AGO,382 Set.of(W3C),383 Set.of(CAPS),384 Map.of(),385 Map.of());386 localQueue.injectIntoQueue(sessionRequest);387 queue.remove(sessionRequest.getRequestId());388 assertThat(latch.await(4, SECONDS)).isTrue();...
Source:NewSessionQueuerTest.java
...101 }102 @Test103 public void shouldBeAbleToAddToQueueAndGetValidResponse() {104 AtomicBoolean isPresent = new AtomicBoolean(false);105 bus.addListener(NewSessionRequestEvent.listener(reqId -> {106 Optional<HttpRequest> sessionRequest = this.local.remove();107 isPresent.set(sessionRequest.isPresent());108 Capabilities capabilities = new ImmutableCapabilities("browserName", "chrome");109 try {110 SessionId sessionId = new SessionId("123");111 Session session =112 new Session(113 sessionId,114 new URI("http://example.com"),115 caps,116 capabilities,117 Instant.now());118 CreateSessionResponse sessionResponse = new CreateSessionResponse(119 session,120 JSON.toJson(121 ImmutableMap.of(122 "value", ImmutableMap.of(123 "sessionId", sessionId,124 "capabilities", capabilities)))125 .getBytes(UTF_8));126 NewSessionResponse newSessionResponse =127 new NewSessionResponse(reqId, sessionResponse.getSession(),128 sessionResponse.getDownstreamEncodedResponse());129 bus.fire(new NewSessionResponseEvent(newSessionResponse));130 } catch (URISyntaxException e) {131 bus.fire(132 new NewSessionRejectedEvent(133 new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));134 }135 }));136 HttpResponse httpResponse = local.addToQueue(request);137 assertThat(isPresent.get()).isTrue();138 assertEquals(httpResponse.getStatus(), HTTP_OK);139 }140 @Test141 public void shouldBeAbleToAddToQueueAndGetErrorResponse() {142 AtomicBoolean isPresent = new AtomicBoolean(false);143 bus.addListener(NewSessionRequestEvent.listener(reqId -> {144 Optional<HttpRequest> sessionRequest = this.local.remove();145 isPresent.set(sessionRequest.isPresent());146 bus.fire(147 new NewSessionRejectedEvent(148 new NewSessionErrorResponse(reqId, "Error")));149 }));150 HttpResponse httpResponse = local.addToQueue(request);151 assertThat(isPresent.get()).isTrue();152 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);153 }154 @Test155 public void shouldBeAbleToAddToQueueRemotelyAndGetErrorResponse() {156 AtomicBoolean isPresent = new AtomicBoolean(false);157 bus.addListener(NewSessionRequestEvent.listener(reqId -> {158 Optional<HttpRequest> sessionRequest = this.remote.remove();159 isPresent.set(sessionRequest.isPresent());160 bus.fire(161 new NewSessionRejectedEvent(162 new NewSessionErrorResponse(reqId, "Could not poll the queue")));163 }));164 HttpResponse httpResponse = remote.addToQueue(request);165 assertThat(isPresent.get()).isTrue();166 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);167 }168 @Test169 public void shouldBeAbleToRemoveFromQueue() {170 Optional<HttpRequest> httpRequest = local.remove();171 assertFalse(httpRequest.isPresent());172 }173 @Test174 public void shouldBeClearQueue() {175 RequestId requestId = new RequestId(UUID.randomUUID());176 sessionQueue.offerLast(request, requestId);177 int count = local.clearQueue();178 assertEquals(count, 1);179 assertFalse(local.remove().isPresent());180 }181 @Test182 public void shouldBeClearQueueRemotely() {183 RequestId requestId = new RequestId(UUID.randomUUID());184 sessionQueue.offerLast(request, requestId);185 int count = remote.clearQueue();186 assertEquals(count, 1);187 assertFalse(remote.remove().isPresent());188 }189 @Test190 public void shouldBeClearQueueAndFireRejectedEvent() {191 AtomicBoolean result = new AtomicBoolean(false);192 RequestId requestId = new RequestId(UUID.randomUUID());193 bus.addListener(NewSessionRejectedEvent.listener(response ->194 result.set(response.getRequestId()195 .equals(requestId))));196 sessionQueue.offerLast(request, requestId);197 int count = remote.clearQueue();198 assertThat(result.get()).isTrue();199 assertEquals(count, 1);200 assertFalse(remote.remove().isPresent());201 }202 @Test203 public void shouldBeAbleToRemoveFromQueueRemotely() {204 Optional<HttpRequest> httpRequest = remote.remove();205 assertFalse(httpRequest.isPresent());206 }207 @Test208 public void shouldBeAbleToAddAgainToQueue() {209 boolean added = local.retryAddToQueue(request, new RequestId(UUID.randomUUID()));210 assertTrue(added);211 }212 @Test213 public void shouldBeAbleToAddAgainToQueueRemotely() {214 HttpRequest request = createRequest(payload, POST, "/se/grid/newsessionqueuer/session");215 boolean added = remote.retryAddToQueue(request, new RequestId(UUID.randomUUID()));216 assertTrue(added);217 }218 @Test219 public void shouldBeAbleToRetryRequest() {220 AtomicBoolean isPresent = new AtomicBoolean(false);221 AtomicBoolean retrySuccess = new AtomicBoolean(false);222 bus.addListener(NewSessionRequestEvent.listener(reqId -> {223 // Keep a count of event fired224 count++;225 Optional<HttpRequest> sessionRequest = this.remote.remove();226 isPresent.set(sessionRequest.isPresent());227 if (count == 1) {228 retrySuccess.set(remote.retryAddToQueue(sessionRequest.get(), reqId));229 }230 // Only if it was retried after an interval, the count is 2231 if (count == 2) {232 ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");233 try {234 SessionId sessionId = new SessionId("123");235 Session session =236 new Session(237 sessionId,238 new URI("http://example.com"),239 caps,240 capabilities,241 Instant.now());242 CreateSessionResponse sessionResponse = new CreateSessionResponse(243 session,244 JSON.toJson(245 ImmutableMap.of(246 "value", ImmutableMap.of(247 "sessionId", sessionId,248 "capabilities", capabilities)))249 .getBytes(UTF_8));250 NewSessionResponse newSessionResponse =251 new NewSessionResponse(reqId, sessionResponse.getSession(),252 sessionResponse.getDownstreamEncodedResponse());253 bus.fire(new NewSessionResponseEvent(newSessionResponse));254 } catch (URISyntaxException e) {255 bus.fire(256 new NewSessionRejectedEvent(257 new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));258 }259 }260 }));261 HttpResponse httpResponse = remote.addToQueue(request);262 assertThat(isPresent.get()).isTrue();263 assertThat(retrySuccess.get()).isTrue();264 assertEquals(httpResponse.getStatus(), HTTP_OK);265 }266 @Test267 public void shouldBeAbleToHandleMultipleSessionRequestsAtTheSameTime() {268 bus.addListener(NewSessionRequestEvent.listener(reqId -> {269 Optional<HttpRequest> sessionRequest = this.local.remove();270 ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");271 try {272 SessionId sessionId = new SessionId(UUID.randomUUID());273 Session session =274 new Session(275 sessionId,276 new URI("http://example.com"),277 caps,278 capabilities,279 Instant.now());280 CreateSessionResponse sessionResponse = new CreateSessionResponse(281 session,282 JSON.toJson(283 ImmutableMap.of(284 "value", ImmutableMap.of(285 "sessionId", sessionId,286 "capabilities", capabilities)))287 .getBytes(UTF_8));288 NewSessionResponse newSessionResponse =289 new NewSessionResponse(reqId, sessionResponse.getSession(),290 sessionResponse.getDownstreamEncodedResponse());291 bus.fire(new NewSessionResponseEvent(newSessionResponse));292 } catch (URISyntaxException e) {293 bus.fire(294 new NewSessionRejectedEvent(295 new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));296 }297 }));298 ExecutorService executor = Executors.newFixedThreadPool(2);299 Callable<HttpResponse> callable = () -> remote.addToQueue(request);300 Future<HttpResponse> firstRequest = executor.submit(callable);301 Future<HttpResponse> secondRequest = executor.submit(callable);302 try {303 HttpResponse firstResponse = firstRequest.get(30, TimeUnit.SECONDS);304 HttpResponse secondResponse = secondRequest.get(30, TimeUnit.SECONDS);305 String firstResponseContents = Contents.string(firstResponse);306 String secondResponseContents = Contents.string(secondResponse);307 assertEquals(firstResponse.getStatus(), HTTP_OK);308 assertEquals(secondResponse.getStatus(), HTTP_OK);309 assertNotEquals(firstResponseContents, secondResponseContents);310 } catch (InterruptedException | ExecutionException | TimeoutException e) {311 fail("Could not create session");312 }313 executor.shutdown();314 }315 @Test316 public void shouldBeAbleToTimeoutARequestOnRetry() {317 Tracer tracer = DefaultTestTracer.createTracer();318 LocalNewSessionQueue sessionQueue = new LocalNewSessionQueue(319 tracer,320 bus,321 Duration.ofSeconds(4),322 Duration.ofSeconds(2));323 local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);324 HttpClient client = new PassthroughHttpClient(local);325 remote = new RemoteNewSessionQueuer(tracer, client);326 HttpRequest request = createRequest(payload, POST, "/session");327 request.addHeader(SESSIONREQUEST_TIMESTAMP_HEADER,328 Long.toString(1539091064));329 AtomicInteger count = new AtomicInteger();330 bus.addListener(NewSessionRequestEvent.listener(reqId -> {331 // Add to front of queue, when retry is triggered it will check if request timed out332 count.incrementAndGet();333 remote.retryAddToQueue(request, reqId);334 }));335 HttpResponse httpResponse = remote.addToQueue(request);336 assertEquals(count.get(),1);337 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);338 }339 @Test340 public void shouldBeAbleToTimeoutARequestOnPoll() {341 Tracer tracer = DefaultTestTracer.createTracer();342 LocalNewSessionQueue sessionQueue = new LocalNewSessionQueue(343 tracer,344 bus,345 Duration.ofSeconds(4),346 Duration.ofSeconds(0));347 local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);348 HttpClient client = new PassthroughHttpClient(local);349 remote = new RemoteNewSessionQueuer(tracer, client);350 AtomicBoolean isPresent = new AtomicBoolean();351 bus.addListener(NewSessionRequestEvent.listener(reqId -> {352 Optional<HttpRequest> request = remote.remove();353 isPresent.set(request.isPresent());354 bus.fire(355 new NewSessionRejectedEvent(356 new NewSessionErrorResponse(reqId, "Error")));357 }));358 HttpResponse httpResponse = remote.addToQueue(request);359 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);360 assertThat(isPresent.get()).isFalse();361 }362 @Test363 public void shouldBeAbleToClearQueueAndRejectMultipleRequests() {364 ExecutorService executor = Executors.newFixedThreadPool(2);365 Callable<HttpResponse> callable = () -> remote.addToQueue(request);...
Source:LocalDistributor.java
...123 this.nodes = new ConcurrentHashMap<>();124 this.sessionRequests = Require.nonNull("New Session Request Queue", sessionRequests);125 this.registrationSecret = Require.nonNull("Registration secret", registrationSecret);126 this.healthcheckInterval = Require.nonNull("Health check interval", healthcheckInterval);127 bus.addListener(NodeStatusEvent.listener(this::register));128 bus.addListener(NodeStatusEvent.listener(model::refresh));129 bus.addListener(NodeHeartBeatEvent.listener(nodeStatus -> {130 if (nodes.containsKey(nodeStatus.getId())) {131 model.touch(nodeStatus.getId());132 } else {133 register(nodeStatus);134 }135 }));136 bus.addListener(NodeDrainComplete.listener(this::remove));137 bus.addListener(NewSessionRequestEvent.listener(requestIds::offer));138 Regularly regularly = new Regularly("Local Distributor");139 regularly.submit(model::purgeDeadNodes, Duration.ofSeconds(30), Duration.ofSeconds(30));140 Thread shutdownHook = new Thread(this::callExecutorShutdown);141 Runtime.getRuntime().addShutdownHook(shutdownHook);142 NewSessionRunnable runnable = new NewSessionRunnable();143 ThreadFactory threadFactory = r -> {144 Thread thread = new Thread(r);145 thread.setName("New Session Creation");146 thread.setDaemon(true);147 return thread;148 };149 executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);150 executorService.scheduleAtFixedRate(runnable, 0, 1000, TimeUnit.MILLISECONDS);151 }...
Source:LocalNewSessionQueue.java
...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);...
Source:GetNewSessionResponse.java
...47 NewSessionQueue sessionRequests) {48 this.tracer = Require.nonNull("Tracer", tracer);49 this.bus = Require.nonNull("Event bus", bus);50 this.sessionRequests = Require.nonNull("New Session Request Queue", sessionRequests);51 this.bus.addListener(NewSessionResponseEvent.listener(sessionResponse -> {52 try {53 this.setResponse(sessionResponse);54 } catch (Exception ignore) {55 // Ignore any exception. Do not want to block the eventbus thread.56 }57 }));58 this.bus.addListener(NewSessionRejectedEvent.listener(sessionResponse -> {59 try {60 this.setErrorResponse(sessionResponse);61 } catch (Exception ignore) {62 // Ignore any exception. Do not want to block the eventbus thread.63 }64 }));65 }66 private void setResponse(NewSessionResponse sessionResponse) {67 // Each thread will get its own CountDownLatch and it is stored in the Map using request id as the key.68 // EventBus thread will retrieve the same request and set it's response and unblock waiting request thread.69 RequestId id = sessionResponse.getRequestId();70 Optional<NewSessionRequest> sessionRequest = Optional.ofNullable(knownRequests.get(id));71 if (sessionRequest.isPresent()) {72 NewSessionRequest request = sessionRequest.get();73 request.setSessionResponse(74 new HttpResponse().setContent(bytes(sessionResponse.getDownstreamEncodedResponse())));75 request.getLatch().countDown();76 }77 }78 private void setErrorResponse(NewSessionErrorResponse sessionResponse) {79 RequestId id = sessionResponse.getRequestId();80 Optional<NewSessionRequest> sessionRequest = Optional.ofNullable(knownRequests.get(id));81 // There could be a situation where the session request in the queue is scheduled for retry.82 // Meanwhile the request queue is cleared.83 // This will fire a error response event and remove the request id from the knownRequests map.84 // Another error response event will be fired by the Distributor when the request is retried.85 // Since a response is already provided for the request, the event listener should not take any action.86 if (sessionRequest.isPresent()) {87 NewSessionRequest request = sessionRequest.get();88 request89 .setSessionResponse(new HttpResponse()90 .setStatus(HTTP_INTERNAL_ERROR)91 .setContent(asJson(92 ImmutableMap.of("message", sessionResponse.getMessage()))));93 request.getLatch().countDown();94 }95 }96 public HttpResponse add(HttpRequest request) {97 Require.nonNull("New Session request", request);98 CountDownLatch latch = new CountDownLatch(1);99 UUID uuid = UUID.randomUUID();...
Source:NewSessionRejectedEvent.java
...24 private static final EventName NEW_SESSION_REJECTED = new EventName("new-session-rejected");25 public NewSessionRejectedEvent(NewSessionErrorResponse response) {26 super(NEW_SESSION_REJECTED, response);27 }28 public static EventListener<NewSessionErrorResponse> listener(Consumer<NewSessionErrorResponse> handler) {29 Require.nonNull("Handler", handler);30 return new EventListener<>(NEW_SESSION_REJECTED, NewSessionErrorResponse.class, handler);31 }32}...
listener
Using AI Code Generation
1package org.openqa.selenium.grid.distributor.local;2import org.openqa.selenium.events.Event;3import org.openqa.selenium.events.EventListener;4import org.openqa.selenium.grid.data.NewSessionRejectedEvent;5public class NewSessionRejectedEventListener implements EventListener {6 public void onEvent(Event event) {7 if (event instanceof NewSessionRejectedEvent) {8 NewSessionRejectedEvent newSessionRejectedEvent = (NewSessionRejectedEvent) event;9 System.out.println("New session rejected by " + newSessionRejectedEvent.getNodeId());10 }11 }12}
listener
Using AI Code Generation
1import org.openqa.selenium.grid.data.NewSessionRejectedEvent;2import org.openqa.selenium.remote.http.HttpClient;3import org.openqa.selenium.remote.http.HttpRequest;4import org.openqa.selenium.remote.http.HttpResponse;5import java.net.URI;6import java.util.concurrent.CompletableFuture;7import java.util.function.Consumer;8public class CustomListener implements Consumer<NewSessionRejectedEvent> {9 public void accept(NewSessionRejectedEvent newSessionRejectedEvent) {10 HttpRequest request = new HttpRequest("GET", "/wd/hub/status");11 CompletableFuture<HttpResponse> response = client.execute(request);12 System.out.println("Status code is " + response.get().getStatusCode());13 }14}15import org.openqa.selenium.grid.config.Config;16import org.openqa.selenium.grid.config.MemoizedConfig;17import org.openqa.selenium.grid.distributor.Distributor;18import org.openqa.selenium.grid.distributor.DistributorFactory;19import org.openqa.selenium.grid.distributor.local.LocalDistributor;20import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;21import org.openqa.selenium.grid.sessionqueue.config.SessionQueueOptions;22import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;23import org.openqa.selenium.grid.web.Routable;24import org.openqa.selenium.grid.web.Routes;25import org.openqa.selenium.remote.http.Filter;26import org.openqa.selenium.remote.http.HttpHandler;27import org.openqa.selenium.remote.tracing.Tracer;28import java.util.Objects;29import java.util.function.Supplier;30public class CustomDistributorFactory implements DistributorFactory {31 public boolean applies(Config config) {32 return Objects.equals("custom", config.get("distributor").orElse(null));33 }34 public Distributor createDistributor(Tracer tracer, Config config, HttpHandler client) {35 Config sessionQueueConfig = new MemoizedConfig(config);36 SessionQueueOptions sessionQueueOptions = new SessionQueueOptions(sessionQueueConfig);37 NewSessionQueue queue = new LocalNewSessionQueue(tracer, sessionQueueOptions, client);38 Supplier<Routable> supplier = () -> new Routes().add(new CustomListener());39 return new CustomDistributor(tracer, queue, supplier);40 }41 private static class CustomDistributor extends LocalDistributor {42 private final Supplier<Routable> supplier;43 CustomDistributor(Tracer tracer, NewSessionQueue queue, Supplier<Routable> supplier) {
listener
Using AI Code Generation
1import org.openqa.selenium.grid.data.NewSessionRejectedEvent;2import org.openqa.selenium.grid.data.NewSessionRejectedEvent.Listener;3import org.openqa.selenium.json.Json;4import org.openqa.selenium.remote.http.HttpClient;5import org.openqa.selenium.remote.http.HttpRequest;6import org.openqa.selenium.remote.http.HttpResponse;7import org.openqa.selenium.remote.http.WebSocket;8import org.openqa.selenium.remote.tracing.Tracer;9import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;10import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerOptions;11import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerOptions.Builder;12import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerOptions.Endpoint;13import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerOptions.SpanExporterFactory;14import java.net.URI;15import java.time.Duration;16import java.util.concurrent.TimeUnit;17import java.util.function.Consumer;18import java.util.function.Supplier;19import io.opentelemetry.exporters.logging.LoggingSpanExporter;20import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;21public class NewSessionRejectedEventExample {22 public static void main(String[] args) {23 Builder builder = OpenTelemetryTracerOptions.builder();24 builder.setSpanExporterFactory(SpanExporterFactory.create(25 () -> SimpleSpanProcessor.newBuilder(26 LoggingSpanExporter.create())27 .build()));28 OpenTelemetryTracerOptions options = builder.build();29 Tracer tracer = new OpenTelemetryTracer(options);30 HttpRequest request = new HttpRequest("GET", "/se/grid/console/events");31 Consumer<HttpResponse> responseHandler = response -> {32 if (response.getStatus() != 101) {33 return;34 }35 response.getContent().ifPresent(content -> {36 WebSocket ws = WebSocket.createClientSocket(37 new Supplier<HttpClient>() {38 public HttpClient get() {39 return client;40 }41 },42 Duration.of(5, TimeUnit.SECONDS));43 ws.addListener(new Listener() {44 public void onNewSessionRejectedEvent(NewSessionRejectedEvent event) {45 System.out.println(event);46 }47 });48 ws.connect();49 });50 };51 client.execute(request, responseHandler);
listener
Using AI Code Generation
1public class ListenerMethod {2 public static void main(String[] args) {3 EventBus bus = new EventBus();4 bus.register(new ListenerMethod());5 bus.post(new NewSessionRejectedEvent("session id", "reason"));6 }7 public void handleNewSessionRejectedEvent(NewSessionRejectedEvent event) {8 System.out.println("NewSessionRejectedEvent");9 }10}11import org.openqa.selenium.grid.data.NewSessionQueuedEvent;12import org.openqa.selenium.remote.tracing.EventBus;13import org.openqa.selenium.remote.tracing.EventBus.Listener;14public class ListenerMethod {15 public static void main(String[] args) {16 EventBus bus = new EventBus();17 bus.register(new ListenerMethod());18 bus.post(new NewSessionQueuedEvent("session id", "reason"));19 }20 public void handleNewSessionQueuedEvent(NewSessionQueuedEvent event) {21 System.out.println("NewSessionQueuedEvent");22 }23}24import org.openqa.selenium.grid.data.NewSessionEvent;25import org.openqa.selenium.remote.tracing.EventBus;26import org.openqa.selenium.remote.tracing.EventBus.Listener;27public class ListenerMethod {28 public static void main(String[] args) {29 EventBus bus = new EventBus();30 bus.register(new ListenerMethod());31 bus.post(new NewSessionEvent("session id", "reason"));32 }33 public void handleNewSessionEvent(NewSessionEvent event) {34 System.out.println("NewSessionEvent");35 }36}37import org.openqa.selenium.grid.data.SessionClosedEvent;38import org.openqa.selenium.remote.tracing.EventBus;39import org.openqa.selenium.remote.tracing.EventBus.Listener;40public class ListenerMethod {41 public static void main(String[] args) {42 EventBus bus = new EventBus();43 bus.register(new ListenerMethod());44 bus.post(new SessionClosedEvent("session id", "reason"));45 }46 public void handleSessionClosedEvent(SessionClosedEvent event) {47 System.out.println("SessionClosedEvent
listener
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.chrome.ChromeDriver;3import org.openqa.selenium.chrome.ChromeOptions;4import org.openqa.selenium.devtools.DevTools;5import org.openqa.selenium.devtools.v91.log.Log;6import org.openqa.selenium.devtools.v91.log.model.LogEntry;7import org.openqa.selenium.devtools.v91.network.Network;8import org.openqa.selenium.devtools.v91.network.model.ConnectionType;9import org.openqa.selenium.devtools.v91.network.model.Request;10import org.openqa.selenium.devtools.v91.network.model.ResourceType;11import org.openqa.selenium.devtools.v91.network.model.Response;12import org.openqa.selenium.devtools.v91.page.Page;13import org.openqa.selenium.devtools.v91.page.model.FrameId;14import org.openqa.selenium.grid.data.NewSessionRejectedEvent;15import org.openqa.selenium.grid.distributor.local.LocalDistributor;16import org.openqa.selenium.grid.node.local.LocalNode;17import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;18import org.openqa.selenium.grid.web.Values;19import org.openqa.selenium.net.PortProber;20import org.openqa.selenium.remote.http.HttpClient;21import org.openqa.selenium.remote.http.HttpMethod;22import org.openqa.selenium.remote.http.HttpRequest;23import org.openqa.selenium.remote.http.HttpResponse;24import org.openqa.selenium.remote.tracing.GlobalDistributorTracer;25import org.openqa.selenium.remote.tracing.GlobalNodeTracer;26import org.openqa.selenium.remote.tracing.Tracer;27import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;28import org.openqa.selenium.support.ui.ExpectedConditions;29import org.openqa.selenium.support.ui.WebDriverWait;30import java.net.URI;31import java.net.URISyntaxException;32import java.time.Duration;33import java.util.Map;34import java.util.concurrent.atomic.AtomicReference;35import java.util.function.Consumer;36public class DevToolsExample {37 private static final Tracer TRACER = OpenTelemetryTracer.create();38 public static void main(String[] args) throws URISyntaxException {39 GlobalDistributorTracer.setInstance(TRACER);40 GlobalNodeTracer.setInstance(TRACER);41 LocalDistributor distributor = LocalDistributor.builder()42 .add(new SessionMapOptions(Values.create()))43 .build();44 LocalNode.Builder builder = LocalNode.builder(distributor.getUri())45 .add(new Session
listener
Using AI Code Generation
1import org.openqa.selenium.grid.data.NewSessionRejectedEvent;2import org.openqa.selenium.grid.data.SessionRequest;3import org.openqa.selenium.grid.events.Event;4import org.openqa.selenium.grid.events.EventBus;5import org.openqa.selenium.grid.events.EventBusOptions;6import org.openqa.selenium.grid.events.EventListener;7import org.openqa.selenium.grid.events.EventName;8import org.openqa.selenium.remote.http.HttpClient;9import org.openqa.selenium.remote.http.HttpRequest;10import org.openqa.selenium.remote.http.HttpResponse;11import org.openqa.selenium.remote.http.HttpVerb;12import org.openqa.selenium.remote.tracing.DefaultTestTracer;13import org.openqa.selenium.remote.tracing.Tracer;14import org.testng.Assert;15import org.testng.annotations.Test;16import java.io.File;17import java.io.FileWriter;18import java.io.IOException;19import java.nio.charset.StandardCharsets;20import java.nio.file.Files;21import java.nio.file.Path;22import java.nio.file.Paths;23import java.util.concurrent.TimeUnit;24public class GridListener {25 public void testGrid() throws IOException, InterruptedException {26 Tracer tracer = DefaultTestTracer.createTracer();27 EventBus bus = new EventBus(new EventBusOptions(tracer));28 bus.addListener(new EventListener() {29 public void onEvent(Event event) {30 if (event instanceof NewSessionRejectedEvent) {31 NewSessionRejectedEvent newSessionRejectedEvent = (NewSessionRejectedEvent) event;32 SessionRequest sessionRequest = newSessionRejectedEvent.getSessionRequest();33 String message = newSessionRejectedEvent.getMessage();34 File file = new File("C:\\Users\\Dell\\Desktop\\file.txt");35 try {36 FileWriter fileWriter = new FileWriter(file);37 fileWriter.write(message);38 fileWriter.close();39 } catch (IOException e) {40 e.printStackTrace();41 }42 }43 }44 });45 HttpClient client = HttpClient.Factory.createDefault().createClient(bus.getBaseUri());46 HttpRequest request = new HttpRequest(HttpVerb.POST, "/session");47 request.setContent("{\"desiredCapabilities\": {\"browserName\": \"chrome\"}}".getBytes(StandardCharsets.UTF_8));48 HttpResponse response = client.execute(request
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!!