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

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

Source:ProxySettingTest.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;18import com.google.common.base.Joiner;19import com.google.common.net.HostAndPort;20import io.netty.channel.ChannelHandlerContext;21import io.netty.handler.codec.http.HttpObject;22import io.netty.handler.codec.http.HttpRequest;23import org.junit.After;24import org.junit.Before;25import org.junit.Test;26import org.littleshoot.proxy.HttpFilters;27import org.littleshoot.proxy.HttpFiltersAdapter;28import org.littleshoot.proxy.HttpFiltersSourceAdapter;29import org.littleshoot.proxy.HttpProxyServer;30import org.littleshoot.proxy.impl.DefaultHttpProxyServer;31import org.openqa.selenium.grid.config.MapConfig;32import org.openqa.selenium.grid.server.BaseServerOptions;33import org.openqa.selenium.grid.server.Server;34import org.openqa.selenium.jre.server.JreServer;35import org.openqa.selenium.net.NetworkUtils;36import org.openqa.selenium.net.PortProber;37import org.openqa.selenium.remote.http.Contents;38import org.openqa.selenium.remote.http.HttpHandler;39import org.openqa.selenium.remote.http.HttpResponse;40import org.openqa.selenium.testing.Ignore;41import org.openqa.selenium.testing.JUnit4TestBase;42import org.openqa.selenium.testing.NeedsLocalEnvironment;43import org.openqa.selenium.testing.NoDriverAfterTest;44import org.openqa.selenium.testing.NoDriverBeforeTest;45import org.openqa.selenium.testing.Safely;46import org.openqa.selenium.testing.TearDownFixture;47import java.net.URL;48import java.util.ArrayList;49import java.util.List;50import static java.nio.charset.StandardCharsets.US_ASCII;51import static java.util.Collections.singletonMap;52import static org.assertj.core.api.Assertions.assertThat;53import static org.openqa.selenium.remote.CapabilityType.PROXY;54import static org.openqa.selenium.testing.drivers.Browser.CHROME;55import static org.openqa.selenium.testing.drivers.Browser.FIREFOX;56import static org.openqa.selenium.testing.drivers.Browser.SAFARI;57public class ProxySettingTest extends JUnit4TestBase {58 private final List<TearDownFixture> tearDowns = new ArrayList<>();59 private ProxyServer proxyServer;60 @Before61 public void newProxyInstance() {62 proxyServer = new ProxyServer();63 tearDowns.add(proxyServer::destroy);64 }65 @After66 public void tearDown() {67 tearDowns.forEach(Safely::safelyCall);68 }69 @Test70 @Ignore(SAFARI)71 @NeedsLocalEnvironment72 @NoDriverBeforeTest73 @NoDriverAfterTest74 public void canConfigureManualHttpProxy() {75 Proxy proxyToUse = proxyServer.asProxy();76 createNewDriver(new ImmutableCapabilities(PROXY, proxyToUse));77 driver.get(appServer.whereElseIs("simpleTest.html"));78 assertThat(proxyServer.hasBeenCalled("simpleTest.html")).isTrue();79 }80 @Test81 @Ignore(SAFARI)82 @NeedsLocalEnvironment83 @NoDriverBeforeTest84 @NoDriverAfterTest85 public void canConfigureNoProxy() {86 Proxy proxyToUse = proxyServer.asProxy();87 proxyToUse.setNoProxy("localhost, 127.0.0.1, " + appServer.getHostName());88 createNewDriver(new ImmutableCapabilities(PROXY, proxyToUse));89 driver.get(appServer.whereIs("simpleTest.html"));90 assertThat(proxyServer.hasBeenCalled("simpleTest.html")).isFalse();91 driver.get(appServer.whereElseIs("simpleTest.html"));92 assertThat(proxyServer.hasBeenCalled("simpleTest.html")).isTrue();93 }94 @Test95 @Ignore(SAFARI)96 @NeedsLocalEnvironment97 @NoDriverBeforeTest98 @NoDriverAfterTest99 public void canConfigureProxyThroughPACFile() {100 Server<?> helloServer = createSimpleHttpServer(101 "<!DOCTYPE html><title>Hello</title><h3>Hello, world!</h3>");102 Server<?> pacFileServer = createPacfileServer(Joiner.on('\n').join(103 "function FindProxyForURL(url, host) {",104 " return 'PROXY " + getHostAndPort(helloServer) + "';",105 "}"));106 Proxy proxy = new Proxy();107 proxy.setProxyAutoconfigUrl("http://" + getHostAndPort(pacFileServer) + "/proxy.pac");108 createNewDriver(new ImmutableCapabilities(PROXY, proxy));109 driver.get(appServer.whereElseIs("mouseOver.html"));110 assertThat(driver.findElement(By.tagName("h3")).getText()).isEqualTo("Hello, world!");111 }112 @Test113 @Ignore(SAFARI)114 @NeedsLocalEnvironment115 @NoDriverBeforeTest116 @NoDriverAfterTest117 @Ignore(value = FIREFOX, travis = true)118 @Ignore(value = CHROME, reason = "Flaky")119 public void canUsePACThatOnlyProxiesCertainHosts() {120 Server<?> helloServer = createSimpleHttpServer(121 "<!DOCTYPE html><title>Hello</title><h3>Hello, world!</h3>");122 Server<?> goodbyeServer = createSimpleHttpServer(123 "<!DOCTYPE html><title>Goodbye</title><h3>Goodbye, world!</h3>");124 Server<?> pacFileServer = createPacfileServer(Joiner.on('\n').join(125 "function FindProxyForURL(url, host) {",126 " if (url.indexOf('" + getHostAndPort(helloServer) + "') != -1) {",127 " return 'PROXY " + getHostAndPort(goodbyeServer) + "';",128 " }",129 " return 'DIRECT';",130 "}"));131 Proxy proxy = new Proxy();132 proxy.setProxyAutoconfigUrl("http://" + getHostAndPort(pacFileServer) + "/proxy.pac");133 createNewDriver(new ImmutableCapabilities(PROXY, proxy));134 driver.get("http://" + getHostAndPort(helloServer));135 assertThat(driver.findElement(By.tagName("h3")).getText()).isEqualTo("Goodbye, world!");136 driver.get(appServer.whereElseIs("simpleTest.html"));137 assertThat(driver.findElement(By.tagName("h1")).getText()).isEqualTo("Heading");138 }139 private Server<?> createSimpleHttpServer(final String responseHtml) {140 return createServer(141 req -> new HttpResponse()142 .setHeader("Content-Type", "text/html; charset=utf-8")143 .setContent(Contents.utf8String(responseHtml)));144 }145 private Server<?> createPacfileServer(final String pacFileContents) {146 return createServer(147 req -> new HttpResponse()148 .setHeader("Content-Type", "application/x-javascript-config; charset=us-ascii")149 .setContent(Contents.bytes(pacFileContents.getBytes(US_ASCII))));150 }151 private Server<?> createServer(HttpHandler handler) {152 Server<?> server = new JreServer(153 new BaseServerOptions(new MapConfig(154 singletonMap("server", singletonMap("port", PortProber.findFreePort())))),155 handler)156 .start();157 tearDowns.add(server::stop);158 return server;159 }160 private static HostAndPort getHostAndPort(Server<?> server) {161 URL url = server.getUrl();162 return HostAndPort.fromParts(url.getHost(), url.getPort());163 }164 public static class ProxyServer {165 private final HttpProxyServer proxyServer;166 private final String baseUrl;167 private final List<String> uris = new ArrayList<>();168 public ProxyServer() {169 int port = PortProber.findFreePort();170 String address = new NetworkUtils().getPrivateLocalAddress();171 baseUrl = String.format("%s:%d", address, port);172 proxyServer = DefaultHttpProxyServer.bootstrap().withAllowLocalOnly(false).withPort(port)173 .withFiltersSource(new HttpFiltersSourceAdapter() {174 @Override175 public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) {176 return new HttpFiltersAdapter(originalRequest) {177 @Override178 public io.netty.handler.codec.http.HttpResponse clientToProxyRequest(HttpObject httpObject) {179 String uri = originalRequest.uri();180 String[] parts = uri.split("/");181 if (parts.length == 0) {182 return null;183 }184 String finalPart = parts[parts.length - 1];185 uris.add(finalPart);186 return null;187 }188 @Override189 public HttpObject serverToProxyResponse(HttpObject httpObject) {190 return httpObject;191 }192 };193 }194 })195 .start();196 }197 /**198 * Checks if a resource has been requested using the short name of the resource.199 *200 * @param resourceName The short name of the resource to check.201 * @return true if the resource has been called.202 */203 public boolean hasBeenCalled(String resourceName) {204 return uris.contains(resourceName);205 }206 public void destroy() {207 proxyServer.stop();208 }209 public Proxy asProxy() {210 Proxy proxy = new Proxy();211 proxy.setHttpProxy(baseUrl);212 return proxy;213 }214 }215}...

Full Screen

Full Screen

Source:Bootstrap.java Github

copy

Full Screen

...32import java.util.List;33import java.util.Set;34import java.util.logging.Level;35import java.util.logging.Logger;36public class Bootstrap {37 private static final String MAIN_CLASS = Bootstrap.class.getPackage().getName() + ".Main";38 private static final Logger LOG = Logger.getLogger(Bootstrap.class.getName());39 public static void main(String[] args) {40 ClassLoader classLoader = Bootstrap.class.getClassLoader();41 if (args.length == 0) {42 runMain(classLoader, args);43 return;44 }45 if ("--ext".equals(args[0])) {46 if (args.length < 2) {47 runMain(classLoader, args);48 return;49 }50 ClassLoader parent = createExtendedClassLoader(args[1]);51 String[] remainingArgs = new String[args.length - 2];52 System.arraycopy(args, 2, remainingArgs, 0, args.length - 2);53 args = remainingArgs;54 classLoader = new PossessiveClassLoader(parent);55 // Ensure that we use our freshly minted classloader by default.56 Thread.currentThread().setContextClassLoader(classLoader);57 }58 runMain(classLoader, args);59 }60 private static void runMain(ClassLoader loader, String[] args) {61 try {62 Class<?> clazz = loader.loadClass(MAIN_CLASS);63 Method main = clazz.getMethod("main", String[].class);64 main.invoke(null, new Object[] {args});65 } catch (ReflectiveOperationException e) {66 e.printStackTrace();67 System.exit(1);68 }69 }70 private static ClassLoader createExtendedClassLoader(String ext) {71 List<File> jars = new ArrayList<>();72 for (String part : ext.split(File.pathSeparator)) {73 File file = new File(part);74 if (!file.exists()) {75 LOG.warning("Extension file or directory does not exist: " + file);76 continue;77 }78 if (file.isDirectory()) {79 File[] files = file.listFiles();80 if (files == null) {81 LOG.warning("Cannot list files in directory: " + file);82 } else {83 for (File subdirFile : files) {84 if (subdirFile.isFile() && subdirFile.getName().endsWith(".jar")) {85 jars.add(subdirFile);86 }87 }88 }89 } else {90 jars.add(file);91 }92 }93 URL[] jarUrls = jars.stream()94 .map(file -> {95 try {96 return file.toURI().toURL();97 } catch (MalformedURLException e) {98 LOG.log(Level.SEVERE, "Unable to find JAR file " + file, e);99 throw new UncheckedIOException(e);100 }101 })102 .toArray(URL[]::new);103 return AccessController.doPrivileged((PrivilegedAction<URLClassLoader>) () ->104 new URLClassLoader(jarUrls, Bootstrap.class.getClassLoader()));105 }106 private static class PossessiveClassLoader extends ClassLoader {107 private final ClassLoader delegate;108 private final Set<String> blessed;109 PossessiveClassLoader(ClassLoader delegate) {110 super(delegate);111 this.delegate = delegate;112 blessed = new HashSet<>();113 blessed.add("java.");114 blessed.add("javax.");115 blessed.add("sun.");116 blessed.add("jdk.");117 }118 @Override...

Full Screen

Full Screen

Source:NettyServer.java Github

copy

Full Screen

...14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.netty.server;18import io.netty.bootstrap.ServerBootstrap;19import io.netty.channel.Channel;20import io.netty.channel.ChannelOption;21import io.netty.channel.EventLoopGroup;22import io.netty.channel.nio.NioEventLoopGroup;23import io.netty.channel.socket.nio.NioServerSocketChannel;24import io.netty.handler.logging.LogLevel;25import io.netty.handler.logging.LoggingHandler;26import org.openqa.selenium.grid.server.AddWebDriverSpecHeaders;27import org.openqa.selenium.grid.server.BaseServerOptions;28import org.openqa.selenium.grid.server.Server;29import org.openqa.selenium.grid.server.WrapExceptions;30import org.openqa.selenium.grid.server.BaseServerOptions;31import org.openqa.selenium.grid.server.Server;32import org.openqa.selenium.remote.http.HttpHandler;33import java.io.IOException;34import java.io.UncheckedIOException;35import java.net.MalformedURLException;36import java.net.URL;37import java.util.Objects;38public class NettyServer implements Server<NettyServer> {39 private final EventLoopGroup bossGroup;40 private final EventLoopGroup workerGroup;41 private final int port;42 private final URL externalUrl;43 private final HttpHandler handler;44 private Channel channel;45 public NettyServer(BaseServerOptions options, HttpHandler handler) {46 Objects.requireNonNull(options, "Server options must be set.");47 Objects.requireNonNull(handler, "Handler to use must be set.");48 this.handler = handler.with(new WrapExceptions().andThen(new AddWebDriverSpecHeaders()));49 bossGroup = new NioEventLoopGroup(1);50 workerGroup = new NioEventLoopGroup();51 port = options.getPort();52 try {53 externalUrl = options.getExternalUri().toURL();54 } catch (MalformedURLException e) {55 throw new UncheckedIOException("Server URI is not a valid URL: " + options.getExternalUri(), e);56 }57 }58 @Override59 public boolean isStarted() {60 return channel != null;61 }62 @Override63 public URL getUrl() {64 return externalUrl;65 }66 @Override67 public void stop() {68 try {69 channel.closeFuture().sync();70 } catch (InterruptedException e) {71 Thread.currentThread().interrupt();72 throw new UncheckedIOException(new IOException("Shutdown interrupted", e));73 } finally {74 channel = null;75 bossGroup.shutdownGracefully();76 workerGroup.shutdownGracefully();77 }78 }79 public NettyServer start() {80 ServerBootstrap b = new ServerBootstrap();81 b.group(bossGroup, workerGroup)82 .channel(NioServerSocketChannel.class)83 .handler(new LoggingHandler(LogLevel.INFO))84 .childHandler(new SeleniumHttpInitializer(handler));85 try {86 channel = b.bind(port).sync().channel();87 } catch (InterruptedException e) {88 Thread.currentThread().interrupt();89 throw new UncheckedIOException(new IOException("Start up interrupted", e));90 }91 return this;92 }93}...

Full Screen

Full Screen

Source:Main.java Github

copy

Full Screen

...12 // assets-path = "/absolute/path/to/your/assets/directory"13 Path debugToml =14 Paths.get("sauce-grid/src/test/resources/sauce_togo_config_debugging.toml")15 .toAbsolutePath();16 org.openqa.selenium.grid.Bootstrap.main(17 new String[]{18 "--ext",19 jarPath.toString(),20 "standalone",21 "--relax-checks",22 "true",23 "--detect-drivers",24 "false",25 "--config",26 debugToml.toString()27 }28 );29 }30}...

Full Screen

Full Screen

Bootstrap

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.grid.Bootstrap;2import org.openqa.selenium.grid.Browser;3import org.openqa.selenium.grid.BrowserOptions;4import org.openqa.selenium.grid.BrowserSession;5import org.openqa.selenium.grid.BrowserSessionFactory;6import org.openqa.selenium.grid.BrowserType;7import org.openqa.selenium.grid.Config;8import org.openqa.selenium.grid.ConfiguredGrid;9import org.openqa.selenium.grid.Grid;10import org.openqa.selenium.grid.GridOptions;11import org.openqa.selenium.grid.GridRole;12import org.openqa.selenium.grid.GridServer;13import org.openqa.selenium.grid.HttpHandler;14import org.openqa.selenium.grid.Node;15import org.openqa.selenium.grid.NodeOptions;16import org.openqa.selenium.grid.NodeStatus;17import org.openqa.selenium.grid.NodeStatusEvent;18import org.openqa.selenium.grid.NodeStatusListener;19import org.openqa.selenium.grid.NodeStatusPage;20import org.openqa.selenium.grid.NodeStatusServlet;21import org.openqa.selenium.grid.NodeStatusSource;22import org.openqa.selenium.grid.NodeStatusUpdate;23import

Full Screen

Full Screen
copy
1import org.apache.commons.lang.RandomStringUtils;2RandomStringUtils.randomAlphanumeric(64);3
Full Screen
copy
1public static String randomSeriesForThreeCharacter() {2 Random r = new Random();3 String value = "";4 char random_Char ;5 for(int i=0; i<10; i++)6 {7 random_Char = (char) (48 + r.nextInt(74));8 value = value + random_char;9 }10 return value;11}12
Full Screen
copy
1 public String generateRandomString(int length) {2 String randomString = "";34 final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890".toCharArray();5 final Random random = new Random();6 for (int i = 0; i < length; i++) {7 randomString = randomString + chars[random.nextInt(chars.length)];8 }910 return randomString;11}12
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 Bootstrap

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