How to use execute method of org.openqa.selenium.grid.node.Drain class

Best Selenium code snippet using org.openqa.selenium.grid.node.Drain.execute

Source:SauceNode.java Github

copy

Full Screen

...328 throw new IOException(e);329 }330 }331 @Override332 public HttpResponse executeWebDriverCommand(HttpRequest req) {333 // True enough to be good enough334 SessionId id = getSessionId(req.getUri()).map(SessionId::new)335 .orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req));336 SessionSlot slot = currentSessions.getIfPresent(id);337 if (slot == null) {338 throw new NoSuchSessionException("Cannot find session with id: " + id);339 }340 ActiveSession activeSession = slot.getSession();341 if (activeSession.getClass().getName().contains("RelaySessionFactory")) {342 HttpResponse toReturn = slot.execute(req);343 if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) {344 stop(id);345 }346 return toReturn;347 }348 SauceDockerSession session = (SauceDockerSession) activeSession;349 SauceCommandInfo.Builder builder = new SauceCommandInfo.Builder();350 builder.setStartTime(Instant.now().toEpochMilli());351 HttpResponse toReturn = slot.execute(req);352 if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) {353 stop(id);354 builder.setScreenshotId(-1);355 } else {356 // Only taking screenshots after a url has been loaded357 if (!session.canTakeScreenshot() && req.getMethod() == POST358 && req.getUri().endsWith("/url")) {359 session.enableScreenshots();360 }361 int screenshotId = takeScreenshot(session, req, slot);362 builder.setScreenshotId(screenshotId);363 }364 Map<String, Object> parsedResponse =365 JSON.toType(new InputStreamReader(toReturn.getContent().get()), MAP_TYPE);366 builder.setRequest(getRequestContents(req))367 .setResult(parsedResponse)368 .setPath(req.getUri().replace(String.format("/session/%s", id), ""))369 .setHttpStatus(toReturn.getStatus())370 .setHttpMethod(req.getMethod().name())371 .setStatusCode(0);372 if (parsedResponse.containsKey("value") && parsedResponse.get("value") != null373 && parsedResponse.get("value").toString().contains("error")) {374 builder.setStatusCode(1);375 }376 builder.setEndTime(Instant.now().toEpochMilli());377 session.addSauceCommandInfo(builder.build());378 return toReturn;379 }380 @Override381 public HttpResponse uploadFile(HttpRequest req, SessionId id) {382 // When the session is running in a Docker container, the upload file command383 // needs to be forwarded to the container as well.384 SessionSlot slot = currentSessions.getIfPresent(id);385 if (slot != null && slot.getSession() instanceof SauceDockerSession) {386 return executeWebDriverCommand(req);387 }388 Map<String, Object> incoming = JSON.toType(string(req), Json.MAP_TYPE);389 File tempDir;390 try {391 TemporaryFilesystem tempfs = getTemporaryFilesystem(id);392 tempDir = tempfs.createTempDir("upload", "file");393 Zip.unzip((String) incoming.get("file"), tempDir);394 } catch (IOException e) {395 throw new UncheckedIOException(e);396 }397 // Select the first file398 File[] allFiles = tempDir.listFiles();399 if (allFiles == null) {400 throw new WebDriverException(401 String.format("Cannot access temporary directory for uploaded files %s", tempDir));402 }403 if (allFiles.length != 1) {404 throw new WebDriverException(405 String.format("Expected there to be only 1 file. There were: %s", allFiles.length));406 }407 ImmutableMap<String, Object> result = ImmutableMap.of(408 "value", allFiles[0].getAbsolutePath());409 return new HttpResponse().setContent(asJson(result));410 }411 @Override412 public void stop(SessionId id) throws NoSuchSessionException {413 Require.nonNull("Session ID", id);414 SessionSlot slot = currentSessions.getIfPresent(id);415 if (slot == null) {416 throw new NoSuchSessionException("Cannot find session with id: " + id);417 }418 currentSessions.invalidate(id);419 tempFileSystems.invalidate(id);420 }421 private void stopAllSessions() {422 if (currentSessions.size() > 0) {423 LOG.info("Trying to stop all running sessions before shutting down...");424 currentSessions.invalidateAll();425 }426 }427 private Session createExternalSession(ActiveSession other, URI externalUri, boolean isSupportingCdp) {428 Capabilities toUse = ImmutableCapabilities.copyOf(other.getCapabilities());429 // Rewrite the se:options if necessary to send the cdp url back430 if (isSupportingCdp) {431 String cdpPath = String.format("/session/%s/se/cdp", other.getId());432 toUse = new PersistentCapabilities(toUse).setCapability("se:cdp", rewrite(cdpPath));433 }434 return new Session(other.getId(), externalUri, other.getStereotype(), toUse, Instant.now());435 }436 private URI rewrite(String path) {437 try {438 String scheme = "https".equals(gridUri.getScheme()) ? "wss" : "ws";439 return new URI(440 scheme,441 gridUri.getUserInfo(),442 gridUri.getHost(),443 gridUri.getPort(),444 path,445 null,446 null);447 } catch (URISyntaxException e) {448 throw new RuntimeException(e);449 }450 }451 @Override452 public NodeStatus getStatus() {453 Set<Slot> slots = factories.stream()454 .map(slot -> {455 Instant lastStarted = Instant.EPOCH;456 Session session = null;457 if (!slot.isAvailable()) {458 ActiveSession activeSession = slot.getSession();459 if (activeSession != null) {460 lastStarted = activeSession.getStartTime();461 session = new Session(462 activeSession.getId(),463 activeSession.getUri(),464 slot.getStereotype(),465 activeSession.getCapabilities(),466 activeSession.getStartTime());467 }468 }469 return new Slot(470 new SlotId(getId(), slot.getId()),471 slot.getStereotype(),472 lastStarted,473 session);474 })475 .collect(toImmutableSet());476 return new NodeStatus(477 getId(),478 externalUri,479 maxSessionCount,480 slots,481 isDraining() ? DRAINING : UP,482 heartbeatPeriod,483 getNodeVersion(),484 getOsInfo());485 }486 @Override487 public HealthCheck getHealthCheck() {488 return healthCheck;489 }490 @Override491 public void drain() {492 bus.fire(new NodeDrainStarted(getId()));493 draining = true;494 int currentSessionCount = getCurrentSessionCount();495 if (currentSessionCount == 0) {496 LOG.info("Firing node drain complete message");497 bus.fire(new NodeDrainComplete(getId()));498 } else {499 pendingSessions.set(currentSessionCount);500 }501 }502 private Map<String, Object> toJson() {503 return ImmutableMap.of(504 "id", getId(),505 "uri", externalUri,506 "maxSessions", maxSessionCount,507 "draining", isDraining(),508 "capabilities", factories.stream()509 .map(SessionSlot::getStereotype)510 .collect(Collectors.toSet()));511 }512 public static class Builder {513 private final Tracer tracer;514 private final EventBus bus;515 private final URI uri;516 private final URI gridUri;517 private final Secret registrationSecret;518 private final ImmutableList.Builder<SessionSlot> factories;519 private int maxCount = Runtime.getRuntime().availableProcessors() * 5;520 private Ticker ticker = Ticker.systemTicker();521 private Duration sessionTimeout = Duration.ofMinutes(5);522 private HealthCheck healthCheck;523 private Duration heartbeatPeriod = Duration.ofSeconds(NodeOptions.DEFAULT_HEARTBEAT_PERIOD);524 private Builder(525 Tracer tracer,526 EventBus bus,527 URI uri,528 URI gridUri,529 Secret registrationSecret) {530 this.tracer = Require.nonNull("Tracer", tracer);531 this.bus = Require.nonNull("Event bus", bus);532 this.uri = Require.nonNull("Remote node URI", uri);533 this.gridUri = Require.nonNull("Grid URI", gridUri);534 this.registrationSecret = Require.nonNull("Registration secret", registrationSecret);535 this.factories = ImmutableList.builder();536 }537 public SauceNode.Builder add(Capabilities stereotype, SessionFactory factory) {538 Require.nonNull("Capabilities", stereotype);539 Require.nonNull("Session factory", factory);540 factories.add(new SessionSlot(bus, stereotype, factory));541 return this;542 }543 public SauceNode.Builder maximumConcurrentSessions(int maxCount) {544 this.maxCount = Require.positive("Max session count", maxCount);545 return this;546 }547 public SauceNode.Builder sessionTimeout(Duration timeout) {548 sessionTimeout = timeout;549 return this;550 }551 public SauceNode.Builder heartbeatPeriod(Duration heartbeatPeriod) {552 this.heartbeatPeriod = heartbeatPeriod;553 return this;554 }555 public SauceNode build() {556 return new SauceNode(557 tracer,558 bus,559 uri,560 gridUri,561 healthCheck,562 maxCount,563 ticker,564 sessionTimeout,565 heartbeatPeriod,566 factories.build(),567 registrationSecret);568 }569 }570 private Object getRequestContents(HttpRequest httpRequest) {571 String reqContents = string(httpRequest);572 if (reqContents.isEmpty()) {573 return Collections.emptyMap();574 }575 return JSON.toType(reqContents, MAP_TYPE);576 }577 private int takeScreenshot(SauceDockerSession session, HttpRequest req, SessionSlot slot) {578 Optional<DockerAssetsPath> path = ofNullable(session.getAssetsPath());579 if (session.canTakeScreenshot() && shouldTakeScreenshot(req.getMethod(), req.getUri())580 && path.isPresent()) {581 HttpRequest screenshotRequest =582 new HttpRequest(GET, String.format("/session/%s/screenshot", session.getId()));583 HttpResponse screenshotResponse = slot.execute(screenshotRequest);584 int screenshotId = session.increaseScreenshotCount();585 String containerPath = path.get().getContainerPath(session.getId());586 String filePathPng = String.format(587 "%s/%s%s.png",588 containerPath,589 formatScreenshotId(screenshotId),590 "screenshot");591 String screenshotContent = string(screenshotResponse).trim();592 Map<String, Object> parsed = JSON.toType(screenshotContent, MAP_TYPE);593 String pngContent;594 if (parsed.containsKey("value")) {595 pngContent = (String) parsed.get("value");596 } else {597 pngContent = JSON.toType(screenshotContent, OBJECT_TYPE);598 }599 try {600 Files.createDirectories(Paths.get(containerPath));601 Files.copy(602 FILE.convertFromBase64Png(pngContent).toPath(),603 Paths.get(filePathPng),604 StandardCopyOption.REPLACE_EXISTING);605 } catch (Exception e) {606 LOG.log(Level.WARNING, "Error saving screenshot", e);607 }608 return screenshotId;609 }610 return -1;611 }612 private String formatScreenshotId(int count) {613 String screenshotCount = String.valueOf(count);614 return ("0000" + screenshotCount).substring(screenshotCount.length());615 }616 private boolean shouldTakeScreenshot(HttpMethod httpMethod, String requestUri) {617 // https://www.w3.org/TR/webdriver1/#list-of-endpoints618 ImmutableListMultimap<String, HttpMethod> commandChangesPage =619 ImmutableListMultimap.<String, HttpMethod>builder()620 .put("/url", POST)621 .put("/forward", POST)622 .put("/back", POST)623 .put("/refresh", POST)624 .put("/execute", POST)625 .put("/click", POST)626 .put("/frame", POST)627 .put("/parent", POST)628 .put("/rect", POST)629 .put("/maximize", POST)630 .put("/minimize", POST)631 .put("/fullscreen", POST)632 .put("/clear", POST)633 .put("/value", POST)634 .put("/actions", POST)635 .put("/alert", POST)636 .put("/window", POST)637 .put("/window", DELETE)638 .build();...

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.node.Drain;2import org.openqa.selenium.remote.http.HttpClient;3import org.openqa.selenium.remote.http.HttpRequest;4import org.openqa.selenium.remote.http.HttpResponse;5import org.openqa.selenium.remote.http.Route;6import java.io.IOException;7import java.net.URI;8import java.util.Objects;9import java.util.concurrent.TimeUnit;10public class TestDrain {11 private static final HttpClient.Factory FACTORY = HttpClient.Factory.createDefault();12 private static final Route<HttpResponse> DRAIN_ROUTE = new Drain(FACTORY, BASE_URI);13 public static void main(String[] args) throws IOException {14 HttpRequest request = new HttpRequest("POST", "/drain");15 HttpResponse response = DRAIN_ROUTE.execute(request);16 System.out.println(response.getStatus());17 }18}

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.node.Drain;2public class DrainNode {3 public static void main(String[] args) throws Exception {4 String nodeConfig = "nodeconfig.json";5 String role = "node";6 System.out.println("Draining node: " + node);7 Drain.main(new String[] {hub, node, nodeConfig, role});8 }9}10{11 {12 }13 "configuration": {14 },15}16import org.openqa.selenium.grid

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1{2 {3 }4 "configuration": {5 },6 "custom": {},7 "slotCounts": {8 },9}

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 method in Drain

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful