How to use NewSessionRequestEvent class of org.openqa.selenium.grid.data package

Best Selenium code snippet using org.openqa.selenium.grid.data.NewSessionRequestEvent

Source:LocalNewSessionQueueTest.java Github

copy

Full Screen

...29import org.openqa.selenium.events.local.GuavaEventBus;30import org.openqa.selenium.grid.data.CreateSessionResponse;31import org.openqa.selenium.grid.data.DefaultSlotMatcher;32import org.openqa.selenium.grid.data.NewSessionRejectedEvent;33import org.openqa.selenium.grid.data.NewSessionRequestEvent;34import org.openqa.selenium.grid.data.RequestId;35import org.openqa.selenium.grid.data.Session;36import org.openqa.selenium.grid.data.SessionRequestCapability;37import org.openqa.selenium.grid.security.Secret;38import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;39import org.openqa.selenium.grid.data.SessionRequest;40import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;41import org.openqa.selenium.grid.testing.PassthroughHttpClient;42import org.openqa.selenium.internal.Debug;43import org.openqa.selenium.internal.Either;44import org.openqa.selenium.json.Json;45import org.openqa.selenium.remote.SessionId;46import org.openqa.selenium.remote.http.Contents;47import org.openqa.selenium.remote.http.HttpClient;48import org.openqa.selenium.remote.http.HttpResponse;49import org.openqa.selenium.remote.tracing.DefaultTestTracer;50import org.openqa.selenium.remote.tracing.Tracer;51import java.net.URI;52import java.net.URISyntaxException;53import java.time.Duration;54import java.time.Instant;55import java.util.Collection;56import java.util.LinkedHashSet;57import java.util.List;58import java.util.Map;59import java.util.Optional;60import java.util.Set;61import java.util.UUID;62import java.util.concurrent.Callable;63import java.util.concurrent.CountDownLatch;64import java.util.concurrent.ExecutionException;65import java.util.concurrent.ExecutorService;66import java.util.concurrent.Executors;67import java.util.concurrent.Future;68import java.util.concurrent.TimeoutException;69import java.util.concurrent.atomic.AtomicBoolean;70import java.util.concurrent.atomic.AtomicInteger;71import java.util.concurrent.atomic.AtomicReference;72import java.util.function.Supplier;73import java.util.stream.Collectors;74import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;75import static java.net.HttpURLConnection.HTTP_OK;76import static java.nio.charset.StandardCharsets.UTF_8;77import static java.util.concurrent.TimeUnit.SECONDS;78import static org.assertj.core.api.Assertions.assertThat;79import static org.assertj.core.api.Assertions.fail;80import static org.junit.Assert.assertEquals;81import static org.junit.Assert.assertFalse;82import static org.junit.Assert.assertNotEquals;83import static org.junit.Assert.assertTrue;84import static org.openqa.selenium.remote.Dialect.W3C;85import static org.openqa.selenium.testing.Safely.safelyCall;86@RunWith(Parameterized.class)87public class LocalNewSessionQueueTest {88 @ClassRule89 public static Timeout classTimeout = new Timeout(60, SECONDS);90 private static final Json JSON = new Json();91 private static final Capabilities CAPS = new ImmutableCapabilities("browserName", "cheese");92 private static final Secret REGISTRATION_SECRET = new Secret("secret");93 private static final Instant LONG_AGO = Instant.parse("2007-01-03T21:49:10.00Z"); // Go check the git log94 private final NewSessionQueue queue;95 private final LocalNewSessionQueue localQueue;96 private final EventBus bus;97 private final SessionRequest sessionRequest;98 static class TestData {99 public final EventBus bus;100 public final LocalNewSessionQueue localQueue;101 public final NewSessionQueue queue;102 public TestData(EventBus bus, LocalNewSessionQueue localQueue, NewSessionQueue queue) {103 this.bus = bus;104 this.localQueue = localQueue;105 this.queue = queue;106 }107 }108 public LocalNewSessionQueueTest(Supplier<TestData> supplier) {109 TestData testData = supplier.get();110 this.bus = testData.bus;111 this.queue = testData.queue;112 this.localQueue = testData.localQueue;113 this.sessionRequest = new SessionRequest(114 new RequestId(UUID.randomUUID()),115 Instant.now(),116 Set.of(W3C),117 Set.of(CAPS),118 Map.of(),119 Map.of());120 }121 @Parameterized.Parameters122 public static Collection<Supplier<TestData>> createQueues() {123 Tracer tracer = DefaultTestTracer.createTracer();124 Set<Supplier<TestData>> toReturn = new LinkedHashSet<>();125 // Note: this method is called only once, so if we want each test to126 // be isolated, everything that they use has to be created via the127 // supplier. In particular, a shared event bus will cause weird128 // failures to happen.129 toReturn.add(() -> {130 EventBus bus = new GuavaEventBus();131 LocalNewSessionQueue local = new LocalNewSessionQueue(132 tracer,133 bus,134 new DefaultSlotMatcher(),135 Duration.ofSeconds(1),136 Duration.ofSeconds(Debug.isDebugging() ? 9999 : 5),137 REGISTRATION_SECRET);138 return new TestData(bus, local, local);139 });140 toReturn.add(() -> {141 EventBus bus = new GuavaEventBus();142 LocalNewSessionQueue local = new LocalNewSessionQueue(143 tracer,144 bus,145 new DefaultSlotMatcher(),146 Duration.ofSeconds(1),147 Duration.ofSeconds(Debug.isDebugging() ? 9999 : 5),148 REGISTRATION_SECRET);149 HttpClient client = new PassthroughHttpClient(local);150 return new TestData(bus, local, new RemoteNewSessionQueue(tracer, client, REGISTRATION_SECRET));151 });152 return toReturn;153 }154 @After155 public void shutdownQueue() {156 safelyCall(localQueue::close);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(...

Full Screen

Full Screen

Source:NewSessionQueuerTest.java Github

copy

Full Screen

...24import org.openqa.selenium.events.local.GuavaEventBus;25import org.openqa.selenium.grid.data.CreateSessionResponse;26import org.openqa.selenium.grid.data.NewSessionErrorResponse;27import org.openqa.selenium.grid.data.NewSessionRejectedEvent;28import org.openqa.selenium.grid.data.NewSessionRequestEvent;29import org.openqa.selenium.grid.data.NewSessionResponse;30import org.openqa.selenium.grid.data.NewSessionResponseEvent;31import org.openqa.selenium.grid.data.RequestId;32import org.openqa.selenium.grid.data.Session;33import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;34import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueuer;35import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueuer;36import org.openqa.selenium.grid.testing.PassthroughHttpClient;37import org.openqa.selenium.json.Json;38import org.openqa.selenium.remote.NewSessionPayload;39import org.openqa.selenium.remote.SessionId;40import org.openqa.selenium.remote.http.Contents;41import org.openqa.selenium.remote.http.HttpClient;42import org.openqa.selenium.remote.http.HttpMethod;43import org.openqa.selenium.remote.http.HttpRequest;44import org.openqa.selenium.remote.http.HttpResponse;45import org.openqa.selenium.remote.tracing.DefaultTestTracer;46import org.openqa.selenium.remote.tracing.Tracer;47import java.io.IOException;48import java.io.UncheckedIOException;49import java.net.URI;50import java.net.URISyntaxException;51import java.time.Duration;52import java.time.Instant;53import java.util.Optional;54import java.util.UUID;55import java.util.concurrent.Callable;56import java.util.concurrent.ExecutionException;57import java.util.concurrent.ExecutorService;58import java.util.concurrent.Executors;59import java.util.concurrent.Future;60import java.util.concurrent.TimeUnit;61import java.util.concurrent.TimeoutException;62import java.util.concurrent.atomic.AtomicBoolean;63import java.util.concurrent.atomic.AtomicInteger;64import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;65import static java.net.HttpURLConnection.HTTP_OK;66import static java.nio.charset.StandardCharsets.UTF_8;67import static org.assertj.core.api.Assertions.assertThat;68import static org.assertj.core.api.Assertions.fail;69import static org.junit.Assert.assertEquals;70import static org.junit.Assert.assertFalse;71import static org.junit.Assert.assertNotEquals;72import static org.junit.Assert.assertTrue;73import static org.openqa.selenium.grid.sessionqueue.NewSessionQueue.SESSIONREQUEST_TIMESTAMP_HEADER;74import static org.openqa.selenium.remote.http.Contents.utf8String;75import static org.openqa.selenium.remote.http.HttpMethod.POST;76public class NewSessionQueuerTest {77 private LocalNewSessionQueuer local;78 private RemoteNewSessionQueuer remote;79 private EventBus bus;80 private ImmutableCapabilities caps;81 private NewSessionPayload payload;82 private HttpRequest request;83 private static int count = 0;84 private static final Json JSON = new Json();85 private NewSessionQueue sessionQueue;86 @Before87 public void setUp() {88 Tracer tracer = DefaultTestTracer.createTracer();89 caps = new ImmutableCapabilities("browserName", "chrome");90 bus = new GuavaEventBus();91 sessionQueue = new LocalNewSessionQueue(92 tracer,93 bus,94 Duration.ofSeconds(1),95 Duration.ofSeconds(1000));96 local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);97 HttpClient client = new PassthroughHttpClient(local);98 remote = new RemoteNewSessionQueuer(tracer, client);99 payload = NewSessionPayload.create(caps);100 request = createRequest(payload, POST, "/session");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);...

Full Screen

Full Screen

Source:LocalDistributor.java Github

copy

Full Screen

...29import org.openqa.selenium.grid.data.CreateSessionResponse;30import org.openqa.selenium.grid.data.DistributorStatus;31import org.openqa.selenium.grid.data.NewSessionErrorResponse;32import org.openqa.selenium.grid.data.NewSessionRejectedEvent;33import org.openqa.selenium.grid.data.NewSessionRequestEvent;34import org.openqa.selenium.grid.data.NewSessionResponse;35import org.openqa.selenium.grid.data.NewSessionResponseEvent;36import org.openqa.selenium.grid.data.NodeAddedEvent;37import org.openqa.selenium.grid.data.NodeDrainComplete;38import org.openqa.selenium.grid.data.NodeHeartBeatEvent;39import org.openqa.selenium.grid.data.NodeId;40import org.openqa.selenium.grid.data.NodeStatus;41import org.openqa.selenium.grid.data.NodeStatusEvent;42import org.openqa.selenium.grid.data.RequestId;43import org.openqa.selenium.grid.data.Slot;44import org.openqa.selenium.grid.data.SlotId;45import org.openqa.selenium.grid.distributor.Distributor;46import org.openqa.selenium.grid.distributor.config.DistributorOptions;47import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;48import org.openqa.selenium.grid.log.LoggingOptions;49import org.openqa.selenium.grid.node.HealthCheck;50import org.openqa.selenium.grid.node.Node;51import org.openqa.selenium.grid.node.remote.RemoteNode;52import org.openqa.selenium.grid.security.Secret;53import org.openqa.selenium.grid.security.SecretOptions;54import org.openqa.selenium.grid.server.EventBusOptions;55import org.openqa.selenium.grid.server.NetworkOptions;56import org.openqa.selenium.grid.sessionmap.SessionMap;57import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;58import org.openqa.selenium.grid.sessionqueue.NewSessionQueuer;59import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueuerOptions;60import org.openqa.selenium.internal.Either;61import org.openqa.selenium.internal.Require;62import org.openqa.selenium.remote.http.HttpClient;63import org.openqa.selenium.remote.http.HttpRequest;64import org.openqa.selenium.remote.tracing.AttributeKey;65import org.openqa.selenium.remote.tracing.EventAttribute;66import org.openqa.selenium.remote.tracing.EventAttributeValue;67import org.openqa.selenium.remote.tracing.Span;68import org.openqa.selenium.remote.tracing.Tracer;69import org.openqa.selenium.status.HasReadyState;70import java.time.Duration;71import java.util.ArrayList;72import java.util.HashMap;73import java.util.List;74import java.util.Map;75import java.util.Optional;76import java.util.Queue;77import java.util.Set;78import java.util.concurrent.ConcurrentHashMap;79import java.util.concurrent.ConcurrentLinkedQueue;80import java.util.concurrent.Executors;81import java.util.concurrent.ScheduledExecutorService;82import java.util.concurrent.ThreadFactory;83import java.util.concurrent.TimeUnit;84import java.util.concurrent.locks.Lock;85import java.util.concurrent.locks.ReadWriteLock;86import java.util.concurrent.locks.ReentrantReadWriteLock;87import java.util.logging.Level;88import java.util.logging.Logger;89import static com.google.common.collect.ImmutableSet.toImmutableSet;90import static org.openqa.selenium.grid.data.Availability.DOWN;91import static org.openqa.selenium.grid.data.Availability.DRAINING;92import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;93public class LocalDistributor extends Distributor {94 private static final Logger LOG = Logger.getLogger(LocalDistributor.class.getName());95 private final Tracer tracer;96 private final EventBus bus;97 private final HttpClient.Factory clientFactory;98 private final SessionMap sessions;99 private final Secret registrationSecret;100 private final Regularly hostChecker = new Regularly("distributor host checker");101 private final Map<NodeId, Runnable> allChecks = new HashMap<>();102 private final Queue<RequestId> requestIds = new ConcurrentLinkedQueue<>();103 private final ScheduledExecutorService executorService;104 private final Duration healthcheckInterval;105 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);106 private final GridModel model;107 private final Map<NodeId, Node> nodes;108 private final NewSessionQueuer sessionRequests;109 public LocalDistributor(110 Tracer tracer,111 EventBus bus,112 HttpClient.Factory clientFactory,113 SessionMap sessions,114 NewSessionQueuer sessionRequests,115 Secret registrationSecret,116 Duration healthcheckInterval) {117 super(tracer, clientFactory, new DefaultSlotSelector(), sessions, registrationSecret);118 this.tracer = Require.nonNull("Tracer", tracer);119 this.bus = Require.nonNull("Event bus", bus);120 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);121 this.sessions = Require.nonNull("Session map", sessions);122 this.model = new GridModel(bus);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 }...

Full Screen

Full Screen

Source:LocalNewSessionQueue.java Github

copy

Full Screen

...6import org.openqa.selenium.grid.config.Config;7import org.openqa.selenium.grid.data.CreateSessionResponse;8import org.openqa.selenium.grid.data.NewSessionErrorResponse;9import org.openqa.selenium.grid.data.NewSessionRejectedEvent;10import org.openqa.selenium.grid.data.NewSessionRequestEvent;11import org.openqa.selenium.grid.data.RequestId;12import org.openqa.selenium.grid.data.SessionRequest;13import org.openqa.selenium.grid.data.SessionRequestCapability;14import org.openqa.selenium.grid.data.TraceSessionRequest;15import org.openqa.selenium.grid.data.SlotMatcher;16import org.openqa.selenium.grid.distributor.config.DistributorOptions;17import org.openqa.selenium.grid.jmx.JMXHelper;18import org.openqa.selenium.grid.jmx.ManagedAttribute;19import org.openqa.selenium.grid.jmx.ManagedService;20import org.openqa.selenium.grid.log.LoggingOptions;21import org.openqa.selenium.grid.security.Secret;22import org.openqa.selenium.grid.security.SecretOptions;23import org.openqa.selenium.grid.server.EventBusOptions;24import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;25import org.openqa.selenium.grid.sessionqueue.config.SessionRequestOptions;26import org.openqa.selenium.internal.Either;27import org.openqa.selenium.internal.Require;28import org.openqa.selenium.remote.http.Contents;29import org.openqa.selenium.remote.http.HttpResponse;30import org.openqa.selenium.remote.tracing.Span;31import org.openqa.selenium.remote.tracing.TraceContext;32import org.openqa.selenium.remote.tracing.Tracer;33import java.io.Closeable;34import java.io.IOException;35import java.time.Duration;36import java.time.Instant;37import java.util.Collections;38import java.util.Deque;39import java.util.Iterator;40import java.util.List;41import java.util.Map;42import java.util.Optional;43import java.util.Set;44import java.util.concurrent.ConcurrentHashMap;45import java.util.concurrent.ConcurrentLinkedDeque;46import java.util.concurrent.CountDownLatch;47import java.util.concurrent.Executors;48import java.util.concurrent.ScheduledExecutorService;49import java.util.concurrent.locks.Lock;50import java.util.concurrent.locks.ReadWriteLock;51import java.util.concurrent.locks.ReentrantReadWriteLock;52import java.util.function.Predicate;53import java.util.stream.Collectors;54import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;55import static java.util.concurrent.TimeUnit.MILLISECONDS;56/**57 * An in-memory implementation of the list of new session requests.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())) {...

Full Screen

Full Screen

Source:NewSessionRequestEvent.java Github

copy

Full Screen

...19import org.openqa.selenium.events.EventListener;20import org.openqa.selenium.events.EventName;21import org.openqa.selenium.internal.Require;22import java.util.function.Consumer;23public class NewSessionRequestEvent extends Event {24 private static final EventName NEW_SESSION_REQUEST = new EventName("new-session-request");25 public NewSessionRequestEvent(RequestId requestId) {26 super(NEW_SESSION_REQUEST, requestId);27 }28 public static EventListener<RequestId> listener(Consumer<RequestId> handler) {29 Require.nonNull("Handler", handler);30 return new EventListener<>(NEW_SESSION_REQUEST, RequestId.class, handler);31 }32}...

Full Screen

Full Screen

NewSessionRequestEvent

Using AI Code Generation

copy

Full Screen

1public class NewSessionRequestEvent implements Event {2 private final NewSessionRequest request;3 private final SessionId sessionId;4 public NewSessionRequestEvent(NewSessionRequest request, SessionId sessionId) {5 this.request = requireNonNull(request);6 this.sessionId = requireNonNull(sessionId);7 }8 public NewSessionRequest getRequest() {9 return request;10 }11 public SessionId getSessionId() {12 return sessionId;13 }14 public String toString() {15 return String.format("New session request %s for %s", sessionId, request);16 }17}18public class NewSessionQueuedEvent implements Event {19 private final NewSessionRequest request;20 private final SessionId sessionId;21 public NewSessionQueuedEvent(NewSessionRequest request, SessionId sessionId) {22 this.request = requireNonNull(request);23 this.sessionId = requireNonNull(sessionId);24 }25 public NewSessionRequest getRequest() {26 return request;27 }28 public SessionId getSessionId() {29 return sessionId;30 }31 public String toString() {32 return String.format("New session request %s for %s queued", sessionId, request);33 }34}

Full Screen

Full Screen

NewSessionRequestEvent

Using AI Code Generation

copy

Full Screen

1package org.openqa.selenium.grid.data;2import org.openqa.selenium.json.JsonInput;3import java.util.Objects;4import java.util.UUID;5public class NewSessionRequestEvent {6 private final UUID id;7 private final NewSessionRequest request;8 public NewSessionRequestEvent(UUID id, NewSessionRequest request) {9 this.id = Objects.requireNonNull(id, "Event id must be set.");10 this.request = Objects.requireNonNull(request, "Request must be set.");11 }12 public UUID getId() {13 return id;14 }15 public NewSessionRequest getRequest() {16 return request;17 }18 public static NewSessionRequestEvent fromJson(JsonInput input) {19 return new NewSessionRequestEvent(20 UUID.fromString(input.nextString()),21 NewSessionRequest.fromJson(input));22 }23}24package org.openqa.selenium.grid.data;25import org.openqa.selenium.json.JsonInput;26import java.util.Objects;27import java.util.UUID;28public class NewSessionRequestEvent {29 private final UUID id;30 private final NewSessionRequest request;31 public NewSessionRequestEvent(UUID id, NewSessionRequest request) {32 this.id = Objects.requireNonNull(id, "Event id must be set.");33 this.request = Objects.requireNonNull(request, "Request must be set.");34 }35 public UUID getId() {36 return id;37 }38 public NewSessionRequest getRequest() {39 return request;40 }41 public static NewSessionRequestEvent fromJson(JsonInput input) {42 return new NewSessionRequestEvent(43 UUID.fromString(input.nextString()),44 NewSessionRequest.fromJson(input));45 }46}47package org.openqa.selenium.grid.data;48import org.openqa.selenium.json.JsonInput;49import java.util.Objects;50import java.util.UUID;51public class NewSessionRequestEvent {52 private final UUID id;53 private final NewSessionRequest request;54 public NewSessionRequestEvent(UUID id, NewSessionRequest request) {55 this.id = Objects.requireNonNull(id, "Event id must be set.");56 this.request = Objects.requireNonNull(request, "Request must be set.");57 }58 public UUID getId() {59 return id;60 }61 public NewSessionRequest getRequest() {62 return request;63 }64 public static NewSessionRequestEvent fromJson(JsonInput input) {65 return new NewSessionRequestEvent(66 UUID.fromString(input.nextString()),

Full Screen

Full Screen

NewSessionRequestEvent

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.NewSessionRequestEvent;2import org.openqa.selenium.grid.data.NewSessionRequestEvent.NewSessionRequestEventCodec;3import org.openqa.selenium.grid.data.NewSessionQueuedEvent;4import org.openqa.selenium.grid.data.NewSessionQueuedEvent.NewSessionQueuedEventCodec;5import org.openqa.selenium.grid.data.NewSessionRejectedEvent;6import org.openqa.selenium.grid.data.NewSessionRejectedEvent.NewSessionRejectedEventCodec;7import org.openqa.selenium.grid.data.NewSessionStartedEvent;8import org.openqa.selenium.grid.data.NewSessionStartedEvent.NewSessionStartedEventCodec;9import org.openqa.selenium.grid.data.SessionClosedEvent;10import org.openqa.selenium.grid.data.SessionClosedEvent.SessionClosedEventCodec;11import org.openqa.selenium.grid.data.SessionCreatedEvent;12import org.openqa.selenium.grid.data.SessionCreatedEvent.SessionCreatedEventCodec;13import org.openqa.selenium.grid.data.SessionEvent;14import org.openqa.selenium.grid.data.SessionEvent.SessionEventCodec;15import org.openqa.selenium.grid.data.SessionInfo;16import org.openqa.selenium.grid.data.SessionRequest;17import org.openqa.selenium.grid.data.SessionRequest.SessionRequestCodec;18import org.openqa.selenium.grid.data.SessionRequest.SessionRequestType;19import org.openqa.selenium.grid.data.SessionRequestEvent;20import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestEventCodec;21import org.openqa.selenium.grid.data.SessionRequestRejectedEvent;22import org.openqa.selenium.grid.data.SessionRequestRejectedEvent.SessionRequestRejectedEventCodec;23import org.openqa.selenium.grid.data.SessionRequestTimedOutEvent;24import org.openqa.selenium.grid.data.SessionRequestTimedOutEvent.SessionRequestTimedOutEventCodec;25import org.openqa.selenium.grid.data.SessionRequestUpdatedEvent;26import org.openqa.selenium.grid.data.SessionRequestUpdatedEvent.SessionRequestUpdatedEventCodec;27import org.openqa.selenium.grid.data.SessionStartedEvent;28import org.openqa.selenium.grid.data.SessionStartedEvent.SessionStartedEventCodec;29import org.openqa.selenium.grid.data.SessionTerminatedEvent;30import org.openqa.selenium.grid.data.SessionTerminatedEvent.SessionTerminatedEventCodec;31import org.openqa.selenium.grid.data.Slot;32import org.openqa.selenium.grid.data.Slot.SlotCodec;33import org.openqa.selenium.grid.data.SlotId;34import org.openqa.selenium.grid.data.SlotId.SlotIdCodec;35import org.openqa.selenium.grid.data.SlotState;36import org.openqa.selenium.grid.data.SlotState.SlotStateCodec;37import org.openqa.selenium.grid.data.SlotUpdatedEvent;38import org.openqa.selenium.grid.data.SlotUpdatedEvent.SlotUpdatedEventCodec;39import org.openqa.selenium.grid.data.Stoppable;40import org.openqa.selenium.grid.data.Stoppable.St

Full Screen

Full Screen

NewSessionRequestEvent

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.NewSessionRequestEvent;2import org.openqa.selenium.grid.data.NewSessionResponseEvent;3import org.openqa.selenium.grid.data.SessionRequest;4import org.openqa.selenium.grid.data.SessionResponse;5import org.openqa.selenium.grid.distributor.local.LocalDistributor;6import org.openqa.selenium.grid.distributor.local.RemoteProxy;7import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;8import org.openqa.selenium.grid.sessionqueue.config.SessionQueueOptions;9import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;10import org.openqa.selenium.grid.web.Values;11import org.openqa.selenium.internal.Require;12import org.openqa.selenium.remote.http.HttpHandler;13import org.openqa.selenium.remote.http.HttpRequest;14import org.openqa.selenium.remote.http.HttpResponse;15import org.openqa.selenium.remote.tracing.Tracer;16import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;17import java.net.URI;18import java.util.ArrayList;19import java.util.Collections;20import java.util.List;21import java.util.Objects;22import java.util.Optional;23import java.util.UUID;24import java.util.logging.Logger;25import java.util.stream.Collectors;26import static java.util.logging.Level.INFO;27import static org.openqa.selenium.grid.data.NewSessionRejectedEvent.newSessionRejected;28import static org.openqa.selenium.grid.data.NewSessionRequestEvent.newSessionRequest;29import static org.openqa.selenium.grid.data.NewSessionResponseEvent.newSessionResponse;30import static org.openqa.selenium.remote.http.Contents.asJson;31import static org.openqa.selenium.remote.http.Contents.utf8String;32import static org.openqa.selenium.remote.http.HttpMethod.GET;33import static org.openqa.selenium.remote.http.HttpMethod.POST;34import static org.openqa.selenium.remote.http.Route.combine;35import static org.openqa.selenium.remote.http.Route.get;36import static org.openqa.selenium.remote.http.Route.matching;37import static org.openqa.selenium.remote.http.Route.post;38public class Distributor implements HttpHandler {39 private static final Logger LOG = Logger.getLogger(Distributor.class.getName());40 private final Tracer tracer;41 private final NewSessionQueue queue;42 private final LocalDistributor distributor;43 public Distributor(Tracer tracer, NewSessionQueue queue, LocalDistributor distributor) {44 this.tracer = Require.nonNull("Tracer", tracer);45 this.queue = Require.nonNull("New session queue", queue);46 this.distributor = Require.nonNull("Distributor", distributor);47 }48 public HttpResponse execute(HttpRequest req) throws Exception {49 if (POST.equals(req.getMethod())) {50 return handleNewSession(req);51 }

Full Screen

Full Screen

NewSessionRequestEvent

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.NewSessionRequestEvent;2import org.openqa.selenium.grid.data.SessionRequest;3import org.openqa.selenium.grid.data.SessionRequestEvent;4import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestListener;5import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestListener.SessionRequestEventSource;6import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestListener.SessionRequestEventSource.SessionRequestEventSourceBuilder;7import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestListener.SessionRequestEventSource.SessionRequestEventSourceBuilder.SessionRequestEventSourceBuilderBuilder;8import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestListener.SessionRequestEventSource.SessionRequestEventSourceBuilder.SessionRequestEventSourceBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilder;9import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestListener.SessionRequestEventSource.SessionRequestEventSourceBuilder.SessionRequestEventSourceBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilderBuilder;10import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestListener.SessionRequestEventSource.SessionRequestEventSourceBuilder.SessionRequestEventSourceBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilderBuilderBuilder;11import org.openqa.selenium.grid.data.SessionRequestEvent.SessionRequestListener.SessionRequestEventSource.SessionRequestEventSourceBuilder.SessionRequestEventSourceBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilderBuilderBuilder.SessionRequestEventSourceBuilderBuilderBuilderBuilderBuilderBuilder;12import java.time.Instant;13import java.util.function.Consumer;14public class SessionRequestEventExample {15 public static void main(String[] args) {16 NewSessionRequestEvent newSessionRequestEvent = new NewSessionRequestEvent(17 new SessionRequest(18 SessionRequestEventSourceBuilderBuilderBuilderBuilderBuilderBuilderBuilderBuilder.builder()19 .setSessionId("Session ID")20 .setSessionRequest("Session Request")21 .setSessionRequest("Session Request ID")22 .setSessionRequest("Session Request Time")23 .setSessionRequest("Session Request Source")24 .build(),25 Instant.now(),26 );27 SessionRequestListener sessionRequestListener = new SessionRequestListener() {28 public void onSessionRequest(SessionRequestEvent event) {29 System.out.println(event);30 }31 };

Full Screen

Full Screen

NewSessionRequestEvent

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.NewSessionRequestEvent;2import org.openqa.selenium.grid.data.NewSessionRequestEvent.NewSessionRequestEventCodec;3import org.openqa.selenium.grid.data.NewSessionRequestEvent.NewSessionRequestEventDecoder;4import org.openqa.selenium.grid.data.NewSessionRequestEvent.NewSessionRequestEventEncoder;5import org.openqa.selenium.grid.data.NewSessionRequestEvent.NewSessionRequestEventSerializer;6import org.openqa.selenium.json.Json;7import org.openqa.selenium.json.JsonInput;8import org.openqa.selenium.json.JsonOutput;9import java.io.IOException;10import java.io.StringReader;11import java.io.StringWriter;12import java.util.Map;13public class NewSessionRequestEventExample {14 public static void main(String[] args) throws IOException {15 Json json = new Json();16 NewSessionRequestEventCodec codec = new NewSessionRequestEventCodec(json);17 StringWriter writer = new StringWriter();18 JsonOutput jsonOutput = json.newOutput(writer);19 codec.encode(jsonOutput, newSessionRequestEvent);20 StringReader reader = new StringReader(writer.toString());21 JsonInput jsonInput = json.newInput(reader);22 NewSessionRequestEvent newSessionRequestEventObject = codec.decode(jsonInput);23 System.out.println(newSessionRequestEventObject);24 NewSessionRequestEventSerializer serializer = new NewSessionRequestEventSerializer();25 Map<String, Object> map = serializer.apply(newSessionRequestEvent);26 System.out.println(map);27 NewSessionRequestEventEncoder encoder = new NewSessionRequestEventEncoder();28 String encodedString = encoder.apply(newSessionRequestEvent);

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.

Most used methods in NewSessionRequestEvent

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