How to use Main class of org.openqa.selenium.grid package

Best Selenium code snippet using org.openqa.selenium.grid.Main

Source:HTMLLauncher.java Github

copy

Full Screen

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}...

Full Screen

Full Screen

Source:NettyAppServer.java Github

copy

Full Screen

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.environment.webserver;18import com.google.common.collect.ImmutableMap;19import org.openqa.selenium.grid.config.CompoundConfig;20import org.openqa.selenium.grid.config.Config;21import org.openqa.selenium.grid.config.MapConfig;22import org.openqa.selenium.grid.config.MemoizedConfig;23import org.openqa.selenium.grid.server.BaseServerOptions;24import org.openqa.selenium.grid.server.Server;25import org.openqa.selenium.internal.Require;26import org.openqa.selenium.io.TemporaryFilesystem;27import org.openqa.selenium.json.Json;28import org.openqa.selenium.net.PortProber;29import org.openqa.selenium.netty.server.NettyServer;30import org.openqa.selenium.remote.http.Contents;31import org.openqa.selenium.remote.http.HttpClient;32import org.openqa.selenium.remote.http.HttpHandler;33import org.openqa.selenium.remote.http.HttpMethod;34import org.openqa.selenium.remote.http.HttpRequest;35import org.openqa.selenium.remote.http.HttpResponse;36import java.io.File;37import java.io.IOException;38import java.io.UncheckedIOException;39import java.net.MalformedURLException;40import java.net.URL;41import static com.google.common.net.HttpHeaders.CONTENT_TYPE;42import static java.nio.charset.StandardCharsets.UTF_8;43import static java.util.Collections.singletonMap;44import static org.openqa.selenium.json.Json.JSON_UTF_8;45import static org.openqa.selenium.remote.http.Contents.bytes;46import static org.openqa.selenium.remote.http.Contents.string;47public class NettyAppServer implements AppServer {48 private final static Config sslConfig = new MapConfig(49 singletonMap("server", singletonMap("https-self-signed", true)));50 private final Server<?> server;51 private final Server<?> secure;52 public NettyAppServer() {53 Config config = createDefaultConfig();54 BaseServerOptions options = new BaseServerOptions(config);55 File tempDir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("generated", "pages");56 HttpHandler handler = new HandlersForTests(57 options.getHostname().orElse("localhost"),58 options.getPort(),59 tempDir.toPath());60 server = new NettyServer(options, handler);61 Config secureConfig = new CompoundConfig(sslConfig, createDefaultConfig());62 BaseServerOptions secureOptions = new BaseServerOptions(secureConfig);63 HttpHandler secureHandler = new HandlersForTests(64 secureOptions.getHostname().orElse("localhost"),65 secureOptions.getPort(),66 tempDir.toPath());67 secure = new NettyServer(secureOptions, secureHandler);68 }69 public NettyAppServer(HttpHandler handler) {70 this(71 createDefaultConfig(),72 Require.nonNull("Handler", handler));73 }74 private NettyAppServer(Config config, HttpHandler handler) {75 Require.nonNull("Config", config);76 Require.nonNull("Handler", handler);77 server = new NettyServer(new BaseServerOptions(new MemoizedConfig(config)), handler);78 secure = null;79 }80 private static Config createDefaultConfig() {81 return new MemoizedConfig(new MapConfig(82 singletonMap("server", singletonMap("port", PortProber.findFreePort()))));83 }84 @Override85 public void start() {86 server.start();87 if (secure != null) {88 secure.start();89 }90 }91 @Override92 public void stop() {93 server.stop();94 if (secure != null) {95 secure.stop();96 }97 }98 @Override99 public String whereIs(String relativeUrl) {100 return createUrl(server, "http", getHostName(), relativeUrl);101 }102 @Override103 public String whereElseIs(String relativeUrl) {104 return createUrl(server, "http", getAlternateHostName(), relativeUrl);105 }106 @Override107 public String whereIsSecure(String relativeUrl) {108 if (secure == null) {109 throw new IllegalStateException("Server not configured to return HTTPS url");110 }111 return createUrl(secure, "https", getHostName(), relativeUrl);112 }113 @Override114 public String whereIsWithCredentials(String relativeUrl, String user, String password) {115 return String.format(116 "http://%s:%s@%s:%d/%s",117 user,118 password,119 getHostName(),120 server.getUrl().getPort(),121 relativeUrl);122 }123 private String createUrl(Server<?> server, String protocol, String hostName, String relativeUrl) {124 if (!relativeUrl.startsWith("/")) {125 relativeUrl = "/" + relativeUrl;126 }127 try {128 return new URL(129 protocol,130 hostName,131 server.getUrl().getPort(),132 relativeUrl133 ).toString();134 } catch (MalformedURLException e) {135 throw new UncheckedIOException(e);136 }137 }138 @Override139 public String create(Page page) {140 try (HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/")))) {141 HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage");142 request.setHeader(CONTENT_TYPE, JSON_UTF_8);143 request.setContent(Contents.asJson(ImmutableMap.of("content", page.toString())));144 HttpResponse response = client.execute(request);145 return string(response);146 } catch (IOException ex) {147 throw new RuntimeException(ex);148 }149 }150 @Override151 public String getHostName() {152 return AppServer.detectHostname();153 }154 @Override155 public String getAlternateHostName() {156 return AppServer.detectAlternateHostname();157 }158 public static void main(String[] args) {159 MemoizedConfig config = new MemoizedConfig(new MapConfig(singletonMap("server", singletonMap("port", 2310))));160 BaseServerOptions options = new BaseServerOptions(config);161 HttpHandler handler = new HandlersForTests(162 options.getHostname().orElse("localhost"),163 options.getPort(),164 TemporaryFilesystem.getDefaultTmpFS().createTempDir("netty", "server").toPath());165 NettyAppServer server = new NettyAppServer(166 config,167 handler);168 server.start();169 System.out.printf("Server started. Root URL: %s%n", server.whereIs("/"));170 }171}...

Full Screen

Full Screen

Source:JreAppServer.java Github

copy

Full Screen

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.environment.webserver;18import com.google.common.collect.ImmutableMap;19import org.openqa.selenium.grid.config.MapConfig;20import org.openqa.selenium.grid.server.BaseServerOptions;21import org.openqa.selenium.grid.server.Server;22import org.openqa.selenium.grid.web.PathResource;23import org.openqa.selenium.grid.web.ResourceHandler;24import org.openqa.selenium.internal.Require;25import org.openqa.selenium.jre.server.JreServer;26import org.openqa.selenium.json.Json;27import org.openqa.selenium.net.PortProber;28import org.openqa.selenium.remote.http.HttpClient;29import org.openqa.selenium.remote.http.HttpHandler;30import org.openqa.selenium.remote.http.HttpMethod;31import org.openqa.selenium.remote.http.HttpRequest;32import org.openqa.selenium.remote.http.HttpResponse;33import org.openqa.selenium.remote.http.Route;34import java.io.IOException;35import java.io.UncheckedIOException;36import java.net.MalformedURLException;37import java.net.URL;38import java.nio.file.Path;39import static com.google.common.net.HttpHeaders.CONTENT_TYPE;40import static com.google.common.net.MediaType.JSON_UTF_8;41import static java.nio.charset.StandardCharsets.UTF_8;42import static java.util.Collections.singletonMap;43import static org.openqa.selenium.build.InProject.locate;44import static org.openqa.selenium.remote.http.Contents.bytes;45import static org.openqa.selenium.remote.http.Contents.string;46import static org.openqa.selenium.remote.http.Route.get;47import static org.openqa.selenium.remote.http.Route.matching;48import static org.openqa.selenium.remote.http.Route.post;49public class JreAppServer implements AppServer {50 private final Server<?> server;51 public JreAppServer() {52 this(emulateJettyAppServer());53 }54 public JreAppServer(HttpHandler handler) {55 Require.nonNull("Handler", handler);56 int port = PortProber.findFreePort();57 server = new JreServer(58 new BaseServerOptions(new MapConfig(singletonMap("server", singletonMap("port", port)))),59 handler);60 }61 private static Route emulateJettyAppServer() {62 Path common = locate("common/src/web").toAbsolutePath();63 return Route.combine(64 new ResourceHandler(new PathResource(common)),65 get("/encoding").to(EncodingHandler::new),66 matching(req -> req.getUri().startsWith("/page/")).to(PageHandler::new),67 get("/redirect").to(() -> new RedirectHandler()),68 get("/sleep").to(SleepingHandler::new),69 post("/upload").to(UploadHandler::new));70 }71 @Override72 public void start() {73 server.start();74 }75 @Override76 public void stop() {77 server.stop();78 }79 @Override80 public String whereIs(String relativeUrl) {81 return createUrl("http", getHostName(), relativeUrl);82 }83 @Override84 public String whereElseIs(String relativeUrl) {85 return createUrl("http", getAlternateHostName(), relativeUrl);86 }87 @Override88 public String whereIsSecure(String relativeUrl) {89 return createUrl("https", getHostName(), relativeUrl);90 }91 @Override92 public String whereIsWithCredentials(String relativeUrl, String user, String password) {93 return String.format94 ("http://%s:%s@%s:%d/%s",95 user,96 password,97 getHostName(),98 server.getUrl().getPort(),99 relativeUrl);100 }101 private String createUrl(String protocol, String hostName, String relativeUrl) {102 if (!relativeUrl.startsWith("/")) {103 relativeUrl = "/" + relativeUrl;104 }105 try {106 return new URL(107 protocol,108 hostName,109 server.getUrl().getPort(),110 relativeUrl)111 .toString();112 } catch (MalformedURLException e) {113 throw new UncheckedIOException(e);114 }115 }116 @Override117 public String create(Page page) {118 try {119 byte[] data = new Json()120 .toJson(ImmutableMap.of("content", page.toString()))121 .getBytes(UTF_8);122 HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/")));123 HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage");124 request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());125 request.setContent(bytes(data));126 HttpResponse response = client.execute(request);127 return string(response);128 } catch (IOException ex) {129 throw new RuntimeException(ex);130 }131 }132 @Override133 public String getHostName() {134 return "localhost";135 }136 @Override137 public String getAlternateHostName() {138 throw new UnsupportedOperationException("getAlternateHostName");139 }140 public static void main(String[] args) {141 JreAppServer server = new JreAppServer();142 server.start();143 System.out.println(server.whereIs("/"));144 }145}...

Full Screen

Full Screen

Source:SeleniumServer.java Github

copy

Full Screen

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.remote.server;18import static java.net.HttpURLConnection.HTTP_NOT_FOUND;19import static java.util.concurrent.TimeUnit.SECONDS;20import static org.openqa.selenium.remote.http.Contents.utf8String;21import static org.openqa.selenium.remote.http.Route.combine;22import com.beust.jcommander.JCommander;23import org.openqa.selenium.grid.config.AnnotatedConfig;24import org.openqa.selenium.grid.server.BaseServer;25import org.openqa.selenium.grid.server.BaseServerFlags;26import org.openqa.selenium.grid.server.BaseServerOptions;27import org.openqa.selenium.grid.server.HelpFlags;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.server.jmx.JMXHelper;33import org.openqa.selenium.remote.server.jmx.ManagedService;34import java.io.UncheckedIOException;35import java.lang.reflect.Constructor;36import java.util.Map;37import java.util.logging.Logger;38import javax.management.ObjectName;39import javax.servlet.Servlet;40/**41 * Provides a server that can launch and manage selenium sessions.42 */43@ManagedService(objectName = "org.seleniumhq.server:type=SeleniumServer")44public class SeleniumServer extends BaseServer {45 private final static Logger LOG = Logger.getLogger(SeleniumServer.class.getName());46 private final BaseServerOptions configuration;47 private Map<String, Class<? extends Servlet>> extraServlets;48 private ObjectName objectName;49 private ActiveSessions allSessions;50 public SeleniumServer(BaseServerOptions configuration) {51 super(configuration);52 this.configuration = configuration;53 objectName = new JMXHelper().register(this).getObjectName();54 }55 private Routable getRcHandler(ActiveSessions sessions) {56 try {57 Class<? extends Routable> rcHandler = Class.forName(58 "com.thoughtworks.selenium.webdriven.WebDriverBackedSeleniumHandler",59 false,60 getClass().getClassLoader())61 .asSubclass(Routable.class);62 Constructor<? extends Routable> constructor = rcHandler.getConstructor(ActiveSessions.class);63 LOG.info("Bound legacy RC support");64 return constructor.newInstance(sessions);65 } catch (ReflectiveOperationException e) {66 // Do nothing.67 }68 return new Routable() {69 @Override70 public boolean matches(HttpRequest req) {71 return false;72 }73 @Override74 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {75 return null;76 }77 };78 }79 @Override80 public BaseServer start() {81 long inactiveSessionTimeoutSeconds = Long.MAX_VALUE / 1000;82 NewSessionPipeline pipeline = DefaultPipeline.createDefaultPipeline().create();83 allSessions = new ActiveSessions(inactiveSessionTimeoutSeconds, SECONDS);84 Servlet driverServlet = new WebDriverServlet(allSessions, pipeline);85 addServlet(driverServlet, "/wd/hub/*");86 addServlet(driverServlet, "/webdriver/*");87 Route route = Route.matching(req -> true)88 .to(() -> req -> new HttpResponse()89 .setStatus(HTTP_NOT_FOUND)90 .setContent(utf8String("Not handler found for " + req)));91 Routable rcHandler = getRcHandler(allSessions);92 if (rcHandler != null) {93 route = combine(route, rcHandler);94 }95 setHandler(route);96 super.start();97 LOG.info(String.format("Selenium Server is up and running on port %s", configuration.getPort()));98 return this;99 }100 /**101 * Stops the Jetty server102 */103 @Override104 public void stop() {105 try {106 super.stop();107 } finally {108 new JMXHelper().unregister(objectName);109 stopAllBrowsers();110 }111 }112 private void stopAllBrowsers() {113 if (allSessions == null) {114 return;115 }116 allSessions.getAllSessions().parallelStream()117 .forEach(session -> {118 try {119 session.stop();120 } catch (Exception ignored) {121 // Ignored122 }123 });124 }125 public static void main(String[] args) {126 HelpFlags helpFlags = new HelpFlags();127 BaseServerFlags flags = new BaseServerFlags(4444);128 JCommander commands = JCommander.newBuilder().addObject(flags).addObject(helpFlags).build();129 commands.parse(args);130 if (helpFlags.displayHelp(commands, System.err)) {131 return;132 }133 SeleniumServer server = new SeleniumServer(new BaseServerOptions(new AnnotatedConfig(flags)));134 server.start();135 }136}...

Full Screen

Full Screen

Main

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.Main;2import org.openqa.selenium.grid.config.Config;3import org.openqa.selenium.grid.config.MapConfig;4import org.openqa.selenium.grid.server.Server;5import org.openqa.selenium.remote.http.HttpClient;6import org.openqa.selenium.remote.http.HttpRequest;7import org.openqa.selenium.remote.http.HttpResponse;8import org.openqa.selenium.remote.http.Route;9import java.io.IOException;10import java.net.URL;11import java.util.Map;12import java.util.function.Supplier;13public class Example {14 public static void main(String[] args) {15 Map<String, String> rawConfig = Map.of(16 );17 Config config = new MapConfig(rawConfig);18 Server<?> server = Main.createServer(config);19 HttpClient client = server.getClient();20 Route route = Route.get("/").to(() -> req -> {21 HttpResponse res = new HttpResponse();22 res.setContent("Hello World!");23 return res;24 });25 HttpRequest req = new HttpRequest("GET", "/");26 HttpResponse res = client.execute(route, req);27 System.out.println(res.getContentString());28 }29}

Full Screen

Full Screen

Main

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.Main;2public class SeleniumGrid {3 public static void main(String[] args) {4 Main.main(args);5 }6}7import org.openqa.selenium.grid.Main;8public class SeleniumGrid {9 public static void main(String[] args) {10 Main.main(args);11 }12}13package org.openqa.selenium.grid;14import java.io.IOException;15import java.util.logging.Logger;16import org.openqa.selenium.grid.config.Config;17import org.openqa.selenium.grid.config.ConfigException;18import org.openqa.selenium.grid.config.TomlConfig;19import org.openqa.selenium.grid.data.Session;20import org.openqa.selenium.grid.data.SessionRequest;21import org.openqa.selenium.grid.node.Node;22import org.openqa.selenium.grid.node.local.LocalNode;23import org.openqa.selenium.grid.router.Router;24import org.openqa.selenium.grid.router.RouterOptions;25import org.openqa.selenium.grid.server.BaseServerOptions;26import org.openqa.selenium.grid.server.Server;27import org.openqa.selenium.grid.server.ServerOptions;28import org.openqa.selenium.grid.web.CommandHandler;29import org.openqa.selenium.grid.web.CommandHandlerException;30import org.openqa.selenium.grid.web.Routes;31import org.openqa.selenium.internal.Require;32import org.openqa.selenium.remote.http.HttpHandler;33import org.openqa.selenium.remote.http.HttpRequest;34import org.openqa.selenium.remote.http.HttpResponse;35import org.openqa.selenium.remote.tracing.Tracer;36import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;37import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracerFactory;38import org.openqa.selenium.remote.tracing.opentelemetry.config.OpenTelemetryConfiguration;39import org.openqa.selenium.remote.tracing.opentelemetry.config.OpenTelemetryConfigurationBuilder;40import org.openqa.selenium.remote.tracing.opentelemetry.config.OpenTelemetryConfigurationBuilder.EnvironmentConfigurationSource;41import org.openqa.selenium.remote.tracing.opentelemetry.config.OpenTelemetryConfigurationBuilder.SystemPropertiesConfigurationSource;42import org.openqa.selenium.remote.tracing.opentelemetry.config.OpenTelemetryConfigurationBuilder.YamlFileConfigurationSource;43import org.openqa.selenium.remote.tracing.opentelemetry.exporter.OpenTelemetryExporter;44import org.openqa.selenium.remote.tracing.opentelemetry.exporter.OpenTelemetryExporterFactory;45import org.openqa.selenium.remote.tracing.opentelemetry.exporter.OpenTelemetryExporterOptions;46import org.openqa.selenium.remote.tracing.opentelemetry.exporter.zipkin.ZipkinExporterFactory;47import org.openqa.selenium.remote.tracing.opentelemetry.exporter.zipkin.ZipkinExporterOptions;48import org.openqa.selenium.remote.tracing.opente

Full Screen

Full Screen

Main

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.Main;2public class SeleniumServer {3 public static void main(String[] args) {4 Main.main(args);5 }6}7{8 {9 },10 {11 }12}

Full Screen

Full Screen
copy
1EvalClassName[] evalClassName;2ArrayList<EvalClassName> list;3evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);4list = new ArrayList<>(Arrays.asList(evalClassName));5
Full Screen
copy
1mapper.enable(SerializationFeature.INDENT_OUTPUT);2
Full Screen
copy
1System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));2
Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in Main

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