Best Selenium code snippet using org.openqa.selenium.grid.data.SessionRequest.getRequestId
Source:LocalDistributor.java  
...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");...Source:LocalNewSessionQueueTest.java  
...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    };...Source:NewSessionQueuerTest.java  
...190  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() {...Source:LocalNewSessionQueue.java  
...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...Source:RemoteNewSessionQueue.java  
...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()) {...Source:GetNewSessionResponse.java  
...65  }66  private void setResponse(NewSessionResponse sessionResponse) {67    // Each thread will get its own CountDownLatch and it is stored in the Map using request id as the key.68    // EventBus thread will retrieve the same request and set it's response and unblock waiting request thread.69    RequestId id = sessionResponse.getRequestId();70    Optional<NewSessionRequest> sessionRequest = Optional.ofNullable(knownRequests.get(id));71    if (sessionRequest.isPresent()) {72      NewSessionRequest request = sessionRequest.get();73      request.setSessionResponse(74          new HttpResponse().setContent(bytes(sessionResponse.getDownstreamEncodedResponse())));75      request.getLatch().countDown();76    }77  }78  private void setErrorResponse(NewSessionErrorResponse sessionResponse) {79    RequestId id = sessionResponse.getRequestId();80    Optional<NewSessionRequest> sessionRequest = Optional.ofNullable(knownRequests.get(id));81    // There could be a situation where the session request in the queue is scheduled for retry.82    // Meanwhile the request queue is cleared.83    // This will fire a error response event and remove the request id from the knownRequests map.84    // Another error response event will be fired by the Distributor when the request is retried.85    // Since a response is already provided for the request, the event listener should not take any action.86    if (sessionRequest.isPresent()) {87      NewSessionRequest request = sessionRequest.get();88      request89          .setSessionResponse(new HttpResponse()90                                  .setStatus(HTTP_INTERNAL_ERROR)91                                  .setContent(asJson(92                                      ImmutableMap.of("message", sessionResponse.getMessage()))));93      request.getLatch().countDown();...Source:SessionRequest.java  
...23  public SessionRequest(RequestId requestId, HttpRequest request) {24    this.requestId = requestId;25    this.request = request;26  }27  public RequestId getRequestId() {28    return requestId;29  }30  public HttpRequest getHttpRequest() {31    return request;32  }33}getRequestId
Using AI Code Generation
1import org.openqa.selenium.grid.data.SessionRequest;2import org.openqa.selenium.remote.http.HttpResponse;3import org.openqa.selenium.remote.http.HttpClient;4import org.openqa.selenium.remote.http.HttpRequest;5import org.openqa.selenium.remote.http.Contents;6import org.openqa.selenium.grid.data.NewSessionRequest;7import org.openqa.selenium.grid.data.NewSessionResponse;8import java.net.URI;9import java.net.URISyntaxException;10import java.util.Map;11import java.util.HashMap;12import java.util.UUID;13import java.util.Optional;14import java.util.logging.Logger;15public class SessionRequestExample {16  private static final Logger LOG = Logger.getLogger(SessionRequestExample.class.getName());17  public static void main(String[] args) throws URISyntaxException {18    Map<String, Object> caps = new HashMap<>();19    caps.put("browserName", "chrome");20    NewSessionRequest request = new NewSessionRequest(UUID.randomUUID(), caps);21    HttpResponse response = client.execute(new HttpRequest("POST", "/session").setContent(Contents.asJson(request)));22    NewSessionResponse sessionResponse = NewSessionResponse.from(response);23    LOG.info("Session Id: " + sessionResponse.getSessionId());24    LOG.info("Session Request Id: " + sessionResponse.getSessionRequest().getRequestId());25  }26}getRequestId
Using AI Code Generation
1    at Object.checkLegacyResponse (C:\Users\username\AppData\Roaming2    at parseHttpResponse (C:\Users\username\AppData\Roaming3    at Executor.execute (C:\Users\username\AppData\Roaming4    at processTicksAndRejections (node:internal/process/task_queues:96:5)5    at async thenableWebDriverProxy.execute (C:\Users\username\AppData\Roaming6    at async Driver.schedule (C:\Users\username\AppData\Roaming7    at async Driver.createSession (C:\Users\username\AppData\getRequestId
Using AI Code Generation
1SessionRequest request = new SessionRequest(requestId, sessionRequest.getCapabilities());2session.setSessionRequest(request);3session.setSessionId(sessionId);4session.setStatus(status);5session.setUri(uri);6session.setCapabilities(capabilities);7session.setNodeId(nodeId);8session.setStartTime(startTime);9session.setEndTime(endTime);10session.setData(data);11session.setLastActive(lastActive);12session.setSlots(slots);13session.setTimeout(timeout);14session.setMaxTimeout(maxTimeout);15session.setConfig(config);16session.setSlot(slot);17session.setSlotId(slotId);18session.setSlotStatus(slotStatus);19session.setSlotStartTime(slotStartTime);20session.setSlotEndTime(slotEndTime);21session.setSlotLastActive(slotLastActive);22session.setSlotMaxTimeout(slotMaxTimeout);23session.setSlotTimeout(slotTimeout);24session.setSlotCapabilities(slotCapabilities);25session.setSlotData(slotData);26SessionRequest request = new SessionRequest(requestId, sessionRequest.getCapabilities());27session.setSessionRequest(request);28session.setSessionId(sessionId);29session.setStatus(status);30session.setUri(uri);31session.setCapabilities(capabilities);32session.setNodeId(nodeId);33session.setStartTime(startTime);34session.setEndTime(endTime);35session.setData(data);LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
