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

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

Source:LocalDistributor.java Github

copy

Full Screen

...36import org.openqa.selenium.grid.data.NodeStatus;37import org.openqa.selenium.grid.data.NodeStatusEvent;38import org.openqa.selenium.grid.data.RequestId;39import org.openqa.selenium.grid.data.SessionRequest;40import org.openqa.selenium.grid.data.SessionRequestCapability;41import org.openqa.selenium.grid.data.Slot;42import org.openqa.selenium.grid.data.SlotId;43import org.openqa.selenium.grid.data.TraceSessionRequest;44import org.openqa.selenium.grid.distributor.Distributor;45import org.openqa.selenium.grid.distributor.config.DistributorOptions;46import org.openqa.selenium.grid.distributor.selector.SlotSelector;47import org.openqa.selenium.grid.log.LoggingOptions;48import org.openqa.selenium.grid.node.HealthCheck;49import org.openqa.selenium.grid.node.Node;50import org.openqa.selenium.grid.node.remote.RemoteNode;51import org.openqa.selenium.grid.security.Secret;52import org.openqa.selenium.grid.security.SecretOptions;53import org.openqa.selenium.grid.server.EventBusOptions;54import org.openqa.selenium.grid.server.NetworkOptions;55import org.openqa.selenium.grid.sessionmap.SessionMap;56import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;57import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;58import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;59import org.openqa.selenium.internal.Either;60import org.openqa.selenium.internal.Require;61import org.openqa.selenium.remote.SessionId;62import org.openqa.selenium.remote.http.HttpClient;63import org.openqa.selenium.remote.tracing.AttributeKey;64import org.openqa.selenium.remote.tracing.EventAttribute;65import org.openqa.selenium.remote.tracing.EventAttributeValue;66import org.openqa.selenium.remote.tracing.Span;67import org.openqa.selenium.remote.tracing.Status;68import org.openqa.selenium.remote.tracing.Tracer;69import org.openqa.selenium.status.HasReadyState;70import java.io.UncheckedIOException;71import java.time.Duration;72import java.util.ArrayList;73import java.util.Collection;74import java.util.HashMap;75import java.util.List;76import java.util.Map;77import java.util.Optional;78import java.util.Set;79import java.util.concurrent.ConcurrentHashMap;80import java.util.concurrent.Executors;81import java.util.concurrent.locks.Lock;82import java.util.concurrent.locks.ReadWriteLock;83import java.util.concurrent.locks.ReentrantReadWriteLock;84import java.util.logging.Level;85import java.util.logging.Logger;86import java.util.stream.Collectors;87import static com.google.common.collect.ImmutableSet.toImmutableSet;88import static org.openqa.selenium.grid.data.Availability.DOWN;89import static org.openqa.selenium.grid.data.Availability.DRAINING;90import static org.openqa.selenium.internal.Debug.getDebugLogLevel;91import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES;92import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES_EVENT;93import static org.openqa.selenium.remote.RemoteTags.SESSION_ID;94import static org.openqa.selenium.remote.RemoteTags.SESSION_ID_EVENT;95import static org.openqa.selenium.remote.tracing.AttributeKey.SESSION_URI;96import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;97public class LocalDistributor extends Distributor {98 private static final Logger LOG = Logger.getLogger(LocalDistributor.class.getName());99 private final Tracer tracer;100 private final EventBus bus;101 private final HttpClient.Factory clientFactory;102 private final SessionMap sessions;103 private final SlotSelector slotSelector;104 private final Secret registrationSecret;105 private final Regularly hostChecker = new Regularly("distributor host checker");106 private final Map<NodeId, Runnable> allChecks = new HashMap<>();107 private final Duration healthcheckInterval;108 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);109 private final GridModel model;110 private final Map<NodeId, Node> nodes;111 private final NewSessionQueue sessionQueue;112 private final Regularly regularly;113 private final boolean rejectUnsupportedCaps;114 public LocalDistributor(115 Tracer tracer,116 EventBus bus,117 HttpClient.Factory clientFactory,118 SessionMap sessions,119 NewSessionQueue sessionQueue,120 SlotSelector slotSelector,121 Secret registrationSecret,122 Duration healthcheckInterval,123 boolean rejectUnsupportedCaps) {124 super(tracer, clientFactory, registrationSecret);125 this.tracer = Require.nonNull("Tracer", tracer);126 this.bus = Require.nonNull("Event bus", bus);127 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);128 this.sessions = Require.nonNull("Session map", sessions);129 this.sessionQueue = Require.nonNull("New Session Request Queue", sessionQueue);130 this.slotSelector = Require.nonNull("Slot selector", slotSelector);131 this.registrationSecret = Require.nonNull("Registration secret", registrationSecret);132 this.healthcheckInterval = Require.nonNull("Health check interval", healthcheckInterval);133 this.model = new GridModel(bus);134 this.nodes = new ConcurrentHashMap<>();135 this.rejectUnsupportedCaps = rejectUnsupportedCaps;136 bus.addListener(NodeStatusEvent.listener(this::register));137 bus.addListener(NodeStatusEvent.listener(model::refresh));138 bus.addListener(NodeHeartBeatEvent.listener(nodeStatus -> {139 if (nodes.containsKey(nodeStatus.getId())) {140 model.touch(nodeStatus.getId());141 } else {142 register(nodeStatus);143 }144 }));145 regularly = new Regularly(146 Executors.newSingleThreadScheduledExecutor(147 r -> {148 Thread thread = new Thread(r);149 thread.setName("New Session Queue");150 thread.setDaemon(true);151 return thread;152 }));153 NewSessionRunnable newSessionRunnable = new NewSessionRunnable();154 bus.addListener(NodeDrainComplete.listener(this::remove));155 bus.addListener(NewSessionRequestEvent.listener(ignored -> newSessionRunnable.run()));156 regularly.submit(model::purgeDeadNodes, Duration.ofSeconds(30), Duration.ofSeconds(30));157 regularly.submit(newSessionRunnable, Duration.ofSeconds(5), Duration.ofSeconds(5));158 }159 public static Distributor create(Config config) {160 Tracer tracer = new LoggingOptions(config).getTracer();161 EventBus bus = new EventBusOptions(config).getEventBus();162 DistributorOptions distributorOptions = new DistributorOptions(config);163 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);164 SessionMap sessions = new SessionMapOptions(config).getSessionMap();165 SecretOptions secretOptions = new SecretOptions(config);166 NewSessionQueue sessionQueue = new NewSessionQueueOptions(config).getSessionQueue(167 "org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue");168 return new LocalDistributor(169 tracer,170 bus,171 clientFactory,172 sessions,173 sessionQueue,174 distributorOptions.getSlotSelector(),175 secretOptions.getRegistrationSecret(),176 distributorOptions.getHealthCheckInterval(),177 distributorOptions.shouldRejectUnsupportedCaps());178 }179 @Override180 public boolean isReady() {181 try {182 return ImmutableSet.of(bus, sessions).parallelStream()183 .map(HasReadyState::isReady)184 .reduce(true, Boolean::logicalAnd);185 } catch (RuntimeException e) {186 return false;187 }188 }189 private void register(NodeStatus status) {190 Require.nonNull("Node", status);191 Lock writeLock = lock.writeLock();192 writeLock.lock();193 try {194 if (nodes.containsKey(status.getId())) {195 return;196 }197 Set<Capabilities> capabilities = status.getSlots().stream()198 .map(Slot::getStereotype)199 .map(ImmutableCapabilities::copyOf)200 .collect(toImmutableSet());201 // A new node! Add this as a remote node, since we've not called add202 RemoteNode remoteNode = new RemoteNode(203 tracer,204 clientFactory,205 status.getId(),206 status.getUri(),207 registrationSecret,208 capabilities);209 add(remoteNode);210 } finally {211 writeLock.unlock();212 }213 }214 @Override215 public LocalDistributor add(Node node) {216 Require.nonNull("Node", node);217 LOG.info(String.format("Added node %s at %s.", node.getId(), node.getUri()));218 nodes.put(node.getId(), node);219 model.add(node.getStatus());220 // Extract the health check221 Runnable runnableHealthCheck = asRunnableHealthCheck(node);222 allChecks.put(node.getId(), runnableHealthCheck);223 hostChecker.submit(runnableHealthCheck, healthcheckInterval, Duration.ofSeconds(30));224 bus.fire(new NodeAddedEvent(node.getId()));225 return this;226 }227 private Runnable asRunnableHealthCheck(Node node) {228 HealthCheck healthCheck = node.getHealthCheck();229 NodeId id = node.getId();230 return () -> {231 HealthCheck.Result result;232 try {233 result = healthCheck.check();234 } catch (Exception e) {235 LOG.log(Level.WARNING, "Unable to process node " + id, e);236 result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");237 }238 Lock writeLock = lock.writeLock();239 writeLock.lock();240 try {241 model.setAvailability(id, result.getAvailability());242 } finally {243 writeLock.unlock();244 }245 };246 }247 @Override248 public boolean drain(NodeId nodeId) {249 Node node = nodes.get(nodeId);250 if (node == null) {251 LOG.info("Asked to drain unregistered node " + nodeId);252 return false;253 }254 Lock writeLock = lock.writeLock();255 writeLock.lock();256 try {257 node.drain();258 model.setAvailability(nodeId, DRAINING);259 } finally {260 writeLock.unlock();261 }262 return node.isDraining();263 }264 public void remove(NodeId nodeId) {265 Lock writeLock = lock.writeLock();266 writeLock.lock();267 try {268 model.remove(nodeId);269 Runnable runnable = allChecks.remove(nodeId);270 if (runnable != null) {271 hostChecker.remove(runnable);272 }273 } finally {274 writeLock.unlock();275 }276 }277 @Override278 public DistributorStatus getStatus() {279 Lock readLock = this.lock.readLock();280 readLock.lock();281 try {282 return new DistributorStatus(model.getSnapshot());283 } finally {284 readLock.unlock();285 }286 }287 @Beta288 public void refresh() {289 List<Runnable> allHealthChecks = new ArrayList<>();290 Lock readLock = this.lock.readLock();291 readLock.lock();292 try {293 allHealthChecks.addAll(allChecks.values());294 } finally {295 readLock.unlock();296 }297 allHealthChecks.parallelStream().forEach(Runnable::run);298 }299 protected Set<NodeStatus> getAvailableNodes() {300 Lock readLock = this.lock.readLock();301 readLock.lock();302 try {303 return model.getSnapshot().stream()304 .filter(node -> !DOWN.equals(node.getAvailability()))305 .collect(toImmutableSet());306 } finally {307 readLock.unlock();308 }309 }310 @Override311 public Either<SessionNotCreatedException, CreateSessionResponse> newSession(SessionRequest request)312 throws SessionNotCreatedException {313 Require.nonNull("Requests to process", request);314 Span span = tracer.getCurrentContext().createSpan("distributor.new_session");315 Map<String, EventAttributeValue> attributeMap = new HashMap<>();316 try {317 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),318 EventAttribute.setValue(getClass().getName()));319 attributeMap.put("request.payload", EventAttribute.setValue(request.getDesiredCapabilities().toString()));320 String sessionReceivedMessage = "Session request received by the distributor";321 span.addEvent(sessionReceivedMessage, attributeMap);322 LOG.info(String.format("%s: \n %s", sessionReceivedMessage, request.getDesiredCapabilities()));323 // If there are no capabilities at all, something is horribly wrong324 if (request.getDesiredCapabilities().isEmpty()) {325 SessionNotCreatedException exception =326 new SessionNotCreatedException("No capabilities found in session request payload");327 EXCEPTION.accept(attributeMap, exception);328 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),329 EventAttribute.setValue("Unable to create session. No capabilities found: " +330 exception.getMessage()));331 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);332 return Either.left(exception);333 }334 boolean retry = false;335 SessionNotCreatedException lastFailure = new SessionNotCreatedException("Unable to create new session");336 for (Capabilities caps : request.getDesiredCapabilities()) {337 if (!isSupported(caps)) {338 continue;339 }340 // Try and find a slot that we can use for this session. While we341 // are finding the slot, no other session can possibly be started.342 // Therefore, spend as little time as possible holding the write343 // lock, and release it as quickly as possible. Under no344 // circumstances should we try to actually start the session itself345 // in this next block of code.346 SlotId selectedSlot = reserveSlot(request.getRequestId(), caps);347 if (selectedSlot == null) {348 LOG.info(String.format("Unable to find slot for request %s. May retry: %s ", request.getRequestId(), caps));349 retry = true;350 continue;351 }352 CreateSessionRequest singleRequest = new CreateSessionRequest(353 request.getDownstreamDialects(),354 caps,355 request.getMetadata());356 try {357 CreateSessionResponse response = startSession(selectedSlot, singleRequest);358 sessions.add(response.getSession());359 model.setSession(selectedSlot, response.getSession());360 SessionId sessionId = response.getSession().getId();361 Capabilities sessionCaps = response.getSession().getCapabilities();362 String sessionUri = response.getSession().getUri().toString();363 SESSION_ID.accept(span, sessionId);364 CAPABILITIES.accept(span, sessionCaps);365 SESSION_ID_EVENT.accept(attributeMap, sessionId);366 CAPABILITIES_EVENT.accept(attributeMap, sessionCaps);367 span.setAttribute(SESSION_URI.getKey(), sessionUri);368 attributeMap.put(SESSION_URI.getKey(), EventAttribute.setValue(sessionUri));369 String sessionCreatedMessage = "Session created by the distributor";370 span.addEvent(sessionCreatedMessage, attributeMap);371 LOG.info(String.format("%s. Id: %s, Caps: %s", sessionCreatedMessage, sessionId, sessionCaps));372 return Either.right(response);373 } catch (SessionNotCreatedException e) {374 model.setSession(selectedSlot, null);375 lastFailure = e;376 }377 }378 // If we've made it this far, we've not been able to start a session379 if (retry) {380 lastFailure = new RetrySessionRequestException(381 "Will re-attempt to find a node which can run this session",382 lastFailure);383 attributeMap.put(384 AttributeKey.EXCEPTION_MESSAGE.getKey(),385 EventAttribute.setValue("Will retry session " + request.getRequestId()));386 } else {387 EXCEPTION.accept(attributeMap, lastFailure);388 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),389 EventAttribute.setValue("Unable to create session: " + lastFailure.getMessage()));390 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);391 }392 return Either.left(lastFailure);393 } catch (SessionNotCreatedException e) {394 span.setAttribute(AttributeKey.ERROR.getKey(), true);395 span.setStatus(Status.ABORTED);396 EXCEPTION.accept(attributeMap, e);397 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),398 EventAttribute.setValue("Unable to create session: " + e.getMessage()));399 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);400 return Either.left(e);401 } catch (UncheckedIOException e) {402 span.setAttribute(AttributeKey.ERROR.getKey(), true);403 span.setStatus(Status.UNKNOWN);404 EXCEPTION.accept(attributeMap, e);405 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),406 EventAttribute.setValue("Unknown error in LocalDistributor while creating session: " + e.getMessage()));407 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);408 return Either.left(new SessionNotCreatedException(e.getMessage(), e));409 } finally {410 span.close();411 }412 }413 private CreateSessionResponse startSession(SlotId selectedSlot, CreateSessionRequest singleRequest) {414 Node node = nodes.get(selectedSlot.getOwningNodeId());415 if (node == null) {416 throw new SessionNotCreatedException("Unable to find owning node for slot");417 }418 Either<WebDriverException, CreateSessionResponse> result;419 try {420 result = node.newSession(singleRequest);421 } catch (SessionNotCreatedException e) {422 result = Either.left(e);423 } catch (RuntimeException e) {424 result = Either.left(new SessionNotCreatedException(e.getMessage(), e));425 }426 if (result.isLeft()) {427 WebDriverException exception = result.left();428 if (exception instanceof SessionNotCreatedException) {429 throw exception;430 }431 throw new SessionNotCreatedException(exception.getMessage(), exception);432 }433 return result.right();434 }435 private SlotId reserveSlot(RequestId requestId, Capabilities caps) {436 Lock writeLock = lock.writeLock();437 writeLock.lock();438 try {439 Set<SlotId> slotIds = slotSelector.selectSlot(caps, getAvailableNodes());440 if (slotIds.isEmpty()) {441 LOG.log(442 getDebugLogLevel(),443 String.format("No slots found for request %s and capabilities %s", requestId, caps));444 return null;445 }446 for (SlotId slotId : slotIds) {447 if (reserve(slotId)) {448 return slotId;449 }450 }451 return null;452 } finally {453 writeLock.unlock();454 }455 }456 private boolean isSupported(Capabilities caps) {457 return getAvailableNodes().stream().anyMatch(node -> node.hasCapability(caps));458 }459 private boolean reserve(SlotId id) {460 Require.nonNull("Slot ID", id);461 Lock writeLock = this.lock.writeLock();462 writeLock.lock();463 try {464 Node node = nodes.get(id.getOwningNodeId());465 if (node == null) {466 LOG.log(getDebugLogLevel(), String.format("Unable to find node with id %s", id));467 return false;468 }469 return model.reserve(id);470 } finally {471 writeLock.unlock();472 }473 }474 public void callExecutorShutdown() {475 LOG.info("Shutting down Distributor executor service");476 regularly.shutdown();477 }478 public class NewSessionRunnable implements Runnable {479 @Override480 public void run() {481 List<SessionRequestCapability> queueContents = sessionQueue.getQueueContents();482 if (rejectUnsupportedCaps) {483 checkMatchingSlot(queueContents);484 }485 int initialSize = queueContents.size();486 boolean retry = initialSize != 0;487 while (retry) {488 // We deliberately run this outside of a lock: if we're unsuccessful489 // starting the session, we just put the request back on the queue.490 // This does mean, however, that under high contention, we might end491 // up starving a session request.492 Set<Capabilities> stereotypes =493 getAvailableNodes().stream()494 .filter(NodeStatus::hasCapacity)495 .map(496 node ->497 node.getSlots().stream()498 .map(Slot::getStereotype)499 .collect(Collectors.toSet()))500 .flatMap(Collection::stream)501 .collect(Collectors.toSet());502 Optional<SessionRequest> maybeRequest = sessionQueue.getNextAvailable(stereotypes);503 maybeRequest.ifPresent(this::handleNewSessionRequest);504 int currentSize = sessionQueue.getQueueContents().size();505 retry = currentSize != 0 && currentSize != initialSize;506 initialSize = currentSize;507 }508 }509 private void checkMatchingSlot(List<SessionRequestCapability> sessionRequests) {510 for(SessionRequestCapability request : sessionRequests) {511 long unmatchableCount = request.getDesiredCapabilities().stream()512 .filter(caps -> !isSupported(caps))513 .count();514 if (unmatchableCount == request.getDesiredCapabilities().size()) {515 SessionNotCreatedException exception = new SessionNotCreatedException(516 "No nodes support the capabilities in the request");517 sessionQueue.complete(request.getRequestId(), Either.left(exception));518 }519 }520 }521 private void handleNewSessionRequest(SessionRequest sessionRequest) {522 RequestId reqId = sessionRequest.getRequestId();523 try (Span span = TraceSessionRequest.extract(tracer, sessionRequest).createSpan("distributor.poll_queue")) {524 Map<String, EventAttributeValue> attributeMap = new HashMap<>();...

Full Screen

Full Screen

Source:LocalNewSessionQueueTest.java Github

copy

Full Screen

...32import org.openqa.selenium.grid.data.NewSessionRejectedEvent;33import org.openqa.selenium.grid.data.NewSessionRequestEvent;34import org.openqa.selenium.grid.data.RequestId;35import org.openqa.selenium.grid.data.Session;36import org.openqa.selenium.grid.data.SessionRequestCapability;37import org.openqa.selenium.grid.security.Secret;38import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;39import org.openqa.selenium.grid.data.SessionRequest;40import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;41import org.openqa.selenium.grid.testing.PassthroughHttpClient;42import org.openqa.selenium.internal.Debug;43import org.openqa.selenium.internal.Either;44import org.openqa.selenium.json.Json;45import org.openqa.selenium.remote.SessionId;46import org.openqa.selenium.remote.http.Contents;47import org.openqa.selenium.remote.http.HttpClient;48import org.openqa.selenium.remote.http.HttpResponse;49import org.openqa.selenium.remote.tracing.DefaultTestTracer;50import org.openqa.selenium.remote.tracing.Tracer;51import java.net.URI;52import java.net.URISyntaxException;53import java.time.Duration;54import java.time.Instant;55import java.util.Collection;56import java.util.LinkedHashSet;57import java.util.List;58import java.util.Map;59import java.util.Optional;60import java.util.Set;61import java.util.UUID;62import java.util.concurrent.Callable;63import java.util.concurrent.CountDownLatch;64import java.util.concurrent.ExecutionException;65import java.util.concurrent.ExecutorService;66import java.util.concurrent.Executors;67import java.util.concurrent.Future;68import java.util.concurrent.TimeoutException;69import java.util.concurrent.atomic.AtomicBoolean;70import java.util.concurrent.atomic.AtomicInteger;71import java.util.concurrent.atomic.AtomicReference;72import java.util.function.Supplier;73import java.util.stream.Collectors;74import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;75import static java.net.HttpURLConnection.HTTP_OK;76import static java.nio.charset.StandardCharsets.UTF_8;77import static java.util.concurrent.TimeUnit.SECONDS;78import static org.assertj.core.api.Assertions.assertThat;79import static org.assertj.core.api.Assertions.fail;80import static org.junit.Assert.assertEquals;81import static org.junit.Assert.assertFalse;82import static org.junit.Assert.assertNotEquals;83import static org.junit.Assert.assertTrue;84import static org.openqa.selenium.remote.Dialect.W3C;85import static org.openqa.selenium.testing.Safely.safelyCall;86@RunWith(Parameterized.class)87public class LocalNewSessionQueueTest {88 @ClassRule89 public static Timeout classTimeout = new Timeout(60, SECONDS);90 private static final Json JSON = new Json();91 private static final Capabilities CAPS = new ImmutableCapabilities("browserName", "cheese");92 private static final Secret REGISTRATION_SECRET = new Secret("secret");93 private static final Instant LONG_AGO = Instant.parse("2007-01-03T21:49:10.00Z"); // Go check the git log94 private final NewSessionQueue queue;95 private final LocalNewSessionQueue localQueue;96 private final EventBus bus;97 private final SessionRequest sessionRequest;98 static class TestData {99 public final EventBus bus;100 public final LocalNewSessionQueue localQueue;101 public final NewSessionQueue queue;102 public TestData(EventBus bus, LocalNewSessionQueue localQueue, NewSessionQueue queue) {103 this.bus = bus;104 this.localQueue = localQueue;105 this.queue = queue;106 }107 }108 public LocalNewSessionQueueTest(Supplier<TestData> supplier) {109 TestData testData = supplier.get();110 this.bus = testData.bus;111 this.queue = testData.queue;112 this.localQueue = testData.localQueue;113 this.sessionRequest = new SessionRequest(114 new RequestId(UUID.randomUUID()),115 Instant.now(),116 Set.of(W3C),117 Set.of(CAPS),118 Map.of(),119 Map.of());120 }121 @Parameterized.Parameters122 public static Collection<Supplier<TestData>> createQueues() {123 Tracer tracer = DefaultTestTracer.createTracer();124 Set<Supplier<TestData>> toReturn = new LinkedHashSet<>();125 // Note: this method is called only once, so if we want each test to126 // be isolated, everything that they use has to be created via the127 // supplier. In particular, a shared event bus will cause weird128 // failures to happen.129 toReturn.add(() -> {130 EventBus bus = new GuavaEventBus();131 LocalNewSessionQueue local = new LocalNewSessionQueue(132 tracer,133 bus,134 new DefaultSlotMatcher(),135 Duration.ofSeconds(1),136 Duration.ofSeconds(Debug.isDebugging() ? 9999 : 5),137 REGISTRATION_SECRET);138 return new TestData(bus, local, local);139 });140 toReturn.add(() -> {141 EventBus bus = new GuavaEventBus();142 LocalNewSessionQueue local = new LocalNewSessionQueue(143 tracer,144 bus,145 new DefaultSlotMatcher(),146 Duration.ofSeconds(1),147 Duration.ofSeconds(Debug.isDebugging() ? 9999 : 5),148 REGISTRATION_SECRET);149 HttpClient client = new PassthroughHttpClient(local);150 return new TestData(bus, local, new RemoteNewSessionQueue(tracer, client, REGISTRATION_SECRET));151 });152 return toReturn;153 }154 @After155 public void shutdownQueue() {156 safelyCall(localQueue::close);157 }158 @Test159 public void shouldBeAbleToAddToQueueAndGetValidResponse() {160 AtomicBoolean isPresent = new AtomicBoolean(false);161 bus.addListener(NewSessionRequestEvent.listener(reqId -> {162 isPresent.set(true);163 Capabilities capabilities = new ImmutableCapabilities("browserName", "chrome");164 SessionId sessionId = new SessionId("123");165 Session session =166 new Session(167 sessionId,168 URI.create("http://example.com"),169 CAPS,170 capabilities,171 Instant.now());172 CreateSessionResponse sessionResponse = new CreateSessionResponse(173 session,174 JSON.toJson(175 ImmutableMap.of(176 "value", ImmutableMap.of(177 "sessionId", sessionId,178 "capabilities", capabilities)))179 .getBytes(UTF_8));180 queue.complete(reqId, Either.right(sessionResponse));181 }));182 HttpResponse httpResponse = queue.addToQueue(sessionRequest);183 assertThat(isPresent.get()).isTrue();184 assertEquals(httpResponse.getStatus(), HTTP_OK);185 }186 @Test187 public void shouldBeAbleToAddToQueueAndGetErrorResponse() {188 bus.addListener(NewSessionRequestEvent.listener(reqId ->189 queue.complete(reqId, Either.left(new SessionNotCreatedException("Error")))));190 HttpResponse httpResponse = queue.addToQueue(sessionRequest);191 assertEquals(httpResponse.getStatus(), HTTP_INTERNAL_ERROR);192 }193 @Test194 public void shouldBeAbleToRemoveFromQueue() {195 Optional<SessionRequest> httpRequest = queue.remove(new RequestId(UUID.randomUUID()));196 assertFalse(httpRequest.isPresent());197 }198 @Test199 public void shouldBeClearQueue() {200 RequestId requestId = new RequestId(UUID.randomUUID());201 localQueue.injectIntoQueue(sessionRequest);202 int count = queue.clearQueue();203 assertEquals(count, 1);204 assertFalse(queue.remove(requestId).isPresent());205 }206 @Test207 public void shouldBeAbleToGetQueueContents() {208 localQueue.injectIntoQueue(sessionRequest);209 List<Set<Capabilities>> response = queue.getQueueContents()210 .stream()211 .map(SessionRequestCapability::getDesiredCapabilities)212 .collect(Collectors.toList());213 assertThat(response).hasSize(1);214 assertEquals(Set.of(CAPS), response.get(0));215 }216 @Test217 public void shouldBeClearQueueAndFireRejectedEvent() throws InterruptedException {218 AtomicBoolean result = new AtomicBoolean(false);219 RequestId requestId = sessionRequest.getRequestId();220 CountDownLatch latch = new CountDownLatch(1);221 bus.addListener(222 NewSessionRejectedEvent.listener(223 response -> {224 result.set(response.getRequestId().equals(requestId));225 latch.countDown();...

Full Screen

Full Screen

Source:LocalNewSessionQueue.java Github

copy

Full Screen

...9import org.openqa.selenium.grid.data.NewSessionRejectedEvent;10import org.openqa.selenium.grid.data.NewSessionRequestEvent;11import org.openqa.selenium.grid.data.RequestId;12import org.openqa.selenium.grid.data.SessionRequest;13import org.openqa.selenium.grid.data.SessionRequestCapability;14import org.openqa.selenium.grid.data.TraceSessionRequest;15import org.openqa.selenium.grid.data.SlotMatcher;16import org.openqa.selenium.grid.distributor.config.DistributorOptions;17import org.openqa.selenium.grid.jmx.JMXHelper;18import org.openqa.selenium.grid.jmx.ManagedAttribute;19import org.openqa.selenium.grid.jmx.ManagedService;20import org.openqa.selenium.grid.log.LoggingOptions;21import org.openqa.selenium.grid.security.Secret;22import org.openqa.selenium.grid.security.SecretOptions;23import org.openqa.selenium.grid.server.EventBusOptions;24import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;25import org.openqa.selenium.grid.sessionqueue.config.SessionRequestOptions;26import org.openqa.selenium.internal.Either;27import org.openqa.selenium.internal.Require;28import org.openqa.selenium.remote.http.Contents;29import org.openqa.selenium.remote.http.HttpResponse;30import org.openqa.selenium.remote.tracing.Span;31import org.openqa.selenium.remote.tracing.TraceContext;32import org.openqa.selenium.remote.tracing.Tracer;33import java.io.Closeable;34import java.io.IOException;35import java.time.Duration;36import java.time.Instant;37import java.util.Collections;38import java.util.Deque;39import java.util.Iterator;40import java.util.List;41import java.util.Map;42import java.util.Optional;43import java.util.Set;44import java.util.concurrent.ConcurrentHashMap;45import java.util.concurrent.ConcurrentLinkedDeque;46import java.util.concurrent.CountDownLatch;47import java.util.concurrent.Executors;48import java.util.concurrent.ScheduledExecutorService;49import java.util.concurrent.locks.Lock;50import java.util.concurrent.locks.ReadWriteLock;51import java.util.concurrent.locks.ReentrantReadWriteLock;52import java.util.function.Predicate;53import java.util.stream.Collectors;54import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;55import static java.util.concurrent.TimeUnit.MILLISECONDS;56/**57 * An in-memory implementation of the list of new session requests.58 * <p>59 * The lifecycle of a request can be described as:60 * <ol>61 * <li>User adds an item on to the queue using {@link #addToQueue(SessionRequest)}. This62 * will block until the request completes in some way.63 * <li>After being added, a {@link NewSessionRequestEvent} is fired. Listeners should use64 * this as an indication to call {@link #remove(RequestId)} to get the session request.65 * <li>If the session request is completed, then {@link #complete(RequestId, Either)} must66 * be called. This will not only ensure that {@link #addToQueue(SessionRequest)}67 * returns, but will also fire a {@link NewSessionRejectedEvent} if the session was68 * rejected. Positive completions of events are assumed to be notified on the event bus69 * by other listeners.70 * <li>If the request cannot be handled right now, call71 * {@link #retryAddToQueue(SessionRequest)} to return the session request to the front72 * of the queue.73 * </ol>74 * <p>75 * There is a background thread that will reap {@link SessionRequest}s that have timed out.76 * This means that a request can either complete by a listener calling77 * {@link #complete(RequestId, Either)} directly, or by being reaped by the thread.78 */79@ManagedService(objectName = "org.seleniumhq.grid:type=SessionQueue,name=LocalSessionQueue",80 description = "New session queue")81public class LocalNewSessionQueue extends NewSessionQueue implements Closeable {82 private final EventBus bus;83 private final SlotMatcher slotMatcher;84 private final Duration requestTimeout;85 private final Map<RequestId, Data> requests;86 private final Map<RequestId, TraceContext> contexts;87 private final Deque<SessionRequest> queue;88 private final ReadWriteLock lock = new ReentrantReadWriteLock();89 private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(r -> {90 Thread thread = new Thread(r);91 thread.setDaemon(true);92 thread.setName("Local New Session Queue");93 return thread;94 });95 public LocalNewSessionQueue(96 Tracer tracer,97 EventBus bus,98 SlotMatcher slotMatcher,99 Duration retryPeriod,100 Duration requestTimeout,101 Secret registrationSecret) {102 super(tracer, registrationSecret);103 this.slotMatcher = Require.nonNull("Slot matcher", slotMatcher);104 this.bus = Require.nonNull("Event bus", bus);105 Require.nonNull("Retry period", retryPeriod);106 if (retryPeriod.isNegative() || retryPeriod.isZero()) {107 throw new IllegalArgumentException("Retry period must be positive");108 }109 this.requestTimeout = Require.nonNull("Request timeout", requestTimeout);110 if (requestTimeout.isNegative() || requestTimeout.isZero()) {111 throw new IllegalArgumentException("Request timeout must be positive");112 }113 this.requests = new ConcurrentHashMap<>();114 this.queue = new ConcurrentLinkedDeque<>();115 this.contexts = new ConcurrentHashMap<>();116 service.scheduleAtFixedRate(this::timeoutSessions, retryPeriod.toMillis(), retryPeriod.toMillis(), MILLISECONDS);117 new JMXHelper().register(this);118 }119 public static NewSessionQueue create(Config config) {120 LoggingOptions loggingOptions = new LoggingOptions(config);121 Tracer tracer = loggingOptions.getTracer();122 EventBusOptions eventBusOptions = new EventBusOptions(config);123 SessionRequestOptions requestOptions = new SessionRequestOptions(config);124 SecretOptions secretOptions = new SecretOptions(config);125 SlotMatcher slotMatcher = new DistributorOptions(config).getSlotMatcher();126 return new LocalNewSessionQueue(127 tracer,128 eventBusOptions.getEventBus(),129 slotMatcher,130 requestOptions.getSessionRequestRetryInterval(),131 requestOptions.getSessionRequestTimeout(),132 secretOptions.getRegistrationSecret());133 }134 private void timeoutSessions() {135 Instant now = Instant.now();136 Lock readLock = lock.readLock();137 readLock.lock();138 Set<RequestId> ids;139 try {140 ids = requests.entrySet().stream()141 .filter(entry -> isTimedOut(now, entry.getValue()))142 .map(Map.Entry::getKey)143 .collect(Collectors.toSet());144 } finally {145 readLock.unlock();146 }147 Lock writeLock = lock.writeLock();148 try {149 for (RequestId id : ids) {150 failDueToTimeout(id);151 }152 } finally {153 writeLock.unlock();154 }155 }156 private boolean isTimedOut(Instant now, Data data) {157 return data.endTime.isBefore(now);158 }159 @Override160 public HttpResponse addToQueue(SessionRequest request) {161 Require.nonNull("New session request", request);162 Require.nonNull("Request id", request.getRequestId());163 TraceContext context = TraceSessionRequest.extract(tracer, request);164 try (Span span = context.createSpan("sessionqueue.add_to_queue")) {165 contexts.put(request.getRequestId(), context);166 Data data = injectIntoQueue(request);167 if (isTimedOut(Instant.now(), data)) {168 failDueToTimeout(request.getRequestId());169 }170 Either<SessionNotCreatedException, CreateSessionResponse> result;171 try {172 if (data.latch.await(requestTimeout.toMillis(), MILLISECONDS)) {173 result = data.result;174 } else {175 result = Either.left(new SessionNotCreatedException("New session request timed out"));176 }177 } catch (InterruptedException e) {178 Thread.currentThread().interrupt();179 result = Either.left(new SessionNotCreatedException("Interrupted when creating the session", e));180 } catch (RuntimeException e) {181 result = Either.left(new SessionNotCreatedException("An error occurred creating the session", e));182 }183 Lock writeLock = this.lock.writeLock();184 writeLock.lock();185 try {186 requests.remove(request.getRequestId());187 queue.remove(request);188 } finally {189 writeLock.unlock();190 }191 HttpResponse res = new HttpResponse();192 if (result.isRight()) {193 res.setContent(Contents.bytes(result.right().getDownstreamEncodedResponse()));194 } else {195 res.setStatus(HTTP_INTERNAL_ERROR)196 .setContent(Contents.asJson(Collections.singletonMap("value", result.left())));197 }198 return res;199 }200 }201 @VisibleForTesting202 Data injectIntoQueue(SessionRequest request) {203 Require.nonNull("Session request", request);204 Data data = new Data(request.getEnqueued());205 Lock writeLock = lock.writeLock();206 writeLock.lock();207 try {208 requests.put(request.getRequestId(), data);209 queue.addLast(request);210 } finally {211 writeLock.unlock();212 }213 bus.fire(new NewSessionRequestEvent(request.getRequestId()));214 return data;215 }216 @Override217 public boolean retryAddToQueue(SessionRequest request) {218 Require.nonNull("New session request", request);219 boolean added;220 TraceContext context = contexts.getOrDefault(request.getRequestId(), tracer.getCurrentContext());221 try (Span span = context.createSpan("sessionqueue.retry")) {222 Lock writeLock = lock.writeLock();223 writeLock.lock();224 try {225 if (!requests.containsKey(request.getRequestId())) {226 return false;227 }228 if (queue.contains(request)) {229 // No need to re-add this230 return true;231 } else {232 added = queue.offerFirst(request);233 }234 } finally {235 writeLock.unlock();236 }237 if (added) {238 bus.fire(new NewSessionRequestEvent(request.getRequestId()));239 }240 return added;241 }242 }243 @Override244 public Optional<SessionRequest> remove(RequestId reqId) {245 Require.nonNull("Request ID", reqId);246 Lock writeLock = lock.writeLock();247 writeLock.lock();248 try {249 Iterator<SessionRequest> iterator = queue.iterator();250 while (iterator.hasNext()) {251 SessionRequest req = iterator.next();252 if (reqId.equals(req.getRequestId())) {253 iterator.remove();254 return Optional.of(req);255 }256 }257 return Optional.empty();258 } finally {259 writeLock.unlock();260 }261 }262 @Override263 public Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes) {264 Require.nonNull("Stereotypes", stereotypes);265 Predicate<Capabilities> matchesStereotype =266 caps -> stereotypes.stream().anyMatch(stereotype -> slotMatcher.matches(stereotype, caps));267 Lock writeLock = lock.writeLock();268 writeLock.lock();269 try {270 Optional<SessionRequest> maybeRequest =271 queue.stream()272 .filter(req -> req.getDesiredCapabilities().stream().anyMatch(matchesStereotype))273 .findFirst();274 maybeRequest.ifPresent(req -> {275 this.remove(req.getRequestId());276 });277 return maybeRequest;278 } finally {279 writeLock.unlock();280 }281 }282 @Override283 public void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result) {284 Require.nonNull("New session request", reqId);285 Require.nonNull("Result", result);286 TraceContext context = contexts.getOrDefault(reqId, tracer.getCurrentContext());287 try (Span span = context.createSpan("sessionqueue.completed")) {288 Lock readLock = lock.readLock();289 readLock.lock();290 Data data;291 try {292 data = requests.get(reqId);293 } finally {294 readLock.unlock();295 }296 if (data == null) {297 return;298 }299 Lock writeLock = lock.writeLock();300 writeLock.lock();301 try {302 requests.remove(reqId);303 queue.removeIf(req -> reqId.equals(req.getRequestId()));304 contexts.remove(reqId);305 } finally {306 writeLock.unlock();307 }308 if (result.isLeft()) {309 bus.fire(new NewSessionRejectedEvent(new NewSessionErrorResponse(reqId, result.left().getMessage())));310 }311 data.setResult(result);312 }313 }314 @Override315 public int clearQueue() {316 Lock writeLock = lock.writeLock();317 writeLock.lock();318 try {319 int size = queue.size();320 queue.clear();321 requests.forEach((reqId, data) -> {322 data.setResult(Either.left(new SessionNotCreatedException("Request queue was cleared")));323 bus.fire(new NewSessionRejectedEvent(324 new NewSessionErrorResponse(reqId, "New session queue was forcibly cleared")));325 });326 requests.clear();327 return size;328 } finally {329 writeLock.unlock();330 }331 }332 @Override333 public List<SessionRequestCapability> getQueueContents() {334 Lock readLock = lock.readLock();335 readLock.lock();336 try {337 return queue.stream()338 .map(req ->339 new SessionRequestCapability(req.getRequestId(), req.getDesiredCapabilities()))340 .collect(Collectors.toList());341 } finally {342 readLock.unlock();343 }344 }345 @ManagedAttribute(name = "NewSessionQueueSize")346 public int getQueueSize() {347 return queue.size();348 }349 @Override350 public boolean isReady() {351 return true;352 }353 @Override...

Full Screen

Full Screen

Source:RemoteNewSessionQueue.java Github

copy

Full Screen

...19import org.openqa.selenium.SessionNotCreatedException;20import org.openqa.selenium.grid.config.Config;21import org.openqa.selenium.grid.data.CreateSessionResponse;22import org.openqa.selenium.grid.data.RequestId;23import org.openqa.selenium.grid.data.SessionRequestCapability;24import org.openqa.selenium.grid.log.LoggingOptions;25import org.openqa.selenium.grid.security.AddSecretFilter;26import org.openqa.selenium.grid.security.Secret;27import org.openqa.selenium.grid.security.SecretOptions;28import org.openqa.selenium.grid.server.NetworkOptions;29import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;30import org.openqa.selenium.grid.data.SessionRequest;31import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;32import org.openqa.selenium.grid.web.Values;33import org.openqa.selenium.internal.Either;34import org.openqa.selenium.internal.Require;35import org.openqa.selenium.json.Json;36import org.openqa.selenium.json.TypeToken;37import org.openqa.selenium.remote.http.Contents;38import org.openqa.selenium.remote.http.Filter;39import org.openqa.selenium.remote.http.HttpClient;40import org.openqa.selenium.remote.http.HttpRequest;41import org.openqa.selenium.remote.http.HttpResponse;42import org.openqa.selenium.remote.tracing.HttpTracing;43import org.openqa.selenium.remote.tracing.Tracer;44import java.io.UncheckedIOException;45import java.lang.reflect.Type;46import java.net.MalformedURLException;47import java.net.URI;48import java.util.List;49import java.util.Optional;50import java.util.Set;51import static org.openqa.selenium.remote.http.HttpMethod.DELETE;52import static org.openqa.selenium.remote.http.HttpMethod.GET;53import static org.openqa.selenium.remote.http.HttpMethod.POST;54public class RemoteNewSessionQueue extends NewSessionQueue {55 private static final Type QUEUE_CONTENTS_TYPE = new TypeToken<List<SessionRequestCapability>>() {}.getType();56 private static final Json JSON = new Json();57 private final HttpClient client;58 private final Filter addSecret;59 public RemoteNewSessionQueue(Tracer tracer, HttpClient client, Secret registrationSecret) {60 super(tracer, registrationSecret);61 this.client = Require.nonNull("HTTP client", client);62 Require.nonNull("Registration secret", registrationSecret);63 this.addSecret = new AddSecretFilter(registrationSecret);64 }65 public static NewSessionQueue create(Config config) {66 Tracer tracer = new LoggingOptions(config).getTracer();67 URI uri = new NewSessionQueueOptions(config).getSessionQueueUri();68 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);69 SecretOptions secretOptions = new SecretOptions(config);70 Secret registrationSecret = secretOptions.getRegistrationSecret();71 try {72 return new RemoteNewSessionQueue(73 tracer,74 clientFactory.createClient(uri.toURL()),75 registrationSecret);76 } catch (MalformedURLException e) {77 throw new UncheckedIOException(e);78 }79 }80 @Override81 public HttpResponse addToQueue(SessionRequest request) {82 HttpRequest upstream = new HttpRequest(POST, "/se/grid/newsessionqueue/session");83 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);84 upstream.setContent(Contents.asJson(request));85 return client.with(addSecret).execute(upstream);86 }87 @Override88 public boolean retryAddToQueue(SessionRequest request) {89 Require.nonNull("Session request", request);90 HttpRequest upstream =91 new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/retry", request.getRequestId()));92 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);93 upstream.setContent(Contents.asJson(request));94 HttpResponse response = client.with(addSecret).execute(upstream);95 return Values.get(response, Boolean.class);96 }97 @Override98 public Optional<SessionRequest> remove(RequestId reqId) {99 HttpRequest upstream = new HttpRequest(POST, "/se/grid/newsessionqueue/session/" + reqId);100 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);101 HttpResponse response = client.with(addSecret).execute(upstream);102 if (response.isSuccessful()) {103 // TODO: This should work cleanly with just a TypeToken of <Optional<SessionRequest>>104 String rawValue = Contents.string(response);105 if (rawValue == null || rawValue.trim().isEmpty()) {106 return Optional.empty();107 }108 return Optional.of(JSON.toType(rawValue, SessionRequest.class));109 }110 return Optional.empty();111 }112 @Override113 public Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes) {114 Require.nonNull("Stereotypes", stereotypes);115 HttpRequest upstream = new HttpRequest(POST, "/se/grid/newsessionqueue/session/next")116 .setContent(Contents.asJson(stereotypes));117 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);118 HttpResponse response = client.with(addSecret).execute(upstream);119 SessionRequest value = Values.get(response, SessionRequest.class);120 return Optional.ofNullable(value);121 }122 @Override123 public void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result) {124 Require.nonNull("Request ID", reqId);125 Require.nonNull("Result", result);126 HttpRequest upstream;127 if (result.isRight()) {128 upstream = new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/success", reqId))129 .setContent(Contents.asJson(result.right()));130 } else {131 upstream = new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/failure", reqId))132 .setContent(Contents.asJson(result.left().getRawMessage()));133 }134 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);135 client.with(addSecret).execute(upstream);136 }137 @Override138 public int clearQueue() {139 HttpRequest upstream = new HttpRequest(DELETE, "/se/grid/newsessionqueue/queue");140 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);141 HttpResponse response = client.with(addSecret).execute(upstream);142 return Values.get(response, Integer.class);143 }144 @Override145 public List<SessionRequestCapability> getQueueContents() {146 HttpRequest upstream = new HttpRequest(GET, "/se/grid/newsessionqueue/queue");147 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);148 HttpResponse response = client.execute(upstream);149 return Values.get(response, QUEUE_CONTENTS_TYPE);150 }151 @Override152 public boolean isReady() {153 try {154 return client.execute(new HttpRequest(GET, "/readyz")).isSuccessful();155 } catch (RuntimeException e) {156 return false;157 }158 }159}...

Full Screen

Full Screen

Source:Grid.java Github

copy

Full Screen

...20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.ImmutableCapabilities;22import org.openqa.selenium.grid.data.DistributorStatus;23import org.openqa.selenium.grid.data.NodeStatus;24import org.openqa.selenium.grid.data.SessionRequestCapability;25import org.openqa.selenium.grid.data.Slot;26import org.openqa.selenium.grid.distributor.Distributor;27import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;28import org.openqa.selenium.internal.Require;29import org.openqa.selenium.json.Json;30import java.net.URI;31import java.util.ArrayList;32import java.util.Collection;33import java.util.HashMap;34import java.util.List;35import java.util.Map;36import java.util.Set;37import java.util.function.Supplier;38import java.util.stream.Collectors;39public class Grid {40 private static final Json JSON = new Json();41 private final URI uri;42 private final Supplier<DistributorStatus> distributorStatus;43 private final List<Set<Capabilities>> queueInfoList;44 private final String version;45 public Grid(46 Distributor distributor,47 NewSessionQueue newSessionQueue,48 URI uri,49 String version) {50 Require.nonNull("Distributor", distributor);51 this.uri = Require.nonNull("Grid's public URI", uri);52 NewSessionQueue sessionQueue = Require.nonNull("New session queue", newSessionQueue);53 this.queueInfoList = sessionQueue54 .getQueueContents()55 .stream()56 .map(SessionRequestCapability::getDesiredCapabilities)57 .collect(Collectors.toList());58 this.distributorStatus = Suppliers.memoize(distributor::getStatus);59 this.version = Require.nonNull("Grid's version", version);60 }61 public URI getUri() {62 return uri;63 }64 public String getVersion() {65 return version;66 }67 public List<Node> getNodes() {68 ImmutableList.Builder<Node> toReturn = ImmutableList.builder();69 for (NodeStatus status : distributorStatus.get().getNodes()) {70 Map<Capabilities, Integer> stereotypes = new HashMap<>();...

Full Screen

Full Screen

Source:NewSessionQueue.java Github

copy

Full Screen

...19import org.openqa.selenium.SessionNotCreatedException;20import org.openqa.selenium.grid.data.CreateSessionResponse;21import org.openqa.selenium.grid.data.RequestId;22import org.openqa.selenium.grid.data.SessionRequest;23import org.openqa.selenium.grid.data.SessionRequestCapability;24import org.openqa.selenium.grid.security.RequiresSecretFilter;25import org.openqa.selenium.grid.security.Secret;26import org.openqa.selenium.internal.Either;27import org.openqa.selenium.internal.Require;28import org.openqa.selenium.remote.http.HttpRequest;29import org.openqa.selenium.remote.http.HttpResponse;30import org.openqa.selenium.remote.http.Routable;31import org.openqa.selenium.remote.http.Route;32import org.openqa.selenium.remote.tracing.Tracer;33import org.openqa.selenium.status.HasReadyState;34import java.time.Instant;35import java.util.List;36import java.util.Map;37import java.util.Optional;38import java.util.Set;39import java.util.UUID;40import static org.openqa.selenium.remote.http.Route.combine;41import static org.openqa.selenium.remote.http.Route.delete;42import static org.openqa.selenium.remote.http.Route.get;43import static org.openqa.selenium.remote.http.Route.post;44public abstract class NewSessionQueue implements HasReadyState, Routable {45 protected final Tracer tracer;46 private final Route routes;47 protected NewSessionQueue(Tracer tracer, Secret registrationSecret) {48 this.tracer = Require.nonNull("Tracer", tracer);49 Require.nonNull("Registration secret", registrationSecret);50 RequiresSecretFilter requiresSecret = new RequiresSecretFilter(registrationSecret);51 routes = combine(52 post("/session")53 .to(() -> req -> {54 SessionRequest sessionRequest = new SessionRequest(55 new RequestId(UUID.randomUUID()),56 req,57 Instant.now()58 );59 return addToQueue(sessionRequest);60 }),61 post("/se/grid/newsessionqueue/session")62 .to(() -> new AddToSessionQueue(tracer, this))63 .with(requiresSecret),64 post("/se/grid/newsessionqueue/session/{requestId}/retry")65 .to(params -> new AddBackToSessionQueue(tracer, this, requestIdFrom(params)))66 .with(requiresSecret),67 post("/se/grid/newsessionqueue/session/{requestId}/failure")68 .to(params -> new SessionNotCreated(tracer, this, requestIdFrom(params)))69 .with(requiresSecret),70 post("/se/grid/newsessionqueue/session/{requestId}/success")71 .to(params -> new SessionCreated(tracer, this, requestIdFrom(params)))72 .with(requiresSecret),73 post("/se/grid/newsessionqueue/session/{requestId}")74 .to(params -> new RemoveFromSessionQueue(tracer, this, requestIdFrom(params)))75 .with(requiresSecret),76 post("/se/grid/newsessionqueue/session/next")77 .to(() -> new GetNextMatchingRequest(tracer, this))78 .with(requiresSecret),79 get("/se/grid/newsessionqueue/queue")80 .to(() -> new GetSessionQueue(tracer, this)),81 delete("/se/grid/newsessionqueue/queue")82 .to(() -> new ClearSessionQueue(tracer, this))83 .with(requiresSecret));84 }85 private RequestId requestIdFrom(Map<String, String> params) {86 return new RequestId(UUID.fromString(params.get("requestId")));87 }88 public abstract HttpResponse addToQueue(SessionRequest request);89 public abstract boolean retryAddToQueue(SessionRequest request);90 public abstract Optional<SessionRequest> remove(RequestId reqId);91 public abstract Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes);92 public abstract void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result);93 public abstract int clearQueue();94 public abstract List<SessionRequestCapability> getQueueContents();95 @Override96 public boolean matches(HttpRequest req) {97 return routes.matches(req);98 }99 @Override100 public HttpResponse execute(HttpRequest req) {101 return routes.execute(req);102 }103}...

Full Screen

Full Screen

Source:SessionRequestCapability.java Github

copy

Full Screen

...27import java.util.Set;28import java.util.StringJoiner;29import static java.util.Collections.unmodifiableMap;30import static java.util.Collections.unmodifiableSet;31public class SessionRequestCapability {32 private static final Type SET_OF_CAPABILITIES = new TypeToken<Set<Capabilities>>() {33 }.getType();34 private final RequestId requestId;35 private final Set<Capabilities> desiredCapabilities;36 public SessionRequestCapability(37 RequestId requestId,38 Set<Capabilities> desiredCapabilities) {39 this.requestId = Require.nonNull("Request ID", requestId);40 this.desiredCapabilities = unmodifiableSet(41 new LinkedHashSet<>(Require.nonNull("Capabilities", desiredCapabilities)));42 }43 public RequestId getRequestId() {44 return requestId;45 }46 public Set<Capabilities> getDesiredCapabilities() {47 return desiredCapabilities;48 }49 @Override50 public String toString() {51 return new StringJoiner(", ", SessionRequestCapability.class.getSimpleName() + "[", "]")52 .add("requestId=" + requestId)53 .add("desiredCapabilities=" + desiredCapabilities)54 .toString();55 }56 @Override57 public boolean equals(Object o) {58 if (!(o instanceof SessionRequestCapability)) {59 return false;60 }61 SessionRequestCapability that = (SessionRequestCapability) o;62 return this.requestId.equals(that.requestId) &&63 this.desiredCapabilities.equals(that.desiredCapabilities);64 }65 @Override66 public int hashCode() {67 return Objects.hash(requestId, desiredCapabilities);68 }69 private Map<String, Object> toJson() {70 Map<String, Object> toReturn = new HashMap<>();71 toReturn.put("requestId", requestId);72 toReturn.put("capabilities", desiredCapabilities);73 return unmodifiableMap(toReturn);74 }75 private static SessionRequestCapability fromJson(JsonInput input) {76 RequestId id = null;77 Set<Capabilities> capabilities = null;78 input.beginObject();79 while (input.hasNext()) {80 switch (input.nextName()) {81 case "capabilities":82 capabilities = input.read(SET_OF_CAPABILITIES);83 break;84 case "requestId":85 id = input.read(RequestId.class);86 break;87 default:88 input.skipValue();89 break;90 }91 }92 input.endObject();93 return new SessionRequestCapability(id, capabilities);94 }95}...

Full Screen

Full Screen

SessionRequestCapability

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.SessionRequest;2import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder;3import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder;4import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder;5import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder;6import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilder;7import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilder;8import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilderBuilder;9import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilderBuilder;10import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilderBuilder;11import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilderBuilder;12import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilderBuilder;13import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilderBuilderBuilderBuilder;14import org.openqa.selenium.grid.data.SessionRequest.SessionRequestBuilder.SessionRequestBuilderBuilder.SessionRequestBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilderBuilder.SessionRequestBuilderBuilderBuilder

Full Screen

Full Screen

SessionRequestCapability

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.SessionRequestCapability;2public class SessionRequestCapabilityExample {3 public static void main(String[] args) {4 SessionRequestCapability capability = new SessionRequestCapability("browserName", "firefox");5 System.out.println(capability.getName());6 System.out.println(capability.getValue());7 System.out.println(capability);8 }9}10Recommended Posts: Java | SetRequestAttribute() method of RequestDispatcher interface11Java | GetRequestAttribute() method of RequestDispatcher interface12Java | GetRequestDispatcher() method of ServletContext interface13Java | GetRequestURL() method of HttpServletRequest interface14Java | GetRequestURI() method of HttpServletRequest interface15Java | GetRequestPathInfo() method of HttpServletRequest interface16Java | GetRequestPathTranslated() method of HttpServletRequest interface17Java | GetRequestServletPath() method of HttpServletRequest interface18Java | GetRequestParameterMap() method of HttpServletRequest interface19Java | GetRequestParameterNames() method of HttpServletRequest interface20Java | GetRequestParameterValues() method of HttpServletRequest interface21Java | GetRequestParameter() method of HttpServletRequest interface22Java | GetRequestHeaderNames() method of HttpServletRequest interface23Java | GetRequestHeaders() method of HttpServletRequest interface24Java | GetRequestHeader() method of HttpServletRequest interface25Java | GetRequestCookies() method of HttpServletRequest interface26Java | GetRequestContentLength() method of HttpServletRequest interface27Java | GetRequestContentType() method of HttpServletRequest interface28Java | GetRequestCharacterEncoding() method of HttpServletRequest interface29Java | GetRequestLocale() method of HttpServletRequest interface30Java | GetRequestLocales() method of HttpServletRequest interface31Java | GetRequestRemoteUser() method of HttpServletRequest interface32Java | GetRequestRemoteAddr() method of HttpServletRequest interface33Java | GetRequestRemoteHost() method of HttpServletRequest interface34Java | GetRequestRemotePort() method of HttpServletRequest interface35Java | GetRequestScheme() method of HttpServletRequest interface36Java | GetRequestServerName() method of HttpServletRequest interface37Java | GetRequestServerPort() method of HttpServletRequest interface38Java | GetRequestContextPath() method of HttpServletRequest interface39Java | GetRequestAuthType() method of HttpServletRequest interface

Full Screen

Full Screen

SessionRequestCapability

Using AI Code Generation

copy

Full Screen

1 SessionRequestCapability capabilities = new SessionRequestCapability();2 capabilities.setBrowserName("chrome");3 capabilities.setBrowserVersion("latest");4 capabilities.setPlatformName("windows 10");5 capabilities.setAcceptInsecureCerts(true);6 capabilities.setPageLoadStrategy("normal");7 capabilities.setStrictFileInteractability(false);8 capabilities.setUnhandledPromptBehavior("accept");9 capabilities.setTimeouts(Timeouts.of(Duration.ofSeconds(30)));10 capabilities.setProxy(Proxy.of("localhost:3128"));11 capabilities.setUnprocessed();12 capabilities.setSetWindowRect(true);13 capabilities.setImplicitWait(Duration.ofSeconds(15));14 capabilities.setPageLoadTimeout(Duration.ofSeconds(30));15 capabilities.setScriptTimeout(Duration.ofSeconds(30));16 capabilities.setUnprocessed();17 capabilities.setPageLoadStrategy("normal");18 capabilities.setStrictFileInteractability(false);19 capabilities.setUnhandledPromptBehavior("accept");20 capabilities.setTimeouts(Timeouts.of(Duration.ofSeconds(30)));21 capabilities.setProxy(Proxy.of("localhost:3128"));22 capabilities.setUnprocessed();23 capabilities.setSetWindowRect(true);24 capabilities.setImplicitWait(Duration.ofSeconds(15));25 capabilities.setPageLoadTimeout(Duration.ofSeconds(30));26 capabilities.setScriptTimeout(Duration.ofSeconds(30));27 capabilities.setUnprocessed();28 capabilities.setPageLoadStrategy("normal");29 capabilities.setStrictFileInteractability(false);30 capabilities.setUnhandledPromptBehavior("accept");31 capabilities.setTimeouts(Timeouts.of(Duration.ofSeconds(30)));32 capabilities.setProxy(Proxy.of("localhost:3128"));33 capabilities.setUnprocessed();34 capabilities.setSetWindowRect(true);35 capabilities.setImplicitWait(Duration.ofSeconds(15));36 capabilities.setPageLoadTimeout(Duration.ofSeconds(30));37 capabilities.setScriptTimeout(Duration.ofSeconds(30));38 capabilities.setUnprocessed();39 capabilities.setPageLoadStrategy("normal");40 capabilities.setStrictFileInteractability(false);41 capabilities.setUnhandledPromptBehavior("accept");42 capabilities.setTimeouts(Timeouts.of(Duration.ofSeconds(30)));43 capabilities.setProxy(Proxy.of("localhost:3128"));44 capabilities.setUnprocessed();45 capabilities.setSetWindowRect(true);46 capabilities.setImplicitWait(Duration.ofSeconds(15));47 capabilities.setPageLoadTimeout(Duration.ofSeconds(30));48 capabilities.setScriptTimeout(Duration.ofSeconds(30));49 capabilities.setUnprocessed();

Full Screen

Full Screen

SessionRequestCapability

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.data.SessionRequestCapability;2SessionRequestCapability cap = new SessionRequestCapability("browserName", "chrome");3String name = cap.getName();4String value = cap.getValue();5cap.setName("browserVersion");6cap.setValue("v90");7boolean isMandatory = cap.isMandatory();8cap.setMandatory(true);9boolean isMandatory = cap.isMandatory();10Map<String, Object> map = cap.asMap();11String json = cap.toJson();12String json = cap.toString();

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 SessionRequestCapability

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