Best Selenium code snippet using org.openqa.selenium.grid.data.NewSessionErrorResponse
Source:NewSessionQueuerTest.java
...22import org.openqa.selenium.ImmutableCapabilities;23import org.openqa.selenium.events.EventBus;24import org.openqa.selenium.events.local.GuavaEventBus;25import org.openqa.selenium.grid.data.CreateSessionResponse;26import org.openqa.selenium.grid.data.NewSessionErrorResponse;27import org.openqa.selenium.grid.data.NewSessionRejectedEvent;28import org.openqa.selenium.grid.data.NewSessionRequestEvent;29import org.openqa.selenium.grid.data.NewSessionResponse;30import org.openqa.selenium.grid.data.NewSessionResponseEvent;31import org.openqa.selenium.grid.data.RequestId;32import org.openqa.selenium.grid.data.Session;33import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;34import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueuer;35import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueuer;36import org.openqa.selenium.grid.testing.PassthroughHttpClient;37import org.openqa.selenium.json.Json;38import org.openqa.selenium.remote.NewSessionPayload;39import org.openqa.selenium.remote.SessionId;40import org.openqa.selenium.remote.http.Contents;41import org.openqa.selenium.remote.http.HttpClient;42import org.openqa.selenium.remote.http.HttpMethod;43import org.openqa.selenium.remote.http.HttpRequest;44import org.openqa.selenium.remote.http.HttpResponse;45import org.openqa.selenium.remote.tracing.DefaultTestTracer;46import org.openqa.selenium.remote.tracing.Tracer;47import java.io.IOException;48import java.io.UncheckedIOException;49import java.net.URI;50import java.net.URISyntaxException;51import java.time.Duration;52import java.time.Instant;53import java.util.Optional;54import java.util.UUID;55import java.util.concurrent.Callable;56import java.util.concurrent.ExecutionException;57import java.util.concurrent.ExecutorService;58import java.util.concurrent.Executors;59import java.util.concurrent.Future;60import java.util.concurrent.TimeUnit;61import java.util.concurrent.TimeoutException;62import java.util.concurrent.atomic.AtomicBoolean;63import java.util.concurrent.atomic.AtomicInteger;64import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;65import static java.net.HttpURLConnection.HTTP_OK;66import static java.nio.charset.StandardCharsets.UTF_8;67import static org.assertj.core.api.Assertions.assertThat;68import static org.assertj.core.api.Assertions.fail;69import static org.junit.Assert.assertEquals;70import static org.junit.Assert.assertFalse;71import static org.junit.Assert.assertNotEquals;72import static org.junit.Assert.assertTrue;73import static org.openqa.selenium.grid.sessionqueue.NewSessionQueue.SESSIONREQUEST_TIMESTAMP_HEADER;74import static org.openqa.selenium.remote.http.Contents.utf8String;75import static org.openqa.selenium.remote.http.HttpMethod.POST;76public class NewSessionQueuerTest {77 private LocalNewSessionQueuer local;78 private RemoteNewSessionQueuer remote;79 private EventBus bus;80 private ImmutableCapabilities caps;81 private NewSessionPayload payload;82 private HttpRequest request;83 private static int count = 0;84 private static final Json JSON = new Json();85 private NewSessionQueue sessionQueue;86 @Before87 public void setUp() {88 Tracer tracer = DefaultTestTracer.createTracer();89 caps = new ImmutableCapabilities("browserName", "chrome");90 bus = new GuavaEventBus();91 sessionQueue = new LocalNewSessionQueue(92 tracer,93 bus,94 Duration.ofSeconds(1),95 Duration.ofSeconds(1000));96 local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);97 HttpClient client = new PassthroughHttpClient(local);98 remote = new RemoteNewSessionQueuer(tracer, client);99 payload = NewSessionPayload.create(caps);100 request = createRequest(payload, POST, "/session");101 }102 @Test103 public void shouldBeAbleToAddToQueueAndGetValidResponse() {104 AtomicBoolean isPresent = new AtomicBoolean(false);105 bus.addListener(NewSessionRequestEvent.listener(reqId -> {106 Optional<HttpRequest> sessionRequest = this.local.remove();107 isPresent.set(sessionRequest.isPresent());108 Capabilities capabilities = new ImmutableCapabilities("browserName", "chrome");109 try {110 SessionId sessionId = new SessionId("123");111 Session session =112 new Session(113 sessionId,114 new URI("http://example.com"),115 caps,116 capabilities,117 Instant.now());118 CreateSessionResponse sessionResponse = new CreateSessionResponse(119 session,120 JSON.toJson(121 ImmutableMap.of(122 "value", ImmutableMap.of(123 "sessionId", sessionId,124 "capabilities", capabilities)))125 .getBytes(UTF_8));126 NewSessionResponse newSessionResponse =127 new NewSessionResponse(reqId, sessionResponse.getSession(),128 sessionResponse.getDownstreamEncodedResponse());129 bus.fire(new NewSessionResponseEvent(newSessionResponse));130 } catch (URISyntaxException e) {131 bus.fire(132 new NewSessionRejectedEvent(133 new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));134 }135 }));136 HttpResponse httpResponse = local.addToQueue(request);137 assertThat(isPresent.get()).isTrue();138 assertEquals(httpResponse.getStatus(), HTTP_OK);139 }140 @Test141 public void shouldBeAbleToAddToQueueAndGetErrorResponse() {142 AtomicBoolean isPresent = new AtomicBoolean(false);143 bus.addListener(NewSessionRequestEvent.listener(reqId -> {144 Optional<HttpRequest> sessionRequest = this.local.remove();145 isPresent.set(sessionRequest.isPresent());146 bus.fire(147 new NewSessionRejectedEvent(148 new NewSessionErrorResponse(reqId, "Error")));149 }));150 HttpResponse httpResponse = local.addToQueue(request);151 assertThat(isPresent.get()).isTrue();152 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);153 }154 @Test155 public void shouldBeAbleToAddToQueueRemotelyAndGetErrorResponse() {156 AtomicBoolean isPresent = new AtomicBoolean(false);157 bus.addListener(NewSessionRequestEvent.listener(reqId -> {158 Optional<HttpRequest> sessionRequest = this.remote.remove();159 isPresent.set(sessionRequest.isPresent());160 bus.fire(161 new NewSessionRejectedEvent(162 new NewSessionErrorResponse(reqId, "Could not poll the queue")));163 }));164 HttpResponse httpResponse = remote.addToQueue(request);165 assertThat(isPresent.get()).isTrue();166 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);167 }168 @Test169 public void shouldBeAbleToRemoveFromQueue() {170 Optional<HttpRequest> httpRequest = local.remove();171 assertFalse(httpRequest.isPresent());172 }173 @Test174 public void shouldBeClearQueue() {175 RequestId requestId = new RequestId(UUID.randomUUID());176 sessionQueue.offerLast(request, requestId);177 int count = local.clearQueue();178 assertEquals(count, 1);179 assertFalse(local.remove().isPresent());180 }181 @Test182 public void shouldBeClearQueueRemotely() {183 RequestId requestId = new RequestId(UUID.randomUUID());184 sessionQueue.offerLast(request, requestId);185 int count = remote.clearQueue();186 assertEquals(count, 1);187 assertFalse(remote.remove().isPresent());188 }189 @Test190 public void shouldBeClearQueueAndFireRejectedEvent() {191 AtomicBoolean result = new AtomicBoolean(false);192 RequestId requestId = new RequestId(UUID.randomUUID());193 bus.addListener(NewSessionRejectedEvent.listener(response ->194 result.set(response.getRequestId()195 .equals(requestId))));196 sessionQueue.offerLast(request, requestId);197 int count = remote.clearQueue();198 assertThat(result.get()).isTrue();199 assertEquals(count, 1);200 assertFalse(remote.remove().isPresent());201 }202 @Test203 public void shouldBeAbleToRemoveFromQueueRemotely() {204 Optional<HttpRequest> httpRequest = remote.remove();205 assertFalse(httpRequest.isPresent());206 }207 @Test208 public void shouldBeAbleToAddAgainToQueue() {209 boolean added = local.retryAddToQueue(request, new RequestId(UUID.randomUUID()));210 assertTrue(added);211 }212 @Test213 public void shouldBeAbleToAddAgainToQueueRemotely() {214 HttpRequest request = createRequest(payload, POST, "/se/grid/newsessionqueuer/session");215 boolean added = remote.retryAddToQueue(request, new RequestId(UUID.randomUUID()));216 assertTrue(added);217 }218 @Test219 public void shouldBeAbleToRetryRequest() {220 AtomicBoolean isPresent = new AtomicBoolean(false);221 AtomicBoolean retrySuccess = new AtomicBoolean(false);222 bus.addListener(NewSessionRequestEvent.listener(reqId -> {223 // Keep a count of event fired224 count++;225 Optional<HttpRequest> sessionRequest = this.remote.remove();226 isPresent.set(sessionRequest.isPresent());227 if (count == 1) {228 retrySuccess.set(remote.retryAddToQueue(sessionRequest.get(), reqId));229 }230 // Only if it was retried after an interval, the count is 2231 if (count == 2) {232 ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");233 try {234 SessionId sessionId = new SessionId("123");235 Session session =236 new Session(237 sessionId,238 new URI("http://example.com"),239 caps,240 capabilities,241 Instant.now());242 CreateSessionResponse sessionResponse = new CreateSessionResponse(243 session,244 JSON.toJson(245 ImmutableMap.of(246 "value", ImmutableMap.of(247 "sessionId", sessionId,248 "capabilities", capabilities)))249 .getBytes(UTF_8));250 NewSessionResponse newSessionResponse =251 new NewSessionResponse(reqId, sessionResponse.getSession(),252 sessionResponse.getDownstreamEncodedResponse());253 bus.fire(new NewSessionResponseEvent(newSessionResponse));254 } catch (URISyntaxException e) {255 bus.fire(256 new NewSessionRejectedEvent(257 new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));258 }259 }260 }));261 HttpResponse httpResponse = remote.addToQueue(request);262 assertThat(isPresent.get()).isTrue();263 assertThat(retrySuccess.get()).isTrue();264 assertEquals(httpResponse.getStatus(), HTTP_OK);265 }266 @Test267 public void shouldBeAbleToHandleMultipleSessionRequestsAtTheSameTime() {268 bus.addListener(NewSessionRequestEvent.listener(reqId -> {269 Optional<HttpRequest> sessionRequest = this.local.remove();270 ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome");271 try {272 SessionId sessionId = new SessionId(UUID.randomUUID());273 Session session =274 new Session(275 sessionId,276 new URI("http://example.com"),277 caps,278 capabilities,279 Instant.now());280 CreateSessionResponse sessionResponse = new CreateSessionResponse(281 session,282 JSON.toJson(283 ImmutableMap.of(284 "value", ImmutableMap.of(285 "sessionId", sessionId,286 "capabilities", capabilities)))287 .getBytes(UTF_8));288 NewSessionResponse newSessionResponse =289 new NewSessionResponse(reqId, sessionResponse.getSession(),290 sessionResponse.getDownstreamEncodedResponse());291 bus.fire(new NewSessionResponseEvent(newSessionResponse));292 } catch (URISyntaxException e) {293 bus.fire(294 new NewSessionRejectedEvent(295 new NewSessionErrorResponse(new RequestId(UUID.randomUUID()), "Error")));296 }297 }));298 ExecutorService executor = Executors.newFixedThreadPool(2);299 Callable<HttpResponse> callable = () -> remote.addToQueue(request);300 Future<HttpResponse> firstRequest = executor.submit(callable);301 Future<HttpResponse> secondRequest = executor.submit(callable);302 try {303 HttpResponse firstResponse = firstRequest.get(30, TimeUnit.SECONDS);304 HttpResponse secondResponse = secondRequest.get(30, TimeUnit.SECONDS);305 String firstResponseContents = Contents.string(firstResponse);306 String secondResponseContents = Contents.string(secondResponse);307 assertEquals(firstResponse.getStatus(), HTTP_OK);308 assertEquals(secondResponse.getStatus(), HTTP_OK);309 assertNotEquals(firstResponseContents, secondResponseContents);310 } catch (InterruptedException | ExecutionException | TimeoutException e) {311 fail("Could not create session");312 }313 executor.shutdown();314 }315 @Test316 public void shouldBeAbleToTimeoutARequestOnRetry() {317 Tracer tracer = DefaultTestTracer.createTracer();318 LocalNewSessionQueue sessionQueue = new LocalNewSessionQueue(319 tracer,320 bus,321 Duration.ofSeconds(4),322 Duration.ofSeconds(2));323 local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);324 HttpClient client = new PassthroughHttpClient(local);325 remote = new RemoteNewSessionQueuer(tracer, client);326 HttpRequest request = createRequest(payload, POST, "/session");327 request.addHeader(SESSIONREQUEST_TIMESTAMP_HEADER,328 Long.toString(1539091064));329 AtomicInteger count = new AtomicInteger();330 bus.addListener(NewSessionRequestEvent.listener(reqId -> {331 // Add to front of queue, when retry is triggered it will check if request timed out332 count.incrementAndGet();333 remote.retryAddToQueue(request, reqId);334 }));335 HttpResponse httpResponse = remote.addToQueue(request);336 assertEquals(count.get(),1);337 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);338 }339 @Test340 public void shouldBeAbleToTimeoutARequestOnPoll() {341 Tracer tracer = DefaultTestTracer.createTracer();342 LocalNewSessionQueue sessionQueue = new LocalNewSessionQueue(343 tracer,344 bus,345 Duration.ofSeconds(4),346 Duration.ofSeconds(0));347 local = new LocalNewSessionQueuer(tracer, bus, sessionQueue);348 HttpClient client = new PassthroughHttpClient(local);349 remote = new RemoteNewSessionQueuer(tracer, client);350 AtomicBoolean isPresent = new AtomicBoolean();351 bus.addListener(NewSessionRequestEvent.listener(reqId -> {352 Optional<HttpRequest> request = remote.remove();353 isPresent.set(request.isPresent());354 bus.fire(355 new NewSessionRejectedEvent(356 new NewSessionErrorResponse(reqId, "Error")));357 }));358 HttpResponse httpResponse = remote.addToQueue(request);359 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);360 assertThat(isPresent.get()).isFalse();361 }362 @Test363 public void shouldBeAbleToClearQueueAndRejectMultipleRequests() {364 ExecutorService executor = Executors.newFixedThreadPool(2);365 Callable<HttpResponse> callable = () -> remote.addToQueue(request);366 Future<HttpResponse> firstRequest = executor.submit(callable);367 Future<HttpResponse> secondRequest = executor.submit(callable);368 int count = 0;369 while (count < 2) {370 count += remote.clearQueue();...
Source:LocalNewSessionQueue.java
...16// under the License.17package org.openqa.selenium.grid.sessionqueue.local;18import org.openqa.selenium.events.EventBus;19import org.openqa.selenium.grid.config.Config;20import org.openqa.selenium.grid.data.NewSessionErrorResponse;21import org.openqa.selenium.grid.data.NewSessionRejectedEvent;22import org.openqa.selenium.grid.data.NewSessionRequestEvent;23import org.openqa.selenium.grid.data.RequestId;24import org.openqa.selenium.grid.log.LoggingOptions;25import org.openqa.selenium.grid.server.EventBusOptions;26import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;27import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;28import org.openqa.selenium.internal.Require;29import org.openqa.selenium.remote.http.HttpRequest;30import org.openqa.selenium.remote.http.HttpResponse;31import org.openqa.selenium.remote.tracing.AttributeKey;32import org.openqa.selenium.remote.tracing.EventAttribute;33import org.openqa.selenium.remote.tracing.EventAttributeValue;34import org.openqa.selenium.remote.tracing.Span;35import org.openqa.selenium.remote.tracing.Tracer;36import java.time.Duration;37import java.util.Deque;38import java.util.HashMap;39import java.util.Map;40import java.util.Optional;41import java.util.UUID;42import java.util.concurrent.ConcurrentLinkedDeque;43import java.util.concurrent.Executors;44import java.util.concurrent.ScheduledExecutorService;45import java.util.concurrent.TimeUnit;46import java.util.concurrent.locks.Lock;47import java.util.concurrent.locks.ReadWriteLock;48import java.util.concurrent.locks.ReentrantReadWriteLock;49import java.util.logging.Level;50import java.util.logging.Logger;51public class LocalNewSessionQueue extends NewSessionQueue {52 private static final Logger LOG = Logger.getLogger(LocalNewSessionQueue.class.getName());53 private final EventBus bus;54 private final Deque<HttpRequest> sessionRequests = new ConcurrentLinkedDeque<>();55 private final ReadWriteLock lock = new ReentrantReadWriteLock(true);56 private final ScheduledExecutorService executorService = Executors57 .newSingleThreadScheduledExecutor();58 private final Thread shutdownHook = new Thread(this::callExecutorShutdown);59 public LocalNewSessionQueue(Tracer tracer, EventBus bus, Duration retryInterval,60 Duration requestTimeout) {61 super(tracer, retryInterval, requestTimeout);62 this.bus = Require.nonNull("Event bus", bus);63 Runtime.getRuntime().addShutdownHook(shutdownHook);64 }65 public static NewSessionQueue create(Config config) {66 Tracer tracer = new LoggingOptions(config).getTracer();67 EventBus bus = new EventBusOptions(config).getEventBus();68 Duration retryInterval = new NewSessionQueueOptions(config).getSessionRequestRetryInterval();69 Duration requestTimeout = new NewSessionQueueOptions(config).getSessionRequestTimeout();70 return new LocalNewSessionQueue(tracer, bus, retryInterval, requestTimeout);71 }72 @Override73 public boolean isReady() {74 return bus.isReady();75 }76 @Override77 public boolean offerLast(HttpRequest request, RequestId requestId) {78 Require.nonNull("New Session request", request);79 Span span = tracer.getCurrentContext().createSpan("local_sessionqueue.add");80 boolean added = false;81 Lock writeLock = lock.writeLock();82 writeLock.lock();83 try {84 Map<String, EventAttributeValue> attributeMap = new HashMap<>();85 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),86 EventAttribute.setValue(getClass().getName()));87 added = sessionRequests.offerLast(request);88 addRequestHeaders(request, requestId);89 attributeMap90 .put(AttributeKey.REQUEST_ID.getKey(), EventAttribute.setValue(requestId.toString()));91 attributeMap.put("request.added", EventAttribute.setValue(added));92 span.addEvent("Add new session request to the queue", attributeMap);93 return added;94 } finally {95 writeLock.unlock();96 span.close();97 if (added) {98 bus.fire(new NewSessionRequestEvent(requestId));99 }100 }101 }102 @Override103 public boolean offerFirst(HttpRequest request, RequestId requestId) {104 Require.nonNull("New Session request", request);105 Lock writeLock = lock.writeLock();106 writeLock.lock();107 boolean added = false;108 try {109 added = sessionRequests.offerFirst(request);110 return added;111 } finally {112 writeLock.unlock();113 if (added) {114 executorService.schedule(() -> retryRequest(request, requestId),115 super.retryInterval.getSeconds(), TimeUnit.SECONDS);116 }117 }118 }119 private void retryRequest(HttpRequest request, RequestId requestId) {120 if (hasRequestTimedOut(request)) {121 LOG.log(Level.INFO, "Request {0} timed out", requestId);122 Lock writeLock = lock.writeLock();123 writeLock.lock();124 try {125 sessionRequests.remove();126 } finally {127 writeLock.unlock();128 bus.fire(new NewSessionRejectedEvent(129 new NewSessionErrorResponse(requestId, "New session request timed out")));130 }131 } else {132 LOG.log(Level.INFO,133 "Adding request back to the queue. All slots are busy. Request: {0}",134 requestId);135 bus.fire(new NewSessionRequestEvent(requestId));136 }137 }138 @Override139 public Optional<HttpRequest> poll() {140 Lock writeLock = lock.writeLock();141 writeLock.lock();142 try {143 Optional<HttpRequest> request = Optional.ofNullable(sessionRequests.poll());144 if (request.isPresent()) {145 HttpRequest httpRequest = request.get();146 if (hasRequestTimedOut(httpRequest)) {147 // TODO Fire NewSessionRejectedEvent with timeout message once request id is passed to poll148 return Optional.empty();149 }150 return Optional.of(httpRequest);151 } else {152 return Optional.empty();153 }154 } finally {155 writeLock.unlock();156 }157 }158 @Override159 public int clear() {160 Lock writeLock = lock.writeLock();161 writeLock.lock();162 try {163 int count = 0;164 LOG.info("Clearing new session request queue");165 for (HttpRequest request = sessionRequests.poll(); request != null;166 request = sessionRequests.poll()) {167 count++;168 UUID reqId = UUID.fromString(request.getHeader(SESSIONREQUEST_ID_HEADER));169 NewSessionErrorResponse errorResponse =170 new NewSessionErrorResponse(new RequestId(reqId), "New session request cancelled.");171 bus.fire(new NewSessionRejectedEvent(errorResponse));172 }173 return count;174 } finally {175 writeLock.unlock();176 }177 }178 public void callExecutorShutdown() {179 LOG.info("Shutting down session queue executor service");180 executorService.shutdown();181 }182}...
Source:GetNewSessionResponse.java
...16// under the License.17package org.openqa.selenium.grid.sessionqueue;18import com.google.common.collect.ImmutableMap;19import org.openqa.selenium.events.EventBus;20import org.openqa.selenium.grid.data.NewSessionErrorResponse;21import org.openqa.selenium.grid.data.NewSessionRejectedEvent;22import org.openqa.selenium.grid.data.NewSessionRequest;23import org.openqa.selenium.grid.data.NewSessionResponse;24import org.openqa.selenium.grid.data.NewSessionResponseEvent;25import org.openqa.selenium.grid.data.RequestId;26import org.openqa.selenium.internal.Require;27import org.openqa.selenium.remote.http.HttpRequest;28import org.openqa.selenium.remote.http.HttpResponse;29import org.openqa.selenium.remote.tracing.Tracer;30import java.util.Map;31import java.util.Optional;32import java.util.UUID;33import java.util.concurrent.ConcurrentHashMap;34import java.util.concurrent.CountDownLatch;35import java.util.logging.Level;36import java.util.logging.Logger;37import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;38import static org.openqa.selenium.remote.http.Contents.asJson;39import static org.openqa.selenium.remote.http.Contents.bytes;40public class GetNewSessionResponse {41 private static final Logger LOG = Logger.getLogger(GetNewSessionResponse.class.getName());42 private final EventBus bus;43 private final Tracer tracer;44 private final NewSessionQueue sessionRequests;45 private final Map<RequestId, NewSessionRequest> knownRequests = new ConcurrentHashMap<>();46 public GetNewSessionResponse(Tracer tracer, EventBus bus,47 NewSessionQueue sessionRequests) {48 this.tracer = Require.nonNull("Tracer", tracer);49 this.bus = Require.nonNull("Event bus", bus);50 this.sessionRequests = Require.nonNull("New Session Request Queue", sessionRequests);51 this.bus.addListener(NewSessionResponseEvent.listener(sessionResponse -> {52 try {53 this.setResponse(sessionResponse);54 } catch (Exception ignore) {55 // Ignore any exception. Do not want to block the eventbus thread.56 }57 }));58 this.bus.addListener(NewSessionRejectedEvent.listener(sessionResponse -> {59 try {60 this.setErrorResponse(sessionResponse);61 } catch (Exception ignore) {62 // Ignore any exception. Do not want to block the eventbus thread.63 }64 }));65 }66 private void setResponse(NewSessionResponse sessionResponse) {67 // Each thread will get its own CountDownLatch and it is stored in the Map using request id as the key.68 // EventBus thread will retrieve the same request and set it's response and unblock waiting request thread.69 RequestId id = sessionResponse.getRequestId();70 Optional<NewSessionRequest> sessionRequest = Optional.ofNullable(knownRequests.get(id));71 if (sessionRequest.isPresent()) {72 NewSessionRequest request = sessionRequest.get();73 request.setSessionResponse(74 new HttpResponse().setContent(bytes(sessionResponse.getDownstreamEncodedResponse())));75 request.getLatch().countDown();76 }77 }78 private void setErrorResponse(NewSessionErrorResponse sessionResponse) {79 RequestId id = sessionResponse.getRequestId();80 Optional<NewSessionRequest> sessionRequest = Optional.ofNullable(knownRequests.get(id));81 // There could be a situation where the session request in the queue is scheduled for retry.82 // Meanwhile the request queue is cleared.83 // This will fire a error response event and remove the request id from the knownRequests map.84 // Another error response event will be fired by the Distributor when the request is retried.85 // Since a response is already provided for the request, the event listener should not take any action.86 if (sessionRequest.isPresent()) {87 NewSessionRequest request = sessionRequest.get();88 request89 .setSessionResponse(new HttpResponse()90 .setStatus(HTTP_INTERNAL_ERROR)91 .setContent(asJson(92 ImmutableMap.of("message", sessionResponse.getMessage()))));...
Source:NewSessionErrorResponse.java
...19import org.openqa.selenium.json.JsonInput;20import java.util.Map;21import java.util.TreeMap;22import static java.util.Collections.unmodifiableMap;23public class NewSessionErrorResponse {24 private final String message;25 private final RequestId requestId;26 public NewSessionErrorResponse(RequestId requestId, String message) {27 this.requestId = Require.nonNull("Request Id", requestId);28 this.message = Require.nonNull("Message", message);29 }30 public String getMessage() {31 return message;32 }33 public RequestId getRequestId() {34 return requestId;35 }36 private Map<String, Object> toJson() {37 Map<String, Object> toReturn = new TreeMap<>();38 toReturn.put("message", message);39 toReturn.put("requestId", requestId);40 return unmodifiableMap(toReturn);41 }42 private static NewSessionErrorResponse fromJson(JsonInput input) {43 String message = null;44 RequestId requestId = null;45 input.beginObject();46 while (input.hasNext()) {47 switch (input.nextName()) {48 case "message":49 message = input.read(String.class);50 break;51 case "requestId":52 requestId = input.read(RequestId.class);53 break;54 default:55 input.skipValue();56 break;57 }58 }59 input.endObject();60 return new NewSessionErrorResponse(requestId, message);61 }62}...
Source:NewSessionRejectedEvent.java
...21import org.openqa.selenium.internal.Require;22import java.util.function.Consumer;23public class NewSessionRejectedEvent extends Event {24 private static final EventName NEW_SESSION_REJECTED = new EventName("new-session-rejected");25 public NewSessionRejectedEvent(NewSessionErrorResponse response) {26 super(NEW_SESSION_REJECTED, response);27 }28 public static EventListener<NewSessionErrorResponse> listener(Consumer<NewSessionErrorResponse> handler) {29 Require.nonNull("Handler", handler);30 return new EventListener<>(NEW_SESSION_REJECTED, NewSessionErrorResponse.class, handler);31 }32}...
NewSessionErrorResponse
Using AI Code Generation
1import org.openqa.selenium.grid.data.NewSessionErrorResponse;2import org.openqa.selenium.grid.data.NewSessionError;3import org.openqa.selenium.grid.data.NewSessionResponse;4import org.openqa.selenium.grid.data.NewSessionResponseCodec;5import org.openqa.selenium.grid.data.NewSessionResponse;6import org.openqa.selenium.grid.data.NewSessionResponseCodec;7import org.openqa.selenium.grid.data.NewSessionResponse;8import org.openqa.selenium.grid.data.NewSessionResponseCodec;9import org.openqa.selenium.grid.data.NewSessionResponse;10import org.openqa.selenium.grid.data.NewSessionResponseCodec;11import org.openqa.selenium.grid.data.NewSessionResponse;12import org.openqa.selenium.grid.data.NewSessionResponseCodec;13import org.openqa.selenium.grid.data.NewSessionResponse;14import org.openqa.selenium.grid.data.NewSessionResponseCodec;15import org.openqa.selenium.grid.data.NewSessionResponse;16import org.openqa.selenium.grid.data.NewSessionResponseCodec;17import org.openqa.selenium.grid.data.NewSessionResponse;18import org.openqa.selenium.grid.data.NewSessionResponseCodec;19import org.openqa.selenium.grid.data.NewSessionResponse;
NewSessionErrorResponse
Using AI Code Generation
1import org.openqa.selenium.grid.data.NewSessionErrorResponse;2import org.openqa.selenium.grid.data.NewSessionResponse;3import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;4import org.openqa.selenium.grid.web.Values;5import org.openqa.selenium.remote.http.HttpRequest;6import org.openqa.selenium.remote.http.HttpResponse;7import org.openqa.selenium.remote.http.Route;8import org.openqa.selenium.remote.tracing.Tracer;9import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;10import java.util.Objects;11import java.util.Optional;12import java.util.function.Predicate;13import java.util.function.Supplier;14import static org.openqa.selenium.remote.http.Contents.asJson;15import static org.openqa.selenium.remote.http.Contents.utf8String;16import static org.openqa.selenium.remote.http.Route.combine;17import static org.openqa.selenium.remote.http.Route.get;18import static org.openqa.selenium.remote.http.Route.post;19public class NewSession implements Route {20 private final Tracer tracer;21 private final SessionMapOptions sessionMapOptions;22 private final Supplier<NewSessionResponse> newSessionResponseSupplier;23 public NewSession(24 Supplier<NewSessionResponse> newSessionResponseSupplier) {25 this.tracer = Objects.requireNonNull(tracer);26 this.sessionMapOptions = Objects.requireNonNull(sessionMapOptions);27 this.newSessionResponseSupplier = Objects.requireNonNull(newSessionResponseSupplier);28 }29 public Predicate<HttpRequest> getMatches() {30 return Route.combine(31 get("/status").or(post("/session")),32 (req) -> Values.get(req, "query", "protocol").isPresent());33 }34 public HttpResponse execute(HttpRequest req) {35 Optional<String> protocol = Values.get(req, "query", "protocol");36 if (protocol.isEmpty()) {37 return new HttpResponse()38 .setStatus(400)39 .setContent(utf8String("Missing protocol"));40 }41 if (!protocol.get().equals("webdriver")) {42 return new HttpResponse()43 .setStatus(400)44 .setContent(utf8String("Unsupported protocol: " + protocol.get()));45 }46 NewSessionResponse response;47 try {48 response = newSessionResponseSupplier.get();49 } catch (Exception e) {50 OpenTelemetryTracer tracer = (OpenTelemetryTracer) this.tracer;51 tracer.getCurrentContext().with(tracer.spanBuilder("NewSession").startSpan()).end();52 return new HttpResponse()
NewSessionErrorResponse
Using AI Code Generation
1import org.openqa.selenium.grid.data.NewSessionErrorResponse;2import org.openqa.selenium.remote.http.HttpResponse;3import org.openqa.selenium.remote.http.JsonHttpResponse;4HttpResponse response = new JsonHttpResponse().setContent(new NewSessionErrorResponse("error message"));5System.out.println(response.getContentString());6{7 "value" : {8 }9}10{11 "value" : {12 }13}14Example 3: [Python]: # Language: python # # This code is in the Public Domain # # Author: Anshul Verma # # Description: Example to use NewSessionErrorResponse class of org.openqa.selenium.grid.data package from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.remote.command import Command from selenium.webdriver.remote.remote_connection import RemoteConnection from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time from selenium.webdriver.remote.command import Command from selenium.webdriver.remote.remote_connection import RemoteConnection from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.remote.command import Command from selenium.webdriver.remote.remote_connection import RemoteConnection from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time from selenium.webdriver.support.ui import WebDriverWait from selenium
NewSessionErrorResponse
Using AI Code Generation
1import org.openqa.selenium.grid.data.NewSessionErrorResponse;2NewSessionErrorResponse.newSessionErrorResponse("error message");3import org.openqa.selenium.grid.data.NewSessionErrorResponse;4NewSessionErrorResponse.newSessionErrorResponse("error message");5from org.openqa.selenium.grid.data import NewSessionErrorResponse6NewSessionErrorResponse.newSessionErrorResponse("error message")7NewSessionErrorResponse.newSessionErrorResponse("error message")8use org.openqa.selenium.grid.data.NewSessionErrorResponse;9NewSessionErrorResponse::newSessionErrorResponse("error message");10using org.openqa.selenium.grid.data;11NewSessionErrorResponse.newSessionErrorResponse("error message");12import org.openqa.selenium.grid.data.NewSessionErrorResponse13NewSessionErrorResponse.newSessionErrorResponse("error message")14import org.openqa.selenium.grid.data.NewSessionErrorResponse15NewSessionErrorResponse.newSessionErrorResponse("error message")16import org.openqa.selenium.grid.data.NewSessionErrorResponse;17NewSessionErrorResponse.newSessionErrorResponse("error message");18import org.openqa.selenium.grid.data.NewSessionErrorResponse;19NewSessionErrorResponse.newSessionErrorResponse("error message");20import org.openqa.selenium.grid.data.NewSessionErrorResponse21NewSessionErrorResponse.newSessionErrorResponse("error message")22import org.openqa.selenium.grid.data.NewSessionErrorResponse23NewSessionErrorResponse.newSessionErrorResponse("error message")24import org.openqa.selenium.grid
NewSessionErrorResponse
Using AI Code Generation
1package com.automationrhapsody.selenium.grid;2import org.openqa.selenium.grid.data.NewSessionErrorResponse;3import org.openqa.selenium.grid.data.NewSessionError;4import org.openqa.selenium.remote.ErrorCodes;5public class NewSessionErrorResponseExample {6 public static void main(String[] args) {7 NewSessionErrorResponse response = new NewSessionErrorResponse(8 new NewSessionError(ErrorCodes.SESSION_NOT_CREATED,9 "Session cannot be created due to error"));10 System.out.println(response);11 }12}13{14 "value" : {15 }16}
NewSessionErrorResponse
Using AI Code Generation
1public class NewSessionErrorResponse extends Response {2 public NewSessionErrorResponse(String message) {3 super(new AppiumResponseCodec(), new AppiumResponse(message));4 }5}6package com.selenium4beginners.java.webdriver;7import org.openqa.selenium.By;8import org.openqa.selenium.WebDriver;9import org.openqa.selenium.WebElement;10import org.openqa.selenium.chrome.ChromeDriver;11import org.openqa.selenium.grid.data.NewSessionErrorResponse;12public class CustomErrorResponse {13 public static void main(String[] args) {14 System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");15 WebDriver driver = new ChromeDriver();16 WebElement submitButton = driver.findElement(By.name("submit"));17 submitButton.click();18 NewSessionErrorResponse errorResponse = new NewSessionErrorResponse("Username and Password is required");19 System.out.println(errorResponse.getMessage());20 driver.quit();21 }22}
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!!