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

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

Source:LocalDistributor.java Github

copy

Full Screen

...155 bus.addListener(NewSessionRequestEvent.listener(ignored -> newSessionRunnable.run()));156 regularly.submit(model::purgeDeadNodes, Duration.ofSeconds(30), Duration.ofSeconds(30));157 regularly.submit(newSessionRunnable, Duration.ofSeconds(5), Duration.ofSeconds(5));158 }159 public static Distributor create(Config config) {160 Tracer tracer = new LoggingOptions(config).getTracer();161 EventBus bus = new EventBusOptions(config).getEventBus();162 DistributorOptions distributorOptions = new DistributorOptions(config);163 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);164 SessionMap sessions = new SessionMapOptions(config).getSessionMap();165 SecretOptions secretOptions = new SecretOptions(config);166 NewSessionQueue sessionQueue = new NewSessionQueueOptions(config).getSessionQueue(167 "org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue");168 return new LocalDistributor(169 tracer,170 bus,171 clientFactory,172 sessions,173 sessionQueue,174 distributorOptions.getSlotSelector(),175 secretOptions.getRegistrationSecret(),176 distributorOptions.getHealthCheckInterval(),177 distributorOptions.shouldRejectUnsupportedCaps());178 }179 @Override180 public boolean isReady() {181 try {182 return ImmutableSet.of(bus, sessions).parallelStream()183 .map(HasReadyState::isReady)184 .reduce(true, Boolean::logicalAnd);185 } catch (RuntimeException e) {186 return false;187 }188 }189 private void register(NodeStatus status) {190 Require.nonNull("Node", status);191 Lock writeLock = lock.writeLock();192 writeLock.lock();193 try {194 if (nodes.containsKey(status.getId())) {195 return;196 }197 Set<Capabilities> capabilities = status.getSlots().stream()198 .map(Slot::getStereotype)199 .map(ImmutableCapabilities::copyOf)200 .collect(toImmutableSet());201 // A new node! Add this as a remote node, since we've not called add202 RemoteNode remoteNode = new RemoteNode(203 tracer,204 clientFactory,205 status.getId(),206 status.getUri(),207 registrationSecret,208 capabilities);209 add(remoteNode);210 } finally {211 writeLock.unlock();212 }213 }214 @Override215 public LocalDistributor add(Node node) {216 Require.nonNull("Node", node);217 LOG.info(String.format("Added node %s at %s.", node.getId(), node.getUri()));218 nodes.put(node.getId(), node);219 model.add(node.getStatus());220 // Extract the health check221 Runnable runnableHealthCheck = asRunnableHealthCheck(node);222 allChecks.put(node.getId(), runnableHealthCheck);223 hostChecker.submit(runnableHealthCheck, healthcheckInterval, Duration.ofSeconds(30));224 bus.fire(new NodeAddedEvent(node.getId()));225 return this;226 }227 private Runnable asRunnableHealthCheck(Node node) {228 HealthCheck healthCheck = node.getHealthCheck();229 NodeId id = node.getId();230 return () -> {231 HealthCheck.Result result;232 try {233 result = healthCheck.check();234 } catch (Exception e) {235 LOG.log(Level.WARNING, "Unable to process node " + id, e);236 result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");237 }238 Lock writeLock = lock.writeLock();239 writeLock.lock();240 try {241 model.setAvailability(id, result.getAvailability());242 } finally {243 writeLock.unlock();244 }245 };246 }247 @Override248 public boolean drain(NodeId nodeId) {249 Node node = nodes.get(nodeId);250 if (node == null) {251 LOG.info("Asked to drain unregistered node " + nodeId);252 return false;253 }254 Lock writeLock = lock.writeLock();255 writeLock.lock();256 try {257 node.drain();258 model.setAvailability(nodeId, DRAINING);259 } finally {260 writeLock.unlock();261 }262 return node.isDraining();263 }264 public void remove(NodeId nodeId) {265 Lock writeLock = lock.writeLock();266 writeLock.lock();267 try {268 model.remove(nodeId);269 Runnable runnable = allChecks.remove(nodeId);270 if (runnable != null) {271 hostChecker.remove(runnable);272 }273 } finally {274 writeLock.unlock();275 }276 }277 @Override278 public DistributorStatus getStatus() {279 Lock readLock = this.lock.readLock();280 readLock.lock();281 try {282 return new DistributorStatus(model.getSnapshot());283 } finally {284 readLock.unlock();285 }286 }287 @Beta288 public void refresh() {289 List<Runnable> allHealthChecks = new ArrayList<>();290 Lock readLock = this.lock.readLock();291 readLock.lock();292 try {293 allHealthChecks.addAll(allChecks.values());294 } finally {295 readLock.unlock();296 }297 allHealthChecks.parallelStream().forEach(Runnable::run);298 }299 protected Set<NodeStatus> getAvailableNodes() {300 Lock readLock = this.lock.readLock();301 readLock.lock();302 try {303 return model.getSnapshot().stream()304 .filter(node -> !DOWN.equals(node.getAvailability()))305 .collect(toImmutableSet());306 } finally {307 readLock.unlock();308 }309 }310 @Override311 public Either<SessionNotCreatedException, CreateSessionResponse> newSession(SessionRequest request)312 throws SessionNotCreatedException {313 Require.nonNull("Requests to process", request);314 Span span = tracer.getCurrentContext().createSpan("distributor.new_session");315 Map<String, EventAttributeValue> attributeMap = new HashMap<>();316 try {317 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),318 EventAttribute.setValue(getClass().getName()));319 attributeMap.put("request.payload", EventAttribute.setValue(request.getDesiredCapabilities().toString()));320 String sessionReceivedMessage = "Session request received by the distributor";321 span.addEvent(sessionReceivedMessage, attributeMap);322 LOG.info(String.format("%s: \n %s", sessionReceivedMessage, request.getDesiredCapabilities()));323 // If there are no capabilities at all, something is horribly wrong324 if (request.getDesiredCapabilities().isEmpty()) {325 SessionNotCreatedException exception =326 new SessionNotCreatedException("No capabilities found in session request payload");327 EXCEPTION.accept(attributeMap, exception);328 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),329 EventAttribute.setValue("Unable to create session. No capabilities found: " +330 exception.getMessage()));331 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);332 return Either.left(exception);333 }334 boolean retry = false;335 SessionNotCreatedException lastFailure = new SessionNotCreatedException("Unable to create new session");336 for (Capabilities caps : request.getDesiredCapabilities()) {337 if (!isSupported(caps)) {338 continue;339 }340 // Try and find a slot that we can use for this session. While we341 // are finding the slot, no other session can possibly be started.342 // Therefore, spend as little time as possible holding the write343 // lock, and release it as quickly as possible. Under no344 // circumstances should we try to actually start the session itself345 // in this next block of code.346 SlotId selectedSlot = reserveSlot(request.getRequestId(), caps);347 if (selectedSlot == null) {348 LOG.info(String.format("Unable to find slot for request %s. May retry: %s ", request.getRequestId(), caps));349 retry = true;350 continue;351 }352 CreateSessionRequest singleRequest = new CreateSessionRequest(353 request.getDownstreamDialects(),354 caps,355 request.getMetadata());356 try {357 CreateSessionResponse response = startSession(selectedSlot, singleRequest);358 sessions.add(response.getSession());359 model.setSession(selectedSlot, response.getSession());360 SessionId sessionId = response.getSession().getId();361 Capabilities sessionCaps = response.getSession().getCapabilities();362 String sessionUri = response.getSession().getUri().toString();363 SESSION_ID.accept(span, sessionId);364 CAPABILITIES.accept(span, sessionCaps);365 SESSION_ID_EVENT.accept(attributeMap, sessionId);366 CAPABILITIES_EVENT.accept(attributeMap, sessionCaps);367 span.setAttribute(SESSION_URI.getKey(), sessionUri);368 attributeMap.put(SESSION_URI.getKey(), EventAttribute.setValue(sessionUri));369 String sessionCreatedMessage = "Session created by the distributor";370 span.addEvent(sessionCreatedMessage, attributeMap);371 LOG.info(String.format("%s. Id: %s, Caps: %s", sessionCreatedMessage, sessionId, sessionCaps));372 return Either.right(response);373 } catch (SessionNotCreatedException e) {374 model.setSession(selectedSlot, null);375 lastFailure = e;376 }377 }378 // If we've made it this far, we've not been able to start a session379 if (retry) {380 lastFailure = new RetrySessionRequestException(381 "Will re-attempt to find a node which can run this session",382 lastFailure);383 attributeMap.put(384 AttributeKey.EXCEPTION_MESSAGE.getKey(),385 EventAttribute.setValue("Will retry session " + request.getRequestId()));386 } else {387 EXCEPTION.accept(attributeMap, lastFailure);388 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),389 EventAttribute.setValue("Unable to create session: " + lastFailure.getMessage()));390 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);391 }392 return Either.left(lastFailure);393 } catch (SessionNotCreatedException e) {394 span.setAttribute(AttributeKey.ERROR.getKey(), true);395 span.setStatus(Status.ABORTED);396 EXCEPTION.accept(attributeMap, e);397 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),398 EventAttribute.setValue("Unable to create session: " + e.getMessage()));399 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);400 return Either.left(e);401 } catch (UncheckedIOException e) {402 span.setAttribute(AttributeKey.ERROR.getKey(), true);403 span.setStatus(Status.UNKNOWN);404 EXCEPTION.accept(attributeMap, e);405 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),406 EventAttribute.setValue("Unknown error in LocalDistributor while creating session: " + e.getMessage()));407 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);408 return Either.left(new SessionNotCreatedException(e.getMessage(), e));409 } finally {410 span.close();411 }412 }413 private CreateSessionResponse startSession(SlotId selectedSlot, CreateSessionRequest singleRequest) {414 Node node = nodes.get(selectedSlot.getOwningNodeId());415 if (node == null) {416 throw new SessionNotCreatedException("Unable to find owning node for slot");417 }418 Either<WebDriverException, CreateSessionResponse> result;419 try {420 result = node.newSession(singleRequest);421 } catch (SessionNotCreatedException e) {422 result = Either.left(e);423 } catch (RuntimeException e) {424 result = Either.left(new SessionNotCreatedException(e.getMessage(), e));425 }426 if (result.isLeft()) {427 WebDriverException exception = result.left();428 if (exception instanceof SessionNotCreatedException) {429 throw exception;430 }431 throw new SessionNotCreatedException(exception.getMessage(), exception);432 }433 return result.right();434 }435 private SlotId reserveSlot(RequestId requestId, Capabilities caps) {436 Lock writeLock = lock.writeLock();437 writeLock.lock();438 try {439 Set<SlotId> slotIds = slotSelector.selectSlot(caps, getAvailableNodes());440 if (slotIds.isEmpty()) {441 LOG.log(442 getDebugLogLevel(),443 String.format("No slots found for request %s and capabilities %s", requestId, caps));444 return null;445 }446 for (SlotId slotId : slotIds) {447 if (reserve(slotId)) {448 return slotId;449 }450 }451 return null;452 } finally {453 writeLock.unlock();454 }455 }456 private boolean isSupported(Capabilities caps) {457 return getAvailableNodes().stream().anyMatch(node -> node.hasCapability(caps));458 }459 private boolean reserve(SlotId id) {460 Require.nonNull("Slot ID", id);461 Lock writeLock = this.lock.writeLock();462 writeLock.lock();463 try {464 Node node = nodes.get(id.getOwningNodeId());465 if (node == null) {466 LOG.log(getDebugLogLevel(), String.format("Unable to find node with id %s", id));467 return false;468 }469 return model.reserve(id);470 } finally {471 writeLock.unlock();472 }473 }474 public void callExecutorShutdown() {475 LOG.info("Shutting down Distributor executor service");476 regularly.shutdown();477 }478 public class NewSessionRunnable implements Runnable {479 @Override480 public void run() {481 List<SessionRequestCapability> queueContents = sessionQueue.getQueueContents();482 if (rejectUnsupportedCaps) {483 checkMatchingSlot(queueContents);484 }485 int initialSize = queueContents.size();486 boolean retry = initialSize != 0;487 while (retry) {488 // We deliberately run this outside of a lock: if we're unsuccessful489 // starting the session, we just put the request back on the queue.490 // This does mean, however, that under high contention, we might end491 // up starving a session request.492 Set<Capabilities> stereotypes =493 getAvailableNodes().stream()494 .filter(NodeStatus::hasCapacity)495 .map(496 node ->497 node.getSlots().stream()498 .map(Slot::getStereotype)499 .collect(Collectors.toSet()))500 .flatMap(Collection::stream)501 .collect(Collectors.toSet());502 Optional<SessionRequest> maybeRequest = sessionQueue.getNextAvailable(stereotypes);503 maybeRequest.ifPresent(this::handleNewSessionRequest);504 int currentSize = sessionQueue.getQueueContents().size();505 retry = currentSize != 0 && currentSize != initialSize;506 initialSize = currentSize;507 }508 }509 private void checkMatchingSlot(List<SessionRequestCapability> sessionRequests) {510 for(SessionRequestCapability request : sessionRequests) {511 long unmatchableCount = request.getDesiredCapabilities().stream()512 .filter(caps -> !isSupported(caps))513 .count();514 if (unmatchableCount == request.getDesiredCapabilities().size()) {515 SessionNotCreatedException exception = new SessionNotCreatedException(516 "No nodes support the capabilities in the request");517 sessionQueue.complete(request.getRequestId(), Either.left(exception));518 }519 }520 }521 private void handleNewSessionRequest(SessionRequest sessionRequest) {522 RequestId reqId = sessionRequest.getRequestId();523 try (Span span = TraceSessionRequest.extract(tracer, sessionRequest).createSpan("distributor.poll_queue")) {524 Map<String, EventAttributeValue> attributeMap = new HashMap<>();525 attributeMap.put(526 AttributeKey.LOGGER_CLASS.getKey(),527 EventAttribute.setValue(getClass().getName()));528 span.setAttribute(AttributeKey.REQUEST_ID.getKey(), reqId.toString());529 attributeMap.put(530 AttributeKey.REQUEST_ID.getKey(),531 EventAttribute.setValue(reqId.toString()));532 attributeMap.put("request", EventAttribute.setValue(sessionRequest.toString()));533 Either<SessionNotCreatedException, CreateSessionResponse> response = newSession(sessionRequest);534 if (response.isLeft() && response.left() instanceof RetrySessionRequestException) {535 try(Span childSpan = span.createSpan("distributor.retry")) {536 LOG.info("Retrying");537 boolean retried = sessionQueue.retryAddToQueue(sessionRequest);538 attributeMap.put("request.retry_add", EventAttribute.setValue(retried));539 childSpan.addEvent("Retry adding to front of queue. No slot available.", attributeMap);540 if (retried) {541 return;542 }543 childSpan.addEvent("retrying_request", attributeMap);544 }545 }546 sessionQueue.complete(reqId, response);547 }548 }549 }...

Full Screen

Full Screen

Source:LocalNewSessionQueueTest.java Github

copy

Full Screen

...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(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();389 assertThat(isPresent.get()).isEqualTo(sessionRequest.getRequestId());390 }391 @Test(timeout = 5000)392 public void shouldBeAbleToClearQueueAndRejectMultipleRequests() {393 ExecutorService executor = Executors.newFixedThreadPool(2);394 Callable<HttpResponse> callable = () -> {395 SessionRequest sessionRequest = new SessionRequest(396 new RequestId(UUID.randomUUID()),397 Instant.now(),398 Set.of(W3C),399 Set.of(CAPS),400 Map.of(),401 Map.of());402 return queue.addToQueue(sessionRequest);403 };404 Future<HttpResponse> firstRequest = executor.submit(callable);405 Future<HttpResponse> secondRequest = executor.submit(callable);406 int count = 0;407 while (count < 2) {408 count += queue.clearQueue();409 }410 try {411 HttpResponse firstResponse = firstRequest.get(30, SECONDS);412 HttpResponse secondResponse = secondRequest.get(30, SECONDS);413 assertEquals(firstResponse.getStatus(), HTTP_INTERNAL_ERROR);414 assertEquals(secondResponse.getStatus(), HTTP_INTERNAL_ERROR);415 } catch (InterruptedException | ExecutionException | TimeoutException e) {416 fail("Could not create session");417 }418 executor.shutdownNow();419 }420 @Test421 public void shouldBeAbleToReturnTheNextAvailableEntryThatMatchesAStereotype() {422 SessionRequest expected = new SessionRequest(423 new RequestId(UUID.randomUUID()),424 Instant.now(),425 Set.of(W3C),426 Set.of(new ImmutableCapabilities("browserName", "cheese", "se:kind", "smoked")),427 Map.of(),428 Map.of());429 localQueue.injectIntoQueue(expected);430 localQueue.injectIntoQueue(new SessionRequest(...

Full Screen

Full Screen

Source:RemoteNewSessionQueue.java Github

copy

Full Screen

...61 this.client = Require.nonNull("HTTP client", client);62 Require.nonNull("Registration secret", registrationSecret);63 this.addSecret = new AddSecretFilter(registrationSecret);64 }65 public static NewSessionQueue create(Config config) {66 Tracer tracer = new LoggingOptions(config).getTracer();67 URI uri = new NewSessionQueueOptions(config).getSessionQueueUri();68 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);69 SecretOptions secretOptions = new SecretOptions(config);70 Secret registrationSecret = secretOptions.getRegistrationSecret();71 try {72 return new RemoteNewSessionQueue(73 tracer,74 clientFactory.createClient(uri.toURL()),75 registrationSecret);76 } catch (MalformedURLException e) {77 throw new UncheckedIOException(e);78 }79 }80 @Override81 public HttpResponse addToQueue(SessionRequest request) {82 HttpRequest upstream = new HttpRequest(POST, "/se/grid/newsessionqueue/session");83 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);84 upstream.setContent(Contents.asJson(request));85 return client.with(addSecret).execute(upstream);86 }87 @Override88 public boolean retryAddToQueue(SessionRequest request) {...

Full Screen

Full Screen

Source:RouterServer.java Github

copy

Full Screen

...96 protected Config getDefaultConfig() {97 return new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", 4444)));98 }99 @Override100 protected Handlers createHandlers(Config config) {101 LoggingOptions loggingOptions = new LoggingOptions(config);102 Tracer tracer = loggingOptions.getTracer();103 NetworkOptions networkOptions = new NetworkOptions(config);104 HttpClient.Factory clientFactory = networkOptions.getHttpClientFactory(tracer);105 BaseServerOptions serverOptions = new BaseServerOptions(config);106 SecretOptions secretOptions = new SecretOptions(config);107 Secret secret = secretOptions.getRegistrationSecret();108 SessionMapOptions sessionsOptions = new SessionMapOptions(config);109 SessionMap sessions = sessionsOptions.getSessionMap();110 NewSessionQueueOptions sessionQueueOptions = new NewSessionQueueOptions(config);111 URL sessionQueueUrl = fromUri(sessionQueueOptions.getSessionQueueUri());112 NewSessionQueue queue = new RemoteNewSessionQueue(113 tracer,114 clientFactory.createClient(sessionQueueUrl),115 secret);116 DistributorOptions distributorOptions = new DistributorOptions(config);117 URL distributorUrl = fromUri(distributorOptions.getDistributorUri());118 Distributor distributor = new RemoteDistributor(119 tracer,120 clientFactory,121 distributorUrl,122 secret);123 GraphqlHandler graphqlHandler = new GraphqlHandler(124 tracer,125 distributor,126 queue,127 serverOptions.getExternalUri(),128 getServerVersion());...

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.Session;2import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;3import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;4import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;5import org.openqa.selenium.remote.http.HttpClient;6import org.openqa.selenium.remote.http.HttpMethod;7import org.openqa.selenium.remote.http.HttpRequest;8import org.openqa.selenium.remote.http.HttpResponse;9import org.openqa.selenium.remote.tracing.Tracer;10import org.openqa.selenium.remote.tracing.distributed.DistributedTracer;11import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;12import java.net.URI;13import java.net.URISyntaxException;14import java.time.Duration;15import java.util.concurrent.TimeUnit;16public class RemoteNewSessionQueueExample {17 public static void main(String[] args) throws URISyntaxException {18 Tracer tracer = new DistributedTracer(new OpenTelemetryTracer());19 HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");20 HttpResponse response = client.execute(request, Duration.ofSeconds(10));21 Session session = new Session(response);22 queue.add(session);23 queue.create(Duration.of(10, TimeUnit.SECONDS));24 }25}26import org.openqa.selenium.grid.data.Session;27import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;28import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;29import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;30import org.openqa.selenium.remote.http.HttpClient;31import org.openqa.selenium.remote.http.HttpMethod;32import org.openqa.selenium.remote.http.HttpRequest;33import org.openqa.selenium.remote.http.HttpResponse;34import org.openqa.selenium.remote.tracing.Tracer;35import org.openqa.selenium.remote.tracing.distributed.DistributedTracer;36import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;37import java.net.URI;38import java.net.URISyntaxException;39import java.time.Duration;40import java.util.concurrent.TimeUnit;41public class LocalNewSessionQueueExample {42 public static void main(String[] args) throws URISyntaxException {43 Tracer tracer = new DistributedTracer(new OpenTelemetryTracer());

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.config.Config;2import org.openqa.selenium.grid.config.MapConfig;3import org.openqa.selenium.grid.data.Session;4import org.openqa.selenium.grid.data.SessionRequest;5import org.openqa.selenium.grid.data.SessionRequestEvent;6import org.openqa.selenium.grid.data.SessionRequestEvent.State;7import org.openqa.selenium.grid.data.SessionRequestEvent.Type;8import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;9import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;10import org.openqa.selenium.grid.web.Routable;11import org.openqa.selenium.remote.http.HttpClient;12import org.openqa.selenium.remote.http.HttpMethod;13import org.openqa.selenium.remote.http.HttpRequest;14import org.openqa.selenium.remote.http.HttpResponse;15import org.openqa.selenium.remote.tracing.DefaultTestTracer;16import org.openqa.selenium.remote.tracer.Tracer;17import java.io.IOException;18import java.net.URI;19import java.net.URISyntaxException;20import java.util.HashMap;21import java.util.Map;22import java.util.concurrent.CompletableFuture;23import java.util.concurrent.ExecutionException;24public class RemoteNewSessionQueueExample {25 public static void main(String[] args) throws URISyntaxException, ExecutionException, InterruptedException, IOException {26 Map<String, String> rawConfig = new HashMap<>();27 Config config = new MapConfig(rawConfig);28 Tracer tracer = DefaultTestTracer.createTracer();29 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();30 RemoteNewSessionQueue queue = new RemoteNewSessionQueue(config, tracer, clientFactory);31 SessionRequest request = new SessionRequest(32 CompletableFuture<Session> future = new CompletableFuture<>();33 request.addListener(new SessionRequestEvent() {34 public Type getType() {35 return Type.CREATED;36 }37 public State getState() {

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1RemoteNewSessionQueue remoteNewSessionQueue = new RemoteNewSessionQueue(URI.create(uri));2remoteNewSessionQueue.create(new SessionRequest(new Capabilities(), Instant.now()));3RemoteNewSessionQueue remoteNewSessionQueue = new RemoteNewSessionQueue(URI.create(uri));4remoteNewSessionQueue.delete("session-id");5RemoteNewSessionQueue remoteNewSessionQueue = new RemoteNewSessionQueue(URI.create(uri));6remoteNewSessionQueue.get("session-id");7RemoteNewSessionQueue remoteNewSessionQueue = new RemoteNewSessionQueue(URI.create(uri));8remoteNewSessionQueue.getAll();9RemoteNewSessionQueue remoteNewSessionQueue = new RemoteNewSessionQueue(URI.create(uri));10remoteNewSessionQueue.getLength();11RemoteNewSessionQueue remoteNewSessionQueue = new RemoteNewSessionQueue(URI.create(uri));12remoteNewSessionQueue.getNewSessionQueueUri();13RemoteNewSessionQueue remoteNewSessionQueue = new RemoteNewSessionQueue(URI.create(uri));14remoteNewSessionQueue.getStatus();15RemoteNewSessionQueue remoteNewSessionQueue = new RemoteNewSessionQueue(URI.create(uri));16remoteNewSessionQueue.update("session-id", new Session(new SessionId("session-id"), new URI

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1NewSessionRequest request = new NewSessionRequest(new ImmutableCapabilities());2String id = queue.add(request);3NewSessionRequest actual = queue.get(id);4queue.remove(id);5NewSessionRequest request = new NewSessionRequest(new ImmutableCapabilities());6String id = queue.add(request);7NewSessionRequest actual = queue.get(id);8queue.remove(id);

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful