How to use getRequestId method of org.openqa.selenium.grid.data.SessionRequestCapability class

Best Selenium code snippet using org.openqa.selenium.grid.data.SessionRequestCapability.getRequestId

Source:LocalDistributor.java Github

copy

Full Screen

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

Full Screen

Full Screen

Source:LocalNewSessionQueueTest.java Github

copy

Full Screen

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

Full Screen

Full Screen

Source:LocalNewSessionQueue.java Github

copy

Full Screen

...158 }159 @Override160 public HttpResponse addToQueue(SessionRequest request) {161 Require.nonNull("New session request", request);162 Require.nonNull("Request id", request.getRequestId());163 TraceContext context = TraceSessionRequest.extract(tracer, request);164 try (Span span = context.createSpan("sessionqueue.add_to_queue")) {165 contexts.put(request.getRequestId(), context);166 Data data = injectIntoQueue(request);167 if (isTimedOut(Instant.now(), data)) {168 failDueToTimeout(request.getRequestId());169 }170 Either<SessionNotCreatedException, CreateSessionResponse> result;171 try {172 if (data.latch.await(requestTimeout.toMillis(), MILLISECONDS)) {173 result = data.result;174 } else {175 result = Either.left(new SessionNotCreatedException("New session request timed out"));176 }177 } catch (InterruptedException e) {178 Thread.currentThread().interrupt();179 result = Either.left(new SessionNotCreatedException("Interrupted when creating the session", e));180 } catch (RuntimeException e) {181 result = Either.left(new SessionNotCreatedException("An error occurred creating the session", e));182 }183 Lock writeLock = this.lock.writeLock();184 writeLock.lock();185 try {186 requests.remove(request.getRequestId());187 queue.remove(request);188 } finally {189 writeLock.unlock();190 }191 HttpResponse res = new HttpResponse();192 if (result.isRight()) {193 res.setContent(Contents.bytes(result.right().getDownstreamEncodedResponse()));194 } else {195 res.setStatus(HTTP_INTERNAL_ERROR)196 .setContent(Contents.asJson(Collections.singletonMap("value", result.left())));197 }198 return res;199 }200 }201 @VisibleForTesting202 Data injectIntoQueue(SessionRequest request) {203 Require.nonNull("Session request", request);204 Data data = new Data(request.getEnqueued());205 Lock writeLock = lock.writeLock();206 writeLock.lock();207 try {208 requests.put(request.getRequestId(), data);209 queue.addLast(request);210 } finally {211 writeLock.unlock();212 }213 bus.fire(new NewSessionRequestEvent(request.getRequestId()));214 return data;215 }216 @Override217 public boolean retryAddToQueue(SessionRequest request) {218 Require.nonNull("New session request", request);219 boolean added;220 TraceContext context = contexts.getOrDefault(request.getRequestId(), tracer.getCurrentContext());221 try (Span span = context.createSpan("sessionqueue.retry")) {222 Lock writeLock = lock.writeLock();223 writeLock.lock();224 try {225 if (!requests.containsKey(request.getRequestId())) {226 return false;227 }228 if (queue.contains(request)) {229 // No need to re-add this230 return true;231 } else {232 added = queue.offerFirst(request);233 }234 } finally {235 writeLock.unlock();236 }237 if (added) {238 bus.fire(new NewSessionRequestEvent(request.getRequestId()));239 }240 return added;241 }242 }243 @Override244 public Optional<SessionRequest> remove(RequestId reqId) {245 Require.nonNull("Request ID", reqId);246 Lock writeLock = lock.writeLock();247 writeLock.lock();248 try {249 Iterator<SessionRequest> iterator = queue.iterator();250 while (iterator.hasNext()) {251 SessionRequest req = iterator.next();252 if (reqId.equals(req.getRequestId())) {253 iterator.remove();254 return Optional.of(req);255 }256 }257 return Optional.empty();258 } finally {259 writeLock.unlock();260 }261 }262 @Override263 public Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes) {264 Require.nonNull("Stereotypes", stereotypes);265 Predicate<Capabilities> matchesStereotype =266 caps -> stereotypes.stream().anyMatch(stereotype -> slotMatcher.matches(stereotype, caps));267 Lock writeLock = lock.writeLock();268 writeLock.lock();269 try {270 Optional<SessionRequest> maybeRequest =271 queue.stream()272 .filter(req -> req.getDesiredCapabilities().stream().anyMatch(matchesStereotype))273 .findFirst();274 maybeRequest.ifPresent(req -> {275 this.remove(req.getRequestId());276 });277 return maybeRequest;278 } finally {279 writeLock.unlock();280 }281 }282 @Override283 public void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result) {284 Require.nonNull("New session request", reqId);285 Require.nonNull("Result", result);286 TraceContext context = contexts.getOrDefault(reqId, tracer.getCurrentContext());287 try (Span span = context.createSpan("sessionqueue.completed")) {288 Lock readLock = lock.readLock();289 readLock.lock();290 Data data;291 try {292 data = requests.get(reqId);293 } finally {294 readLock.unlock();295 }296 if (data == null) {297 return;298 }299 Lock writeLock = lock.writeLock();300 writeLock.lock();301 try {302 requests.remove(reqId);303 queue.removeIf(req -> reqId.equals(req.getRequestId()));304 contexts.remove(reqId);305 } finally {306 writeLock.unlock();307 }308 if (result.isLeft()) {309 bus.fire(new NewSessionRejectedEvent(new NewSessionErrorResponse(reqId, result.left().getMessage())));310 }311 data.setResult(result);312 }313 }314 @Override315 public int clearQueue() {316 Lock writeLock = lock.writeLock();317 writeLock.lock();318 try {319 int size = queue.size();320 queue.clear();321 requests.forEach((reqId, data) -> {322 data.setResult(Either.left(new SessionNotCreatedException("Request queue was cleared")));323 bus.fire(new NewSessionRejectedEvent(324 new NewSessionErrorResponse(reqId, "New session queue was forcibly cleared")));325 });326 requests.clear();327 return size;328 } finally {329 writeLock.unlock();330 }331 }332 @Override333 public List<SessionRequestCapability> getQueueContents() {334 Lock readLock = lock.readLock();335 readLock.lock();336 try {337 return queue.stream()338 .map(req ->339 new SessionRequestCapability(req.getRequestId(), req.getDesiredCapabilities()))340 .collect(Collectors.toList());341 } finally {342 readLock.unlock();343 }344 }345 @ManagedAttribute(name = "NewSessionQueueSize")346 public int getQueueSize() {347 return queue.size();348 }349 @Override350 public boolean isReady() {351 return true;352 }353 @Override...

Full Screen

Full Screen

Source:RemoteNewSessionQueue.java Github

copy

Full Screen

...87 @Override88 public boolean retryAddToQueue(SessionRequest request) {89 Require.nonNull("Session request", request);90 HttpRequest upstream =91 new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/retry", request.getRequestId()));92 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);93 upstream.setContent(Contents.asJson(request));94 HttpResponse response = client.with(addSecret).execute(upstream);95 return Values.get(response, Boolean.class);96 }97 @Override98 public Optional<SessionRequest> remove(RequestId reqId) {99 HttpRequest upstream = new HttpRequest(POST, "/se/grid/newsessionqueue/session/" + reqId);100 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);101 HttpResponse response = client.with(addSecret).execute(upstream);102 if (response.isSuccessful()) {103 // TODO: This should work cleanly with just a TypeToken of <Optional<SessionRequest>>104 String rawValue = Contents.string(response);105 if (rawValue == null || rawValue.trim().isEmpty()) {...

Full Screen

Full Screen

Source:SessionRequestCapability.java Github

copy

Full Screen

...39 this.requestId = Require.nonNull("Request ID", requestId);40 this.desiredCapabilities = unmodifiableSet(41 new LinkedHashSet<>(Require.nonNull("Capabilities", desiredCapabilities)));42 }43 public RequestId getRequestId() {44 return requestId;45 }46 public Set<Capabilities> getDesiredCapabilities() {47 return desiredCapabilities;48 }49 @Override50 public String toString() {51 return new StringJoiner(", ", SessionRequestCapability.class.getSimpleName() + "[", "]")52 .add("requestId=" + requestId)53 .add("desiredCapabilities=" + desiredCapabilities)54 .toString();55 }56 @Override57 public boolean equals(Object o) {...

Full Screen

Full Screen

getRequestId

Using AI Code Generation

copy

Full Screen

1SessionRequestCapability sessionRequestCapability = new SessionRequestCapability();2sessionRequestCapability.getRequestId();3sessionRequestCapability.getSlotId();4sessionRequestCapability.getSlot();5sessionRequestCapability.getCapabilities();6sessionRequestCapability.getStartTime();7sessionRequestCapability.getEndTime();8sessionRequestCapability.getDuration();9sessionRequestCapability.getUri();10sessionRequestCapability.getMetadata();11sessionRequestCapability.getRequestedCapabilities();12sessionRequestCapability.getRequiredCapabilities();13sessionRequestCapability.getAdditionalCapabilities();14sessionRequestCapability.getCapability();

Full Screen

Full Screen

getRequestId

Using AI Code Generation

copy

Full Screen

1package com.selenium4beginners.java.basics;2import java.util.List;3import java.util.Set;4import org.openqa.selenium.Capabilities;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.devtools.DevTools;8import org.openqa.selenium.devtools.v91.log.Log;9import org.openqa.selenium.devtools.v91.log.model.LogEntry;10import org.openqa.selenium.devtools.v91.log.model.LogEntryAdded;11import org.openqa.selenium.devtools.v91.network.Network;12import org.openqa.selenium.devtools.v91.network.model.ConnectionType;13import org.openqa.selenium.devtools.v91.network.model.Initiator;14import org.openqa.selenium.devtools.v91.network.model.Request;15import org.openqa.selenium.devtools.v91.network.model.RequestId;16import org.openqa.selenium.devtools.v91.network.model.ResourceType;17import org.openqa.selenium.devtools.v91.network.model.Response;18import org.openqa.selenium.devtools.v91.network.model.WallTime;19import io.github.bonigarcia.wdm.WebDriverManager;20public class NetworkRequestLogs {21 public static void main(String[] args) {22 WebDriverManager.chromedriver().setup();23 WebDriver driver = new ChromeDriver();24 DevTools devTools = ((ChromeDriver) driver).getDevTools();25 devTools.createSession();26 devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));27 devTools.addListener(Network.requestWillBeSent(), request -> {28 RequestId requestId = request.getRequestId();29 Request req = request.getRequest();30 String url = req.getUrl();31 String method = req.getMethod();32 Initiator initiator = request.getInitiator();33 String type = initiator.getType();34 String url2 = initiator.getUrl();35 WallTime time = request.getWallTime();36 double timestamp = time.getTimeSinceEpoch();37 System.out.println("Request ID: " + requestId + " URL: " + url + " Method: " + method + " Initiator Type: " + type + " Initiator URL: " + url2 + " Timestamp: " + timestamp);38 });39 devTools.addListener(Network.responseReceived(), response -> {40 RequestId requestId = response.getRequestId();41 Response resp = response.getResponse();42 String url = resp.getUrl();43 String status = resp.getStatus();44 String mimeType = resp.getMimeType();45 System.out.println("Response Request ID: " + requestId + " URL: " + url + " Status: " + status + " M

Full Screen

Full Screen

getRequestId

Using AI Code Generation

copy

Full Screen

1package com.test;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.HashMap;5import java.util.List;6import java.util.Map;7import org.openqa.selenium.Capabilities;8import org.openqa.selenium.MutableCapabilities;9import org.openqa.selenium.SessionNotCreatedException;10import org.openqa.selenium.WebDriver;11import org.openqa.selenium.WebDriverException;12import org.openqa.selenium.grid.data.Session;13import org.openqa.selenium.grid.data.SessionId;14import org.openqa.selenium.grid.data.SessionRequest;15import org.openqa.selenium.grid.data.SessionRequestCapability;16import org.openqa.selenium.grid.distributor.local.LocalDistributor;17import org.openqa.selenium.grid.node.local.LocalNode;18import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;19import org.openqa.selenium.grid.web.Routable;20import org.openqa.selenium.grid.web.Routes;21import org.openqa.selenium.remote.NewSessionPayload;22import org.openqa.selenium.remote.RemoteWebDriver;23import org.openqa.selenium.remote.SessionIdGenerator;24import org.openqa.selenium.remote.http.HttpMethod;25import org.openqa.selenium.remote.http.HttpRequest;26import org.openqa.selenium.remote.http.HttpResponse;27import org.openqa.selenium.remote.http.Route;28import org.openqa.selenium.remote.tracing.DefaultTestTracer;29import org.openqa.selenium.remote.tracing.Tracer;30public class GetSessionId {31 public static void main(String[] args) throws MalformedURLException {32 Tracer tracer = DefaultTestTracer.createTracer();33 LocalSessionMap sessions = new LocalSessionMap(tracer);34 LocalDistributor distributor = new LocalDistributor(tracer, sessions);35 LocalNode node = LocalNode.builder(tracer, sessions, distributor)36 .add(new Firefox()).build();37 node.start();38 distributor.add(node);39 System.out.println("Session ID: " + driver.getSessionId());40 driver.quit();41 }42 private static class Firefox extends MutableCapabilities implements Routable {43 public Firefox() {44 setCapability("browserName", "firefox");45 }46 public List<Route> getRoutes() {47 return new Routes()48 .add(Route.matching(req -> req.getMethod() == HttpMethod.POST && req.getUri().equals("/session"))49 .to(() -> new CreateSession()))50 .add(Route.matching(req -> req.getMethod() ==

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 method in SessionRequestCapability

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful