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

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

Source:NewSessionQueuerTest.java Github

copy

Full Screen

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

Full Screen

Full Screen

Source:RemoteNode.java Github

copy

Full Screen

...18import com.google.common.collect.ImmutableMap;19import com.google.common.collect.ImmutableSet;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.NoSuchSessionException;22import org.openqa.selenium.grid.data.CreateSessionRequest;23import org.openqa.selenium.grid.data.CreateSessionResponse;24import org.openqa.selenium.grid.data.NodeId;25import org.openqa.selenium.grid.data.NodeStatus;26import org.openqa.selenium.grid.data.Session;27import org.openqa.selenium.grid.node.HealthCheck;28import org.openqa.selenium.grid.node.Node;29import org.openqa.selenium.grid.security.AddSecretFilter;30import org.openqa.selenium.grid.security.Secret;31import org.openqa.selenium.grid.web.Values;32import org.openqa.selenium.internal.Require;33import org.openqa.selenium.json.Json;34import org.openqa.selenium.json.JsonInput;35import org.openqa.selenium.remote.SessionId;36import org.openqa.selenium.remote.http.Filter;37import org.openqa.selenium.remote.http.HttpClient;38import org.openqa.selenium.remote.http.HttpHandler;39import org.openqa.selenium.remote.http.HttpRequest;40import org.openqa.selenium.remote.http.HttpResponse;41import org.openqa.selenium.remote.tracing.HttpTracing;42import org.openqa.selenium.remote.tracing.Tracer;43import java.io.IOException;44import java.io.Reader;45import java.io.UncheckedIOException;46import java.net.URI;47import java.util.Collection;48import java.util.Map;49import java.util.Objects;50import java.util.Optional;51import java.util.Set;52import static java.net.HttpURLConnection.HTTP_OK;53import static org.openqa.selenium.grid.data.Availability.DOWN;54import static org.openqa.selenium.grid.data.Availability.DRAINING;55import static org.openqa.selenium.grid.data.Availability.UP;56import static org.openqa.selenium.net.Urls.fromUri;57import static org.openqa.selenium.remote.http.Contents.asJson;58import static org.openqa.selenium.remote.http.Contents.reader;59import static org.openqa.selenium.remote.http.HttpMethod.DELETE;60import static org.openqa.selenium.remote.http.HttpMethod.GET;61import static org.openqa.selenium.remote.http.HttpMethod.POST;62public class RemoteNode extends Node {63 public static final Json JSON = new Json();64 private final HttpHandler client;65 private final URI externalUri;66 private final Set<Capabilities> capabilities;67 private final HealthCheck healthCheck;68 private final Filter addSecret;69 public RemoteNode(70 Tracer tracer,71 HttpClient.Factory clientFactory,72 NodeId id,73 URI externalUri,74 Secret registrationSecret,75 Collection<Capabilities> capabilities) {76 super(tracer, id, externalUri, registrationSecret);77 this.externalUri = Require.nonNull("External URI", externalUri);78 this.capabilities = ImmutableSet.copyOf(capabilities);79 this.client = Require.nonNull("HTTP client factory", clientFactory).createClient(fromUri(externalUri));80 this.healthCheck = new RemoteCheck();81 Require.nonNull("Registration secret", registrationSecret);82 this.addSecret = new AddSecretFilter(registrationSecret);83 }84 @Override85 public boolean isReady() {86 try {87 return client.execute(new HttpRequest(GET, "/readyz")).isSuccessful();88 } catch (Exception e) {89 return false;90 }91 }92 @Override93 public boolean isSupporting(Capabilities capabilities) {94 return this.capabilities.stream()95 .anyMatch(caps -> caps.getCapabilityNames().stream()96 .allMatch(name -> Objects.equals(97 caps.getCapability(name),98 capabilities.getCapability(name))));99 }100 @Override101 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {102 Require.nonNull("Capabilities for session", sessionRequest);103 HttpRequest req = new HttpRequest(POST, "/se/grid/node/session");104 HttpTracing.inject(tracer, tracer.getCurrentContext(), req);105 req.setContent(asJson(sessionRequest));106 HttpResponse res = client.with(addSecret).execute(req);107 return Optional.ofNullable(Values.get(res, CreateSessionResponse.class));108 }109 @Override110 public boolean isSessionOwner(SessionId id) {111 Require.nonNull("Session ID", id);112 HttpRequest req = new HttpRequest(GET, "/se/grid/node/owner/" + id);113 HttpTracing.inject(tracer, tracer.getCurrentContext(), req);114 HttpResponse res = client.with(addSecret).execute(req);115 return Boolean.TRUE.equals(Values.get(res, Boolean.class));...

Full Screen

Full Screen

Source:Host.java Github

copy

Full Screen

...28import org.openqa.selenium.Capabilities;29import org.openqa.selenium.SessionNotCreatedException;30import org.openqa.selenium.events.EventBus;31import org.openqa.selenium.grid.component.HealthCheck;32import org.openqa.selenium.grid.data.CreateSessionRequest;33import org.openqa.selenium.grid.data.CreateSessionResponse;34import org.openqa.selenium.grid.data.DistributorStatus;35import org.openqa.selenium.grid.data.NodeStatus;36import org.openqa.selenium.grid.node.Node;37import org.openqa.selenium.remote.SessionId;38import java.net.URI;39import java.util.HashMap;40import java.util.List;41import java.util.Map;42import java.util.Objects;43import java.util.Set;44import java.util.UUID;45import java.util.concurrent.locks.Lock;46import java.util.concurrent.locks.ReadWriteLock;47import java.util.concurrent.locks.ReentrantReadWriteLock;48import java.util.function.Supplier;49import java.util.logging.Logger;50class Host {51 private static final Logger LOG = Logger.getLogger("Selenium Distributor");52 private final Node node;53 private final UUID nodeId;54 private final URI uri;55 private final Runnable performHealthCheck;56 // Used any time we need to read or modify the mutable state of this host57 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);58 private Status status;59 private List<Slot> slots;60 private int maxSessionCount;61 public Host(EventBus bus, Node node) {62 this.node = Objects.requireNonNull(node);63 this.nodeId = node.getId();64 this.uri = node.getUri();65 this.status = Status.DOWN;66 this.slots = ImmutableList.of();67 HealthCheck healthCheck = node.getHealthCheck();68 this.performHealthCheck = () -> {69 HealthCheck.Result result = healthCheck.check();70 Host.Status current = result.isAlive() ? UP : DOWN;71 Host.Status previous = setHostStatus(current);72 if (previous == DRAINING) {73 // We want to continue to allow the node to drain.74 setHostStatus(DRAINING);75 return;76 }77 if (current != previous) {78 LOG.info(String.format(79 "Changing status of node %s from %s to %s. Reason: %s",80 node.getId(),81 previous,82 current,83 result.getMessage()));84 }85 };86 bus.addListener(SESSION_CLOSED, event -> {87 SessionId id = event.getData(SessionId.class);88 this.slots.forEach(slot -> slot.onEnd(id));89 });90 update(node.getStatus());91 }92 void update(NodeStatus status) {93 Objects.requireNonNull(status);94 Lock writeLock = lock.writeLock();95 writeLock.lock();96 try {97 // This is grossly inefficient. But we're on a modern processor and we're expecting 10s to 100s98 // of nodes, so this is probably ok.99 Set<NodeStatus.Active> sessions = status.getCurrentSessions();100 Map<Capabilities, Integer> actives = sessions.parallelStream().collect(101 groupingBy(NodeStatus.Active::getStereotype, summingInt(active -> 1)));102 ImmutableList.Builder<Slot> slots = ImmutableList.builder();103 status.getStereotypes().forEach((caps, count) -> {104 if (actives.containsKey(caps)) {105 Integer activeCount = actives.get(caps);106 for (int i = 0; i < activeCount; i++) {107 slots.add(new Slot(node, caps, ACTIVE));108 }109 count -= activeCount;110 }111 for (int i = 0; i < count; i++) {112 slots.add(new Slot(node, caps, AVAILABLE));113 }114 });115 this.slots = slots.build();116 // By definition, we can never have more sessions than we have slots available117 this.maxSessionCount = Math.min(this.slots.size(), status.getMaxSessionCount());118 } finally {119 writeLock.unlock();120 }121 }122 public UUID getId() {123 return nodeId;124 }125 public DistributorStatus.NodeSummary asSummary() {126 Map<Capabilities, Integer> stereotypes = new HashMap<>();127 Map<Capabilities, Integer> used = new HashMap<>();128 slots.forEach(slot -> {129 stereotypes.compute(slot.getStereotype(), (key, curr) -> curr == null ? 1 : curr + 1);130 if (slot.getStatus() != AVAILABLE) {131 used.compute(slot.getStereotype(), (key, curr) -> curr == null ? 1 : curr + 1);132 }133 });134 return new DistributorStatus.NodeSummary(135 nodeId,136 uri,137 getHostStatus() == UP,138 maxSessionCount,139 stereotypes,140 used);141 }142 public Status getHostStatus() {143 return status;144 }145 /**146 * @return The previous status of the node.147 */148 private Status setHostStatus(Status status) {149 Status toReturn = this.status;150 this.status = Objects.requireNonNull(status, "Status must be set.");151 return toReturn;152 }153 public boolean hasCapacity(Capabilities caps) {154 Lock read = lock.readLock();155 read.lock();156 try {157 long count = slots.stream()158 .filter(slot -> slot.isSupporting(caps))159 .filter(slot -> slot.getStatus() == AVAILABLE)160 .count();161 return count > 0;162 } finally {163 read.unlock();164 }165 }166 public float getLoad() {167 Lock read = lock.readLock();168 read.lock();169 try {170 float inUse = slots.parallelStream()171 .filter(slot -> slot.getStatus() != AVAILABLE)172 .count();173 return (inUse / (float) maxSessionCount) * 100f;174 } finally {175 read.unlock();176 }177 }178 public long getLastSessionCreated() {179 Lock read = lock.readLock();180 read.lock();181 try {182 return slots.parallelStream()183 .mapToLong(Slot::getLastSessionCreated)184 .max()185 .orElse(0);186 } finally {187 read.unlock();188 }189 }190 public Supplier<CreateSessionResponse> reserve(CreateSessionRequest sessionRequest) {191 Objects.requireNonNull(sessionRequest);192 Lock write = lock.writeLock();193 write.lock();194 try {195 Slot toReturn = slots.stream()196 .filter(slot -> slot.isSupporting(sessionRequest.getCapabilities()))197 .filter(slot -> slot.getStatus() == AVAILABLE)198 .findFirst()199 .orElseThrow(() -> new SessionNotCreatedException("Unable to reserve an instance"));200 return toReturn.onReserve(sessionRequest);201 } finally {202 write.unlock();203 }204 }...

Full Screen

Full Screen

Source:GetNewSessionResponse.java Github

copy

Full Screen

...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()))));93 request.getLatch().countDown();94 }95 }96 public HttpResponse add(HttpRequest request) {97 Require.nonNull("New Session request", request);98 CountDownLatch latch = new CountDownLatch(1);99 UUID uuid = UUID.randomUUID();100 RequestId requestId = new RequestId(uuid);101 NewSessionRequest requestIdentifier = new NewSessionRequest(requestId, latch);102 knownRequests.put(requestId, requestIdentifier);103 if (!sessionRequests.offerLast(request, requestId)) {104 return new HttpResponse()105 .setStatus(HTTP_INTERNAL_ERROR)106 .setContent(asJson(ImmutableMap.of("message",107 "Session request could not be created. Error while adding to the session queue.")));108 }109 try {110 // Block until response is received.111 // This will not wait indefinitely due to request timeout handled by the LocalDistributor.112 latch.await();113 HttpResponse res = requestIdentifier.getSessionResponse();114 return res;115 } catch (InterruptedException e) {...

Full Screen

Full Screen

Source:Slot.java Github

copy

Full Screen

...19import static org.openqa.selenium.grid.distributor.local.Slot.Status.AVAILABLE;20import static org.openqa.selenium.grid.distributor.local.Slot.Status.RESERVED;21import org.openqa.selenium.Capabilities;22import org.openqa.selenium.SessionNotCreatedException;23import org.openqa.selenium.grid.data.CreateSessionRequest;24import org.openqa.selenium.grid.data.CreateSessionResponse;25import org.openqa.selenium.grid.data.Session;26import org.openqa.selenium.grid.node.Node;27import org.openqa.selenium.remote.SessionId;28import java.util.Objects;29import java.util.function.Supplier;30public class Slot {31 private final Node node;32 private final Capabilities registeredCapabilities;33 private Status currentStatus;34 private long lastStartedNanos;35 private Session currentSession;36 public Slot(Node node, Capabilities capabilities, Status status) {37 this.node = Objects.requireNonNull(node);38 this.registeredCapabilities = Objects.requireNonNull(capabilities);39 this.currentStatus = Objects.requireNonNull(status);40 }41 public Capabilities getStereotype() {42 return registeredCapabilities;43 }44 public Status getStatus() {45 return currentStatus;46 }47 public long getLastSessionCreated() {48 return lastStartedNanos;49 }50 public boolean isSupporting(Capabilities caps) {51 // Simple implementation --- only checks current values52 return registeredCapabilities.getCapabilityNames().stream()53 .map(name -> Objects.equals(54 registeredCapabilities.getCapability(name),55 caps.getCapability(name)))56 .reduce(Boolean::logicalAnd)57 .orElse(false);58 }59 public Supplier<CreateSessionResponse> onReserve(CreateSessionRequest sessionRequest) {60 if (getStatus() != AVAILABLE) {61 throw new IllegalStateException("Node is not available");62 }63 currentStatus = RESERVED;64 return () -> {65 try {66 CreateSessionResponse sessionResponse = node.newSession(sessionRequest)67 .orElseThrow(68 () -> new SessionNotCreatedException(69 "Unable to create session for " + sessionRequest));70 onStart(sessionResponse.getSession());71 return sessionResponse;72 } catch (Throwable t) {73 currentStatus = AVAILABLE;...

Full Screen

Full Screen

Source:TestSessionFactory.java Github

copy

Full Screen

...16// under the License.17package org.openqa.selenium.grid.testing;18import static org.openqa.selenium.remote.Dialect.W3C;19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.grid.data.CreateSessionRequest;21import org.openqa.selenium.grid.data.Session;22import org.openqa.selenium.grid.node.ActiveSession;23import org.openqa.selenium.grid.node.BaseActiveSession;24import org.openqa.selenium.grid.node.SessionFactory;25import org.openqa.selenium.grid.web.CommandHandler;26import org.openqa.selenium.remote.Dialect;27import org.openqa.selenium.remote.SessionId;28import org.openqa.selenium.remote.http.HttpRequest;29import org.openqa.selenium.remote.http.HttpResponse;30import java.io.IOException;31import java.io.UncheckedIOException;32import java.net.MalformedURLException;33import java.net.URL;34import java.util.Optional;35import java.util.UUID;36import java.util.function.BiFunction;37public class TestSessionFactory implements SessionFactory {38 private final BiFunction<SessionId, Capabilities, Session> sessionGenerator;39 public TestSessionFactory(BiFunction<SessionId, Capabilities, Session> sessionGenerator) {40 this.sessionGenerator = sessionGenerator;41 }42 @Override43 public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {44 SessionId id = new SessionId(UUID.randomUUID());45 Session session = sessionGenerator.apply(id, sessionRequest.getCapabilities());46 URL url = null;47 try {48 url = session.getUri().toURL();49 } catch (MalformedURLException e) {50 throw new UncheckedIOException(e);51 }52 Dialect downstream = sessionRequest.getDownstreamDialects().contains(W3C) ?53 W3C :54 sessionRequest.getDownstreamDialects().iterator().next();55 BaseActiveSession activeSession = new BaseActiveSession(56 session.getId(),57 url,...

Full Screen

Full Screen

SessionRequest

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.SessionRequest;2import org.openqa.selenium.grid.data.SessionRequestConverter;3import org.openqa.selenium.json.Json;4import org.openqa.selenium.remote.http.HttpRequest;5import org.openqa.selenium.remote.http.HttpResponse;6public class SessionRequestDemo {7 public static void main(String[] args) {8 Json json = new Json();9 HttpRequest request = new HttpRequest("POST", "/session");10 request.setContent(json.toJson(new SessionRequest("chrome", "76.0.3809.132")));11 SessionRequest sessionRequest = new SessionRequestConverter().apply(request);12 System.out.println("SessionRequest: " + sessionRequest);13 }14}15SessionRequest: SessionRequest{capabilities=Capabilities{firstMatch=[{browserName=chrome, browserVersion=76.0.3809.132}]}}

Full Screen

Full Screen

SessionRequest

Using AI Code Generation

copy

Full Screen

1SessionRequest request = new SessionRequest(ImmutableMap.of(2 "capabilities", ImmutableMap.of(3 "alwaysMatch", ImmutableMap.of(4));5SessionResponse response = sessions.execute(request);6SessionId id = response.getSessionId();

Full Screen

Full Screen

SessionRequest

Using AI Code Generation

copy

Full Screen

1SessionRequest sessionRequest = new SessionRequest(2 ImmutableMap.of("browserName", "chrome"),3 ImmutableMap.of("browserName", "chrome"),4 ImmutableMap.of("browserName", "chrome"),5 ImmutableMap.of("browserName", "chrome")6);7SessionRequest sessionRequest = new SessionRequest(8 ImmutableMap.of("browserName", "chrome"),9 ImmutableMap.of("browserName", "chrome"),10 ImmutableMap.of("browserName", "chrome"),11 ImmutableMap.of("browserName", "chrome")12);13SessionRequest sessionRequest = new SessionRequest(14 ImmutableMap.of("browserName", "chrome"),15 ImmutableMap.of("browserName", "chrome"),16 ImmutableMap.of("browserName", "chrome"),17 ImmutableMap.of("browserName", "chrome")18);19SessionRequest sessionRequest = new SessionRequest(20 ImmutableMap.of("browserName", "chrome"),21 ImmutableMap.of("browserName", "chrome"),22 ImmutableMap.of("browserName", "chrome"),23 ImmutableMap.of("browserName", "chrome")24);25SessionRequest sessionRequest = new SessionRequest(26 ImmutableMap.of("browserName", "chrome"),27 ImmutableMap.of("browserName", "chrome"),28 ImmutableMap.of("browserName", "chrome"),29 ImmutableMap.of("browserName", "chrome")30);31SessionRequest sessionRequest = new SessionRequest(32 ImmutableMap.of("browserName", "chrome"),33 ImmutableMap.of("browserName", "chrome"),34 ImmutableMap.of("browserName", "chrome"),35 ImmutableMap.of("browserName", "chrome")36);37SessionRequest sessionRequest = new SessionRequest(38 ImmutableMap.of("browserName", "chrome"),39 ImmutableMap.of("browserName", "chrome"),40 ImmutableMap.of("browserName", "chrome"),41 ImmutableMap.of("browserName", "chrome")42);43SessionRequest sessionRequest = new SessionRequest(44 ImmutableMap.of("browserName", "chrome"),45 ImmutableMap.of("browserName", "chrome"),46 ImmutableMap.of("browserName", "chrome"),47 ImmutableMap.of("browserName", "chrome")48);

Full Screen

Full Screen

SessionRequest

Using AI Code Generation

copy

Full Screen

1SessionRequest request = new SessionRequest(2 new SessionId(UUID.randomUUID()),3 new Capabilities(),4 new Capabilities(),5);6SessionRequest request = new SessionRequest(7 new SessionId(UUID.randomUUID()),8 new Capabilities(),9 new Capabilities(),10);11SessionResponse response = new SessionResponse(12 new SessionId(UUID.randomUUID()),13 new SessionId(UUID.randomUUID()),14);15SessionResponse response = new SessionResponse(16 new SessionId(UUID.randomUUID()),17 new SessionId(UUID.randomUUID()),18);19SessionId sessionId = new SessionId(UUID.randomUUID());20SessionId sessionId = new SessionId(UUID.randomUUID());21SessionInfo sessionInfo = new SessionInfo(22 new SessionId(UUID.randomUUID()),23 new Capabilities(),24 new Capabilities()25);26SessionInfo sessionInfo = new SessionInfo(27 new SessionId(UUID.randomUUID()),28 new Capabilities(),29 new Capabilities()30);

Full Screen

Full Screen
copy
1i += l; 2
Full Screen
copy
1i = i + (int)l;2
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.

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