Best Selenium code snippet using org.openqa.selenium.grid.data.CreateSessionRequest.getDesiredCapabilities
Source:LocalDistributor.java
...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<>();525 attributeMap.put(526 AttributeKey.LOGGER_CLASS.getKey(),527 EventAttribute.setValue(getClass().getName()));528 span.setAttribute(AttributeKey.REQUEST_ID.getKey(), reqId.toString());...
Source:LocalNode.java
...246 Map<String, EventAttributeValue> attributeMap = new HashMap<>();247 attributeMap248 .put(AttributeKey.LOGGER_CLASS.getKey(), EventAttribute.setValue(getClass().getName()));249 attributeMap.put("session.request.capabilities",250 EventAttribute.setValue(sessionRequest.getDesiredCapabilities().toString()));251 attributeMap.put("session.request.downstreamdialect",252 EventAttribute.setValue(sessionRequest.getDownstreamDialects().toString()));253 int currentSessionCount = getCurrentSessionCount();254 span.setAttribute("current.session.count", currentSessionCount);255 attributeMap.put("current.session.count", EventAttribute.setValue(currentSessionCount));256 if (getCurrentSessionCount() >= maxSessionCount) {257 span.setAttribute("error", true);258 span.setStatus(Status.RESOURCE_EXHAUSTED);259 attributeMap.put("max.session.count", EventAttribute.setValue(maxSessionCount));260 span.addEvent("Max session count reached", attributeMap);261 return Either.left(new RetrySessionRequestException("Max session count reached."));262 }263 if (isDraining()) {264 span.setStatus(Status.UNAVAILABLE.withDescription("The node is draining. Cannot accept new sessions."));265 return Either.left(266 new RetrySessionRequestException("The node is draining. Cannot accept new sessions."));267 }268 // Identify possible slots to use as quickly as possible to enable concurrent session starting269 SessionSlot slotToUse = null;270 synchronized (factories) {271 for (SessionSlot factory : factories) {272 if (!factory.isAvailable() || !factory.test(sessionRequest.getDesiredCapabilities())) {273 continue;274 }275 factory.reserve();276 slotToUse = factory;277 break;278 }279 }280 if (slotToUse == null) {281 span.setAttribute("error", true);282 span.setStatus(Status.NOT_FOUND);283 span.addEvent("No slot matched the requested capabilities. ", attributeMap);284 return Either.left(285 new RetrySessionRequestException("No slot matched the requested capabilities."));286 }...
Source:AddingNodesTest.java
...262 Objects.requireNonNull(sessionRequest);263 if (running != null) {264 return Either.left(new SessionNotCreatedException("Session already exists"));265 }266 Session session = factory.apply(sessionRequest.getDesiredCapabilities());267 running = session;268 return Either.right(269 new CreateSessionResponse(270 session,271 CapabilityResponseEncoder.getEncoder(W3C).apply(session)));272 }273 @Override274 public HttpResponse executeWebDriverCommand(HttpRequest req) {275 throw new UnsupportedOperationException("executeWebDriverCommand");276 }277 @Override278 public HttpResponse uploadFile(HttpRequest req, SessionId id) {279 throw new UnsupportedOperationException("uploadFile");280 }...
Source:OneShotNode.java
...144 public Either<WebDriverException, CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {145 if (driver != null) {146 throw new IllegalStateException("Only expected one session at a time");147 }148 Optional<WebDriver> driver = driverInfo.createDriver(sessionRequest.getDesiredCapabilities());149 if (!driver.isPresent()) {150 return Either.left(new WebDriverException("Unable to create a driver instance"));151 }152 if (!(driver.get() instanceof RemoteWebDriver)) {153 driver.get().quit();154 return Either.left(new WebDriverException("Driver is not a RemoteWebDriver instance"));155 }156 this.driver = (RemoteWebDriver) driver.get();157 this.sessionId = this.driver.getSessionId();158 this.client = extractHttpClient(this.driver);159 this.capabilities = rewriteCapabilities(this.driver);160 this.sessionStart = Instant.now();161 LOG.info("Encoded response: " + JSON.toJson(ImmutableMap.of(162 "value", ImmutableMap.of(...
Source:InMemorySession.java
...112 public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {113 Require.nonNull("Session creation request", sessionRequest);114 // Assume the blob fits in the available memory.115 try {116 if (!provider.canCreateDriverInstanceFor(sessionRequest.getDesiredCapabilities())) {117 return Optional.empty();118 }119 WebDriver driver = provider.newInstance(sessionRequest.getDesiredCapabilities());120 // Prefer the OSS dialect.121 Set<Dialect> downstreamDialects = sessionRequest.getDownstreamDialects();122 Dialect downstream = downstreamDialects.contains(Dialect.OSS) || downstreamDialects.isEmpty() ?123 Dialect.OSS :124 downstreamDialects.iterator().next();125 return Optional.of(126 new InMemorySession(driver, sessionRequest.getDesiredCapabilities(), downstream));127 } catch (IllegalStateException e) {128 return Optional.empty();129 }130 }131 @Override132 public String toString() {133 return getClass() + " (provider: " + provider + ")";134 }135 }136 private class PretendDriverSessions implements DriverSessions {137 private final Session session;138 private PretendDriverSessions() {139 this.session = new ActualSession();140 }...
Source:SessionSlot.java
...113 public Either<WebDriverException, ActiveSession> apply(CreateSessionRequest sessionRequest) {114 if (currentSession != null) {115 return Either.left(new RetrySessionRequestException("Slot is busy. Try another slot."));116 }117 if (!test(sessionRequest.getDesiredCapabilities())) {118 return Either.left(new SessionNotCreatedException("New session request capabilities do not "119 + "match the stereotype."));120 }121 try {122 Either<WebDriverException, ActiveSession> possibleSession = factory.apply(sessionRequest);123 if (possibleSession.isRight()) {124 ActiveSession session = possibleSession.right();125 currentSession = session;126 return Either.right(session);127 } else {128 return Either.left(possibleSession.left());129 }130 } catch (Exception e) {131 LOG.log(Level.WARNING, "Unable to create session", e);...
Source:TestSessionFactory.java
...50 }51 @Override52 public Either<WebDriverException, ActiveSession> apply(CreateSessionRequest sessionRequest) {53 SessionId id = new SessionId(UUID.randomUUID());54 Session session = sessionGenerator.apply(id, sessionRequest.getDesiredCapabilities());55 URL url;56 try {57 url = session.getUri().toURL();58 } catch (MalformedURLException e) {59 throw new UncheckedIOException(e);60 }61 Dialect downstream = sessionRequest.getDownstreamDialects().contains(W3C) ?62 W3C :63 sessionRequest.getDownstreamDialects().iterator().next();64 BaseActiveSession activeSession = new BaseActiveSession(65 session.getId(),66 url,67 downstream,68 W3C,...
Source:CreateSessionRequest.java
...43 }44 public Set<Dialect> getDownstreamDialects() {45 return downstreamDialects;46 }47 public Capabilities getDesiredCapabilities() {48 return capabilities;49 }50 public Map<String, Object> getMetadata() {51 return metadata;52 }53 private static CreateSessionRequest fromJson(JsonInput input) {54 Set<Dialect> downstreamDialects = null;55 Capabilities capabilities = null;56 Map<String, Object> metadata = null;57 input.beginObject();58 while (input.hasNext()) {59 switch (input.nextName()) {60 case "desiredCapabilities":61 capabilities = input.read(Capabilities.class);...
getDesiredCapabilities
Using AI Code Generation
1package com.selenium4beginners.java.webdriver;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.HashMap;5import java.util.Map;6import org.openqa.selenium.Capabilities;7import org.openqa.selenium.MutableCapabilities;8import org.openqa.selenium.WebDriver;9import org.openqa.selenium.WebDriverException;10import org.openqa.selenium.chrome.ChromeDriver;11import org.openqa.selenium.chrome.ChromeOptions;12import org.openqa.selenium.devtools.DevTools;13import org.openqa.selenium.devtools.v91.browser.Browser;14import org.openqa.selenium.devtools.v91.browser.model.BrowserInfo;15import org.openqa.selenium.devtools.v91.browser.model.PermissionType;16import org.openqa.selenium.devtools.v91.browser.model.PermissionSetting;17import org.openqa.selenium.devtools.v91.log.Log;18import org.openqa.selenium.devtools.v91.network.Network;19import org.openqa.selenium.devtools.v91.network.model.ConnectionType;20import org.openqa.selenium.devtools.v91.network.model.ConnectionTypeChanged;21import org.openqa.selenium.devtools.v91.network.model.Request;22import org.openqa.selenium.devtools.v91.network.model.Response;23import org.openqa.selenium.devtools.v91.network.model.ResourceType;24import org.openqa.selenium.devtools.v91.page.Page;25import org.openqa.selenium.devtools.v91.page.model.FrameId;26import org.openqa.selenium.devtools.v91.page.model.FrameNavigated;27import org.openqa.selenium.devtools.v91.page.model.FrameStartedLoading;28import org.openqa.selenium.devtools.v91.performance.Performance;29import org.openqa.selenium.devtools.v91.performance.model.Metric;30import org.openqa.selenium.devtools.v91.performance.model.MetricName;31import org.openqa.selenium.devtools.v91.security.Security;32import org.openqa.selenium.devtools.v91.security.model.SecurityStateChanged;33import org.openqa.selenium.devtools.v91.security.model.SecurityState;34import org.openqa.selenium.devtools.v91.security.model.MixedContentType;35import org.openqa.selenium.devtools.v91.security.model.MixedContentResolutionStatus;36import org.openqa.selenium.devtools.v91.security.model.SanitizationDetails;37import org.openqa.selenium.devtools.v91.security.model.SanitizationStatus;38import org.openqa.selenium.devtools.v91.security.model.InsecureContentStatus;39import org.openqa.selenium.devtools.v91.security.model.SecurityStateExplanation;40import org.openqa.selenium.devtools.v91.security.model.SecurityStateDetails;41import org.openqa.selenium.devtools.v91.storage.Storage;42import org.openqa.selenium.devtools.v91.storage.model.CacheStorageContentUpdated;43import org.openqa.selenium.devtools.v91.storage.model.CacheStorageListUpdated;44import org.openqa
getDesiredCapabilities
Using AI Code Generation
1import org.openqa.selenium.Capabilities;2import org.openqa.selenium.grid.data.CreateSessionRequest;3CreateSessionRequest request = new CreateSessionRequest();4Capabilities capabilities = request.getDesiredCapabilities();5System.out.println(capabilities);6{browserName=chrome, version=, platform=ANY}7import org.openqa.selenium.Capabilities;8import org.openqa.selenium.grid.data.CreateSessionRequest;9import org.openqa.selenium.remote.DesiredCapabilities;10CreateSessionRequest request = new CreateSessionRequest();11DesiredCapabilities capabilities = (DesiredCapabilities) request.getDesiredCapabilities();12System.out.println(capabilities);13{browserName=chrome, version=, platform=ANY}14import org.openqa.selenium.Capabilities;15import org.openqa.selenium.grid.data.CreateSessionRequest;16import org.openqa.selenium.remote.DesiredCapabilities;17CreateSessionRequest request = new CreateSessionRequest();18DesiredCapabilities capabilities = (DesiredCapabilities) request.getDesiredCapabilities();19capabilities.setCapability("browserName", "chrome");20capabilities.setCapability("platform", "windows");21System.out.println(capabilities);22{browserName=chrome, version=, platform=windows}23import org.openqa.selenium.Capabilities;24import org.openqa.selenium.grid.data.CreateSessionRequest;25import org.openqa.selenium.remote.DesiredCapabilities;26CreateSessionRequest request = new CreateSessionRequest();27DesiredCapabilities capabilities = (DesiredCapabilities) request.getDesiredCapabilities();28capabilities.setCapability("browserName", "chrome");29capabilities.setCapability("platform", "windows");30capabilities.setCapability("version", "latest");31System.out.println(capabilities);32{browserName=chrome, version=latest, platform=windows}33import org
getDesiredCapabilities
Using AI Code Generation
1DesiredCapabilities capabilities = new DesiredCapabilities();2capabilities.setCapability("browserName", "firefox");3capabilities.setCapability("platform", Platform.LINUX);4capabilities.setCapability("version", "3.6");5capabilities.setCapability("javascriptEnabled", true);6capabilities.setCapability("acceptSslCerts", true);7DesiredCapabilities capabilities = new DesiredCapabilities();8capabilities.setCapability("browserName", "firefox");9capabilities.setCapability("platform", Platform.LINUX);10capabilities.setCapability("version", "3.6");11capabilities.setCapability("javascriptEnabled", true);12capabilities.setCapability("acceptSslCerts", true);13DesiredCapabilities capabilities = new DesiredCapabilities();14capabilities.setCapability("browserName", "firefox");15capabilities.setCapability("platform", Platform.LINUX);16capabilities.setCapability("version", "3.6");17capabilities.setCapability("javascriptEnabled", true);18capabilities.setCapability("acceptSslCerts", true);
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!