Best Selenium code snippet using org.openqa.selenium.grid.web.PathResource.list
Source:HTMLLauncher.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.server.htmlrunner;18import com.beust.jcommander.JCommander;19import com.beust.jcommander.Parameter;20import com.beust.jcommander.ParameterException;21import com.beust.jcommander.internal.Console;22import com.google.common.collect.ImmutableMap;23import com.thoughtworks.selenium.Selenium;24import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;25import org.openqa.selenium.By;26import org.openqa.selenium.WebDriver;27import org.openqa.selenium.WebElement;28import org.openqa.selenium.chrome.ChromeDriver;29import org.openqa.selenium.edge.EdgeDriver;30import org.openqa.selenium.firefox.FirefoxDriver;31import org.openqa.selenium.firefox.FirefoxOptions;32import org.openqa.selenium.grid.config.MapConfig;33import org.openqa.selenium.grid.server.BaseServerOptions;34import org.openqa.selenium.grid.server.Server;35import org.openqa.selenium.grid.web.NoHandler;36import org.openqa.selenium.grid.web.PathResource;37import org.openqa.selenium.grid.web.ResourceHandler;38import org.openqa.selenium.ie.InternetExplorerDriver;39import org.openqa.selenium.jre.server.JreServer;40import org.openqa.selenium.json.Json;41import org.openqa.selenium.net.PortProber;42import org.openqa.selenium.opera.OperaDriver;43import org.openqa.selenium.remote.http.Route;44import org.openqa.selenium.safari.SafariDriver;45import java.io.File;46import java.io.IOException;47import java.io.Writer;48import java.net.HttpURLConnection;49import java.net.URL;50import java.net.URLConnection;51import java.nio.file.Files;52import java.nio.file.Path;53import java.nio.file.Paths;54import java.util.List;55import java.util.logging.Level;56import java.util.logging.Logger;57import static java.util.concurrent.TimeUnit.SECONDS;58/**59 * Runs HTML Selenium test suites.60 */61public class HTMLLauncher {62 // java -jar selenium-server-standalone-<version-number>.jar -htmlSuite "*firefox"63 // "http://www.google.com" "c:\absolute\path\to\my\HTMLSuite.html"64 // "c:\absolute\path\to\my\results.html"65 private static Logger log = Logger.getLogger(HTMLLauncher.class.getName());66 private Server<?> server;67 /**68 * Launches a single HTML Selenium test suite.69 *70 * @param browser - the browserString ("*firefox", "*iexplore" or an executable path)71 * @param startURL - the start URL for the browser72 * @param suiteURL - the relative URL to the HTML suite73 * @param outputFile - The file to which we'll output the HTML results74 * @param timeoutInSeconds - the amount of time (in seconds) to wait for the browser to finish75 * @return PASS or FAIL76 * @throws IOException if we can't write the output file77 */78 public String runHTMLSuite(79 String browser,80 String startURL,81 String suiteURL,82 File outputFile,83 long timeoutInSeconds,84 String userExtensions) throws IOException {85 File parent = outputFile.getParentFile();86 if (parent != null && !parent.exists()) {87 parent.mkdirs();88 }89 if (outputFile.exists() && !outputFile.canWrite()) {90 throw new IOException("Can't write to outputFile: " + outputFile.getAbsolutePath());91 }92 long timeoutInMs = 1000L * timeoutInSeconds;93 if (timeoutInMs < 0) {94 log.warning("Looks like the timeout overflowed, so resetting it to the maximum.");95 timeoutInMs = Long.MAX_VALUE;96 }97 WebDriver driver = null;98 try {99 driver = createDriver(browser);100 URL suiteUrl = determineSuiteUrl(startURL, suiteURL);101 driver.get(suiteUrl.toString());102 Selenium selenium = new WebDriverBackedSelenium(driver, startURL);103 selenium.setTimeout(String.valueOf(timeoutInMs));104 if (userExtensions != null) {105 selenium.setExtensionJs(userExtensions);106 }107 List<WebElement> allTables = driver.findElements(By.id("suiteTable"));108 if (allTables.isEmpty()) {109 throw new RuntimeException("Unable to find suite table: " + driver.getPageSource());110 }111 Results results = new CoreTestSuite(suiteUrl.toString()).run(driver, selenium, new URL(startURL));112 HTMLTestResults htmlResults = results.toSuiteResult();113 try (Writer writer = Files.newBufferedWriter(outputFile.toPath())) {114 htmlResults.write(writer);115 }116 return results.isSuccessful() ? "PASSED" : "FAILED";117 } finally {118 if (server != null) {119 try {120 server.stop();121 } catch (Exception e) {122 // Nothing sane to do. Log the error and carry on123 log.log(Level.INFO, "Exception shutting down server. You may ignore this.", e);124 }125 }126 if (driver != null) {127 driver.quit();128 }129 }130 }131 private URL determineSuiteUrl(String startURL, String suiteURL) throws IOException {132 if (suiteURL.startsWith("https://") || suiteURL.startsWith("http://")) {133 return verifySuiteUrl(new URL(suiteURL));134 }135 // Is the suiteURL a file?136 Path path = Paths.get(suiteURL).toAbsolutePath();137 if (Files.exists(path)) {138 // Not all drivers can read files from the disk, so we need to host the suite somewhere.139 int port = PortProber.findFreePort();140 BaseServerOptions options = new BaseServerOptions(141 new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", port))));142 Json json = new Json();143 server = new JreServer(144 options,145 Route.prefix("/test")146 .to(Route.combine(new ResourceHandler(new PathResource(path.getParent()))))147 .fallbackTo(() -> new NoHandler(json)));148 PortProber.waitForPortUp(port, 15, SECONDS);149 URL serverUrl = server.getUrl();150 return new URL(serverUrl.getProtocol(), serverUrl.getHost(), serverUrl.getPort(),151 "/tests/");152 }153 // Well then, it must be a URL relative to whatever the browserUrl. Probe and find out.154 URL browser = new URL(startURL);155 return verifySuiteUrl(new URL(browser, suiteURL));156 }157 private URL verifySuiteUrl(URL url) throws IOException {158 // Now probe.159 URLConnection connection = url.openConnection();160 if (!(connection instanceof HttpURLConnection)) {161 throw new IOException("The HTMLLauncher only supports relative HTTP URLs");162 }163 HttpURLConnection httpConnection = (HttpURLConnection) connection;164 httpConnection.setInstanceFollowRedirects(true);165 httpConnection.setRequestMethod("HEAD");166 int responseCode = httpConnection.getResponseCode();167 if (responseCode != HttpURLConnection.HTTP_OK) {168 throw new IOException("Invalid suite URL: " + url);169 }170 return url;171 }172 private static String printUsage(JCommander commander) {173 StringBuilder usage = new StringBuilder();174 commander.setConsole(new Console() {175 @Override176 public void print(String msg) {177 usage.append(msg);178 }179 @Override180 public void println(String msg) {181 usage.append(msg).append("\n");182 }183 @Override184 public char[] readPassword(boolean echoInput) {185 throw new UnsupportedOperationException("readPassword");186 }187 });188 commander.usage();189 return usage.toString();190 }191 public static int mainInt(String... args) throws Exception {192 Args processed = new Args();193 JCommander jCommander = new JCommander(processed);194 jCommander.setCaseSensitiveOptions(false);195 try {196 jCommander.parse(args);197 } catch (ParameterException ex) {198 System.err.print(ex.getMessage() + "\n" + printUsage(jCommander));199 return 0;200 }201 if (processed.help) {202 System.err.print(printUsage(jCommander));203 return 0;204 }205 warnAboutLegacyOptions(processed);206 Path resultsPath = Paths.get(processed.htmlSuite.get(3));207 Files.createDirectories(resultsPath);208 String suite = processed.htmlSuite.get(2);209 String startURL = processed.htmlSuite.get(1);210 String[] browsers = new String[] {processed.htmlSuite.get(0)};211 HTMLLauncher launcher = new HTMLLauncher();212 boolean passed = true;213 for (String browser : browsers) {214 // Turns out that Windows doesn't like "*" in a path name215 String reportFileName = browser.contains(" ") ? browser.substring(0, browser.indexOf(' ')) : browser;216 File results = resultsPath.resolve(reportFileName.substring(1) + ".results.html").toFile();217 String result = "FAILED";218 try {219 long timeout;220 try {221 timeout = Long.parseLong(processed.timeout);222 } catch (NumberFormatException e) {223 System.err.println("Timeout does not appear to be a number: " + processed.timeout);224 return -2;225 }226 result = launcher.runHTMLSuite(browser, startURL, suite, results, timeout, processed.userExtensions);227 passed &= "PASSED".equals(result);228 } catch (Throwable e) {229 log.log(Level.WARNING, "Test of browser failed: " + browser, e);230 passed = false;231 }232 }233 return passed ? 1 : 0;234 }235 private static void warnAboutLegacyOptions(Args processed) {236 if (processed.multiWindow) {237 System.err.println("Multi-window mode is no longer used as an option and will be ignored.");238 }239 if (processed.port != 0) {240 System.err.println("Port is no longer used as an option and will be ignored.");241 }242 if (processed.trustAllSSLCertificates) {243 System.err.println("Trusting all ssl certificates is no longer a user-settable option.");244 }245 }246 public static void main(String[] args) throws Exception {247 System.exit(mainInt(args));248 }249 private WebDriver createDriver(String browser) {250 String[] parts = browser.split(" ", 2);251 browser = parts[0];252 switch (browser) {253 case "*chrome":254 case "*firefox":255 case "*firefoxproxy":256 case "*firefoxchrome":257 case "*pifirefox":258 FirefoxOptions options = new FirefoxOptions().setLegacy(false);259 if (parts.length > 1) {260 options.setBinary(parts[1]);261 }262 return new FirefoxDriver(options);263 case "*iehta":264 case "*iexplore":265 case "*iexploreproxy":266 case "*piiexplore":267 return new InternetExplorerDriver();268 case "*googlechrome":269 return new ChromeDriver();270 case "*MicrosoftEdge":271 return new EdgeDriver();272 case "*opera":273 case "*operablink":274 return new OperaDriver();275 case "*safari":276 case "*safariproxy":277 return new SafariDriver();278 default:279 throw new RuntimeException("Unrecognized browser: " + browser);280 }281 }282 public static class Args {283 @Parameter(284 names = "-htmlSuite",285 required = true,286 arity = 4,287 description = "Run an HTML Suite: \"*browser\" \"http://baseUrl.com\" \"path\\to\\HTMLSuite.html\" \"path\\to\\report\\dir\"")288 private List<String> htmlSuite;289 @Parameter(290 names = "-timeout",291 description = "Timeout to use in seconds")292 private String timeout = "30";293 @Parameter(294 names = "-userExtensions",295 description = "User extensions to attempt to use."296 )297 private String userExtensions;298 @Parameter(299 names = "-multiwindow",300 hidden = true)301 private boolean multiWindow = true;302 @Parameter(303 names = "-port",304 hidden = true)305 private Integer port = 0;306 @Parameter(307 names = "-trustAllSSLCertificates",308 hidden = true)309 private boolean trustAllSSLCertificates;310 @Parameter(311 names = {"-help", "--help", "-h"},312 description = "This help message",313 help = true)314 private boolean help;315 }316}...
Source:PathResource.java
...52 public boolean isDirectory() {53 return Files.isDirectory(base);54 }55 @Override56 public Set<Resource> list() {57 try (Stream<Path> files = Files.list(base)) {58 return files.map(PathResource::new).collect(toImmutableSet());59 } catch (IOException e) {60 throw new UncheckedIOException(e);61 }62 }63 @Override64 public Optional<byte[]> read() {65 if (!Files.exists(base)) {66 return Optional.empty();67 }68 try {69 return Optional.of(Files.readAllBytes(base));70 } catch (IOException e) {71 throw new UncheckedIOException(e);...
list
Using AI Code Generation
1import org.openqa.selenium.grid.web.PathResource;2import org.openqa.selenium.remote.http.HttpMethod;3import org.openqa.selenium.remote.http.HttpRequest;4import org.openqa.selenium.remote.http.HttpResponse;5import org.openqa.selenium.remote.http.Route;6import java.util.List;7public class TestPathResource {8 public static void main(String[] args) {9 PathResource resource = new PathResource(HttpMethod.GET, "/foo/bar");10 HttpRequest request = new HttpRequest(HttpMethod.GET, "/foo/bar");11 HttpResponse response = resource.execute(request);12 System.out.println(response.getStatus());13 List<Route> routes = resource.getRoutes();14 System.out.println(routes.size());15 }16}
list
Using AI Code Generation
1package org.openqa.selenium.grid.web;2import com.google.common.collect.ImmutableList;3import java.util.List;4import java.util.Objects;5public class PathResource implements Resource {6 private final String path;7 private final List<Resource> children;8 public PathResource(String path, Resource... children) {9 this.path = Objects.requireNonNull(path);10 this.children = ImmutableList.copyOf(children);11 }12 public String getPath() {13 return path;14 }15 public List<Resource> list() {16 return children;17 }18}19package org.openqa.selenium.grid.web;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.ImmutableCapabilities;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.WebDriverException;24import org.openqa.selenium.grid.config.Config;25import org.openqa.selenium.grid.config.ConfigException;26import org.openqa.selenium.grid.data.CreateSessionResponse;27import org.openqa.selenium.grid.data.Session;28import org.openqa.selenium.grid.data.SessionClosedEvent;29import org.openqa.selenium.grid.data.SessionCreatedEvent;30import org.openqa.selenium.grid.distributor.Distributor;31import org.openqa.selenium.grid.log.LoggingOptions;32import org.openqa.selenium.grid.node.ActiveSessionFactory;33import org.openqa.selenium.grid.node.Node;34import org.openqa.selenium.grid.node.local.LocalNode;35import org.openqa.selenium.grid.node.local.SessionFactory;36import org.openqa.selenium.grid.security.Secret;37import org.openqa.selenium.grid.sessionmap.SessionMap;38import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;39import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;40import org.openqa.selenium.grid.web.CommandHandler;41import org.openqa.selenium.grid.web.CommandHandlerException;42import org.openqa.selenium.grid.web.CommandHandlerRoute;43import org.openqa.selenium.grid.web.Routable;44import org.openqa.selenium.grid.web.Routes;45import org.openqa.selenium.internal.Require;46import org.openqa.selenium.json.Json;47import org.openqa.selenium.json.JsonException;48import org.openqa.selenium.json.JsonInput;49import org.openqa.selenium.remote.Dialect;50import org.openqa.selenium.remote.ErrorCodes;51import org.openqa.selenium.remote.http.Contents;52import org.openqa.selenium.remote.http.HttpHandler;53import org.openqa.selenium.remote.http.HttpRequest;54import org.openqa.selenium.remote.http.HttpResponse;55import org.openqa.selenium.remote.tracing.Tracer;56import java.io.IOException;57import java.io.Reader;58import java.io.UncheckedIOException;59import java.net.URI;60import java.net.URISyntaxException;61import java.time.Duration;62import java.util.Map;63import java.util.Objects;64import
list
Using AI Code Generation
1import org.openqa.selenium.grid.web.PathResource;2import java.io.File;3import java.io.IOException;4import java.nio.file.Path;5import java.nio.file.Paths;6import java.util.List;7import java.util.stream.Collectors;8import java.util.stream.Stream;9public class ListFiles {10 public static void main(String[] args) throws IOException {11 Path path = Paths.get(new File("").getAbsolutePath());12 List<PathResource> pathResources = PathResource.list(path);13 List<Path> paths = pathResources.stream().map(PathResource::getPath).collect(Collectors.toList());14 System.out.println("List of files and directories in the current directory");15 paths.forEach(System.out::println);16 }17}18Related posts: Java Program to Write to a File Java Program to Read a File Java Program to Read a File Line by Line Java Program to Count the Number of Lines in a Text File Java Program to Find the Size (Length) of a File Java Program to Delete a File Java Program to Copy a File Java Program to Append Text to an Existing File Java Program to Delete a File Java Program to Copy a File Java Program to Append Text to an Existing File Java Program to Read a File Line by Line Java Program to Count the Number of Lines in a Text File Java Program to Find the Size (Length) of a File Java Program to Delete a File Java Program to Copy a File Java Program to Append Text to an Existing File Java Program to Read a File Line by Line Java Program to Count the Number of Lines in a Text File Java Program to Find the Size (Length) of a File Java Program to Delete a File Java Program to Copy a File Java Program to Append Text to an Existing File Java Program to Read a File Line by Line Java Program to Count the Number of Lines in a Text File Java Program to Find the Size (Length) of a File Java Program to Delete a File Java Program to Copy a File Java Program to Append Text to an Existing File
list
Using AI Code Generation
1import org.openqa.selenium.grid.web.PathResource;2import org.openqa.selenium.grid.web.Routable;3import org.openqa.selenium.net.UrlChecker;4import org.openqa.selenium.remote.http.Contents;5import org.openqa.selenium.remote.http.HttpHandler;6import org.openqa.selenium.remote.http.HttpRequest;7import org.openqa.selenium.remote.http.HttpResponse;8import org.openqa.selenium.remote.http.Route;9import java.util.ArrayList;10import java.util.List;11import java.util.Objects;12import static org.openqa.selenium.remote.http.Contents.utf8String;13import static org.openqa.selenium.remote.http.HttpMethod.GET;14import static org.openqa.selenium.remote.http.HttpMethod.OPTIONS;15@AutoService(Routable.class)16public class ResourceRoutes implements Routable {17 private final PathResource resources;18 public ResourceRoutes(PathResource resources) {19 this.resources = Objects.requireNonNull(resources);20 }21 public Route get() {22 return new Route(GET, "/")23 .to(() -> req -> {24 List<String> resourceList = new ArrayList<>();25 resources.list(resourceList, req.getUri(), true);26 String resourceString = "";27 for (String resource : resourceList) {28";29 }30 return new HttpResponse().setContent(utf8String(resourceString));31 });32 }33}
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!!