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

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

Source:NewSessionQueuerTest.java Github

copy

Full Screen

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

Full Screen

Full Screen

Source:LocalDistributor.java Github

copy

Full Screen

...30import org.openqa.selenium.grid.data.DistributorStatus;31import org.openqa.selenium.grid.data.NewSessionErrorResponse;32import org.openqa.selenium.grid.data.NewSessionRejectedEvent;33import org.openqa.selenium.grid.data.NewSessionRequestEvent;34import org.openqa.selenium.grid.data.NewSessionResponse;35import org.openqa.selenium.grid.data.NewSessionResponseEvent;36import org.openqa.selenium.grid.data.NodeAddedEvent;37import org.openqa.selenium.grid.data.NodeDrainComplete;38import org.openqa.selenium.grid.data.NodeHeartBeatEvent;39import org.openqa.selenium.grid.data.NodeId;40import org.openqa.selenium.grid.data.NodeStatus;41import org.openqa.selenium.grid.data.NodeStatusEvent;42import org.openqa.selenium.grid.data.RequestId;43import org.openqa.selenium.grid.data.Slot;44import org.openqa.selenium.grid.data.SlotId;45import org.openqa.selenium.grid.distributor.Distributor;46import org.openqa.selenium.grid.distributor.config.DistributorOptions;47import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;48import org.openqa.selenium.grid.log.LoggingOptions;49import org.openqa.selenium.grid.node.HealthCheck;50import org.openqa.selenium.grid.node.Node;51import org.openqa.selenium.grid.node.remote.RemoteNode;52import org.openqa.selenium.grid.security.Secret;53import org.openqa.selenium.grid.security.SecretOptions;54import org.openqa.selenium.grid.server.EventBusOptions;55import org.openqa.selenium.grid.server.NetworkOptions;56import org.openqa.selenium.grid.sessionmap.SessionMap;57import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;58import org.openqa.selenium.grid.sessionqueue.NewSessionQueuer;59import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueuerOptions;60import org.openqa.selenium.internal.Either;61import org.openqa.selenium.internal.Require;62import org.openqa.selenium.remote.http.HttpClient;63import org.openqa.selenium.remote.http.HttpRequest;64import org.openqa.selenium.remote.tracing.AttributeKey;65import org.openqa.selenium.remote.tracing.EventAttribute;66import org.openqa.selenium.remote.tracing.EventAttributeValue;67import org.openqa.selenium.remote.tracing.Span;68import org.openqa.selenium.remote.tracing.Tracer;69import org.openqa.selenium.status.HasReadyState;70import java.time.Duration;71import java.util.ArrayList;72import java.util.HashMap;73import java.util.List;74import java.util.Map;75import java.util.Optional;76import java.util.Queue;77import java.util.Set;78import java.util.concurrent.ConcurrentHashMap;79import java.util.concurrent.ConcurrentLinkedQueue;80import java.util.concurrent.Executors;81import java.util.concurrent.ScheduledExecutorService;82import java.util.concurrent.ThreadFactory;83import java.util.concurrent.TimeUnit;84import java.util.concurrent.locks.Lock;85import java.util.concurrent.locks.ReadWriteLock;86import java.util.concurrent.locks.ReentrantReadWriteLock;87import java.util.logging.Level;88import java.util.logging.Logger;89import static com.google.common.collect.ImmutableSet.toImmutableSet;90import static org.openqa.selenium.grid.data.Availability.DOWN;91import static org.openqa.selenium.grid.data.Availability.DRAINING;92import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;93public class LocalDistributor extends Distributor {94 private static final Logger LOG = Logger.getLogger(LocalDistributor.class.getName());95 private final Tracer tracer;96 private final EventBus bus;97 private final HttpClient.Factory clientFactory;98 private final SessionMap sessions;99 private final Secret registrationSecret;100 private final Regularly hostChecker = new Regularly("distributor host checker");101 private final Map<NodeId, Runnable> allChecks = new HashMap<>();102 private final Queue<RequestId> requestIds = new ConcurrentLinkedQueue<>();103 private final ScheduledExecutorService executorService;104 private final Duration healthcheckInterval;105 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);106 private final GridModel model;107 private final Map<NodeId, Node> nodes;108 private final NewSessionQueuer sessionRequests;109 public LocalDistributor(110 Tracer tracer,111 EventBus bus,112 HttpClient.Factory clientFactory,113 SessionMap sessions,114 NewSessionQueuer sessionRequests,115 Secret registrationSecret,116 Duration healthcheckInterval) {117 super(tracer, clientFactory, new DefaultSlotSelector(), sessions, registrationSecret);118 this.tracer = Require.nonNull("Tracer", tracer);119 this.bus = Require.nonNull("Event bus", bus);120 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);121 this.sessions = Require.nonNull("Session map", sessions);122 this.model = new GridModel(bus);123 this.nodes = new ConcurrentHashMap<>();124 this.sessionRequests = Require.nonNull("New Session Request Queue", sessionRequests);125 this.registrationSecret = Require.nonNull("Registration secret", registrationSecret);126 this.healthcheckInterval = Require.nonNull("Health check interval", healthcheckInterval);127 bus.addListener(NodeStatusEvent.listener(this::register));128 bus.addListener(NodeStatusEvent.listener(model::refresh));129 bus.addListener(NodeHeartBeatEvent.listener(nodeStatus -> {130 if (nodes.containsKey(nodeStatus.getId())) {131 model.touch(nodeStatus.getId());132 } else {133 register(nodeStatus);134 }135 }));136 bus.addListener(NodeDrainComplete.listener(this::remove));137 bus.addListener(NewSessionRequestEvent.listener(requestIds::offer));138 Regularly regularly = new Regularly("Local Distributor");139 regularly.submit(model::purgeDeadNodes, Duration.ofSeconds(30), Duration.ofSeconds(30));140 Thread shutdownHook = new Thread(this::callExecutorShutdown);141 Runtime.getRuntime().addShutdownHook(shutdownHook);142 NewSessionRunnable runnable = new NewSessionRunnable();143 ThreadFactory threadFactory = r -> {144 Thread thread = new Thread(r);145 thread.setName("New Session Creation");146 thread.setDaemon(true);147 return thread;148 };149 executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);150 executorService.scheduleAtFixedRate(runnable, 0, 1000, TimeUnit.MILLISECONDS);151 }152 public static Distributor create(Config config) {153 Tracer tracer = new LoggingOptions(config).getTracer();154 EventBus bus = new EventBusOptions(config).getEventBus();155 DistributorOptions distributorOptions = new DistributorOptions(config);156 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);157 SessionMap sessions = new SessionMapOptions(config).getSessionMap();158 SecretOptions secretOptions = new SecretOptions(config);159 NewSessionQueuer sessionRequests =160 new NewSessionQueuerOptions(config).getSessionQueuer(161 "org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueuer");162 return new LocalDistributor(163 tracer,164 bus,165 clientFactory,166 sessions,167 sessionRequests,168 secretOptions.getRegistrationSecret(),169 distributorOptions.getHealthCheckInterval());170 }171 @Override172 public boolean isReady() {173 try {174 return ImmutableSet.of(bus, sessions).parallelStream()175 .map(HasReadyState::isReady)176 .reduce(true, Boolean::logicalAnd);177 } catch (RuntimeException e) {178 return false;179 }180 }181 private void register(NodeStatus status) {182 Require.nonNull("Node", status);183 Lock writeLock = lock.writeLock();184 writeLock.lock();185 try {186 if (nodes.containsKey(status.getId())) {187 return;188 }189 Set<Capabilities> capabilities = status.getSlots().stream()190 .map(Slot::getStereotype)191 .map(ImmutableCapabilities::copyOf)192 .collect(toImmutableSet());193 // A new node! Add this as a remote node, since we've not called add194 RemoteNode remoteNode = new RemoteNode(195 tracer,196 clientFactory,197 status.getId(),198 status.getUri(),199 registrationSecret,200 capabilities);201 add(remoteNode);202 } finally {203 writeLock.unlock();204 }205 }206 @Override207 public LocalDistributor add(Node node) {208 Require.nonNull("Node", node);209 LOG.info(String.format("Added node %s at %s.", node.getId(), node.getUri()));210 nodes.put(node.getId(), node);211 model.add(node.getStatus());212 // Extract the health check213 Runnable runnableHealthCheck = asRunnableHealthCheck(node);214 allChecks.put(node.getId(), runnableHealthCheck);215 hostChecker.submit(runnableHealthCheck, healthcheckInterval, Duration.ofSeconds(30));216 bus.fire(new NodeAddedEvent(node.getId()));217 return this;218 }219 private Runnable asRunnableHealthCheck(Node node) {220 HealthCheck healthCheck = node.getHealthCheck();221 NodeId id = node.getId();222 return () -> {223 HealthCheck.Result result;224 try {225 result = healthCheck.check();226 } catch (Exception e) {227 LOG.log(Level.WARNING, "Unable to process node " + id, e);228 result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");229 }230 Lock writeLock = lock.writeLock();231 writeLock.lock();232 try {233 model.setAvailability(id, result.getAvailability());234 } finally {235 writeLock.unlock();236 }237 };238 }239 @Override240 public boolean drain(NodeId nodeId) {241 Node node = nodes.get(nodeId);242 if (node == null) {243 LOG.info("Asked to drain unregistered node " + nodeId);244 return false;245 }246 Lock writeLock = lock.writeLock();247 writeLock.lock();248 try {249 node.drain();250 model.setAvailability(nodeId, DRAINING);251 } finally {252 writeLock.unlock();253 }254 return node.isDraining();255 }256 public void remove(NodeId nodeId) {257 Lock writeLock = lock.writeLock();258 writeLock.lock();259 try {260 model.remove(nodeId);261 Runnable runnable = allChecks.remove(nodeId);262 if (runnable != null) {263 hostChecker.remove(runnable);264 }265 } finally {266 writeLock.unlock();267 }268 }269 @Override270 public DistributorStatus getStatus() {271 Lock readLock = this.lock.readLock();272 readLock.lock();273 try {274 return new DistributorStatus(model.getSnapshot());275 } finally {276 readLock.unlock();277 }278 }279 @Beta280 public void refresh() {281 List<Runnable> allHealthChecks = new ArrayList<>();282 Lock readLock = this.lock.readLock();283 readLock.lock();284 try {285 allHealthChecks.addAll(allChecks.values());286 } finally {287 readLock.unlock();288 }289 allHealthChecks.parallelStream().forEach(Runnable::run);290 }291 @Override292 protected Set<NodeStatus> getAvailableNodes() {293 Lock readLock = this.lock.readLock();294 readLock.lock();295 try {296 return model.getSnapshot().stream()297 .filter(node -> !DOWN.equals(node.getAvailability()))298 .collect(toImmutableSet());299 } finally {300 readLock.unlock();301 }302 }303 @Override304 protected Either<SessionNotCreatedException, CreateSessionResponse> reserve(SlotId slotId, CreateSessionRequest request) {305 Require.nonNull("Slot ID", slotId);306 Require.nonNull("New Session request", request);307 Lock writeLock = this.lock.writeLock();308 writeLock.lock();309 try {310 Node node = nodes.get(slotId.getOwningNodeId());311 if (node == null) {312 return Either.left(new RetrySessionRequestException(313 "Unable to find node. Try a different node"));314 }315 model.reserve(slotId);316 Either<WebDriverException, CreateSessionResponse> response = node.newSession(request);317 if (response.isRight()) {318 model.setSession(slotId, response.right().getSession());319 return Either.right(response.right());320 } else {321 model.setSession(slotId, null);322 WebDriverException exception = response.left();323 if (exception instanceof RetrySessionRequestException) {324 return Either.left(new RetrySessionRequestException(exception.getMessage()));325 } else {326 return Either.left(new SessionNotCreatedException(exception.getMessage()));327 }328 }329 } finally {330 writeLock.unlock();331 }332 }333 public void callExecutorShutdown() {334 LOG.info("Shutting down Distributor executor service");335 executorService.shutdownNow();336 }337 public class NewSessionRunnable implements Runnable {338 @Override339 public void run() {340 Lock writeLock = lock.writeLock();341 writeLock.lock();342 try {343 if (!requestIds.isEmpty()) {344 Set<NodeStatus> availableNodes = ImmutableSet.copyOf(getAvailableNodes());345 boolean hasCapacity = availableNodes.stream()346 .anyMatch(NodeStatus::hasCapacity);347 if (hasCapacity) {348 RequestId reqId = requestIds.poll();349 if (reqId != null) {350 Optional<HttpRequest> optionalHttpRequest = sessionRequests.remove(reqId);351 // Check if polling the queue did not return null352 if (optionalHttpRequest.isPresent()) {353 handleNewSessionRequest(optionalHttpRequest.get(), reqId);354 } else {355 fireSessionRejectedEvent(356 "Unable to poll request from the new session request queue.",357 reqId);358 }359 }360 }361 }362 } finally {363 writeLock.unlock();364 }365 }366 private void handleNewSessionRequest(HttpRequest sessionRequest, RequestId reqId) {367 try (Span span = newSpanAsChildOf(tracer, sessionRequest, "distributor.poll_queue")) {368 Map<String, EventAttributeValue> attributeMap = new HashMap<>();369 attributeMap.put(370 AttributeKey.LOGGER_CLASS.getKey(),371 EventAttribute.setValue(getClass().getName()));372 span.setAttribute(AttributeKey.REQUEST_ID.getKey(), reqId.toString());373 attributeMap.put(374 AttributeKey.REQUEST_ID.getKey(),375 EventAttribute.setValue(reqId.toString()));376 attributeMap.put("request", EventAttribute.setValue(sessionRequest.toString()));377 Either<SessionNotCreatedException, CreateSessionResponse> response =378 newSession(sessionRequest);379 if (response.isRight()) {380 CreateSessionResponse sessionResponse = response.right();381 NewSessionResponse newSessionResponse =382 new NewSessionResponse(383 reqId,384 sessionResponse.getSession(),385 sessionResponse.getDownstreamEncodedResponse());386 bus.fire(new NewSessionResponseEvent(newSessionResponse));387 } else {388 SessionNotCreatedException exception = response.left();389 if (exception instanceof RetrySessionRequestException) {390 boolean retried = sessionRequests.retryAddToQueue(sessionRequest, reqId);391 attributeMap.put("request.retry_add", EventAttribute.setValue(retried));392 span.addEvent("Retry adding to front of queue. No slot available.", attributeMap);393 if (!retried) {394 span.addEvent("Retry adding to front of queue failed.", attributeMap);395 fireSessionRejectedEvent(exception.getMessage(), reqId);396 }397 } else {398 fireSessionRejectedEvent(exception.getMessage(), reqId);399 }400 }...

Full Screen

Full Screen

Source:GetNewSessionResponse.java Github

copy

Full Screen

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

Full Screen

Full Screen

Source:NewSessionResponse.java Github

copy

Full Screen

...19import org.openqa.selenium.internal.Require;20import org.openqa.selenium.json.JsonInput;21import java.util.Base64;22import java.util.Map;23public class NewSessionResponse {24 private final RequestId requestId;25 private final Session session;26 private final byte[] downstreamEncodedResponse;27 public NewSessionResponse(RequestId requestId, Session session,28 byte[] downstreamEncodedResponse) {29 this.requestId = Require.nonNull("Request Id", requestId);30 this.session = Require.nonNull("Session", session);31 this.downstreamEncodedResponse = Require.nonNull32 ("Downstream encoded response", downstreamEncodedResponse);33 }34 public RequestId getRequestId() {35 return requestId;36 }37 public Session getSession() {38 return session;39 }40 public byte[] getDownstreamEncodedResponse() {41 return downstreamEncodedResponse;42 }43 private Map<String, Object> toJson() {44 return ImmutableMap.of(45 "requestId", requestId,46 "session", session,47 "downstreamEncodedResponse", Base64.getEncoder().encodeToString(downstreamEncodedResponse)48 );49 }50 private static NewSessionResponse fromJson(JsonInput input) {51 RequestId requestId = null;52 Session session = null;53 byte[] downstreamResponse = null;54 input.beginObject();55 while (input.hasNext()) {56 switch (input.nextName()) {57 case "requestId":58 requestId = input.read(RequestId.class);59 break;60 case "session":61 session = input.read(Session.class);62 break;63 case "downstreamEncodedResponse":64 downstreamResponse = Base64.getDecoder().decode(input.nextString());65 break;66 default:67 input.skipValue();68 break;69 }70 }71 input.endObject();72 return new NewSessionResponse(requestId, session, downstreamResponse);73 }74}...

Full Screen

Full Screen

Source:NewSessionResponseEvent.java Github

copy

Full Screen

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

Full Screen

Full Screen

NewSessionResponse

Using AI Code Generation

copy

Full Screen

1package org.openqa.selenium.grid.data;2import com.google.common.collect.ImmutableMap;3import java.util.Map;4import java.util.Objects;5import java.util.UUID;6public class NewSessionResponse {7 private final Session session;8 private final Map<String, Object> value;9 public NewSessionResponse(Session session, Map<String, Object> value) {10 this.session = Objects.requireNonNull(session);11 this.value = ImmutableMap.copyOf(Objects.requireNonNull(value));12 }13 public Session getSession() {14 return session;15 }16 public Map<String, Object> getValue() {17 return value;18 }19 public Map<String, Object> toJson() {20 Map<String, Object> toReturn = ImmutableMap.<String, Object>builder()21 .put("sessionId", session.getId().toString())22 .put("capabilities", value)23 .build();24 return toReturn;25 }26 public static NewSessionResponse fromJson(Map<String, Object> raw) {27 Map<String, Object> capabilities = (Map<String, Object>) raw.get("capabilities");28 UUID id = UUID.fromString((String) raw.get("sessionId"));29 Session session = new Session(id, capabilities);30 return new NewSessionResponse(session, capabilities);31 }32}33package com.automationrhapsody.junit5;34import org.junit.jupiter.api.Assertions;35import org.junit.jupiter.api.Test;36import org.openqa.selenium.grid.data.NewSessionResponse;37import org.openqa.selenium.remote.http.HttpClient;38import org.openqa.selenium.remote.http.HttpRequest;39import org.openqa.selenium.remote.http.HttpResponse;40import java.io.IOException;

Full Screen

Full Screen

NewSessionResponse

Using AI Code Generation

copy

Full Screen

1package com.example;2import org.openqa.selenium.grid.data.NewSessionResponse;3public class Example {4 public static void main(String[] args) {5 NewSessionResponse response = new NewSessionResponse();6 System.out.println("Hello, World!");7 }8}

Full Screen

Full Screen

Selenium 4 Tutorial:

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

Chapters:

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

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

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

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

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

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

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

Selenium 101 certifications:

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

Run Selenium automation tests on LambdaTest cloud grid

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

Most used methods in NewSessionResponse

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful