Best Selenium code snippet using org.openqa.selenium.remote.http.Route.options
Source:RouterServer.java
...132 Routable route = Route.combine(133 ui,134 routerWithSpecChecks,135 Route.prefix("/wd/hub").to(combine(routerWithSpecChecks)),136 Route.options("/graphql").to(() -> graphqlHandler),137 Route.post("/graphql").to(() -> graphqlHandler));138 UsernameAndPassword uap = secretOptions.getServerAuthentication();139 if (uap != null) {140 LOG.info("Requiring authentication to connect");141 route = route.with(new BasicAuthenticationFilter(uap.username(), uap.password()));142 }143 // Since k8s doesn't make it easy to do an authenticated liveness probe, allow unauthenticated access to it.144 Routable routeWithLiveness = Route.combine(145 route,146 get("/readyz").to(() -> req -> new HttpResponse().setStatus(HTTP_NO_CONTENT)));147 return new Handlers(routeWithLiveness, new ProxyCdpIntoGrid(clientFactory, sessions));148 }149 @Override150 protected void execute(Config config) {...
Source:Standalone.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.grid.commands;18import com.google.auto.service.AutoService;19import com.google.common.collect.ImmutableSet;20import org.openqa.selenium.BuildInfo;21import org.openqa.selenium.cli.CliCommand;22import org.openqa.selenium.events.EventBus;23import org.openqa.selenium.grid.TemplateGridServerCommand;24import org.openqa.selenium.grid.config.Config;25import org.openqa.selenium.grid.config.Role;26import org.openqa.selenium.grid.distributor.Distributor;27import org.openqa.selenium.grid.distributor.local.LocalDistributor;28import org.openqa.selenium.grid.graphql.GraphqlHandler;29import org.openqa.selenium.grid.log.LoggingOptions;30import org.openqa.selenium.grid.node.Node;31import org.openqa.selenium.grid.node.ProxyNodeCdp;32import org.openqa.selenium.grid.node.local.LocalNodeFactory;33import org.openqa.selenium.grid.router.Router;34import org.openqa.selenium.grid.security.Secret;35import org.openqa.selenium.grid.server.BaseServerOptions;36import org.openqa.selenium.grid.server.EventBusOptions;37import org.openqa.selenium.grid.server.NetworkOptions;38import org.openqa.selenium.grid.server.Server;39import org.openqa.selenium.grid.sessionmap.SessionMap;40import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;41import org.openqa.selenium.grid.web.ClassPathResource;42import org.openqa.selenium.grid.web.CombinedHandler;43import org.openqa.selenium.grid.web.NoHandler;44import org.openqa.selenium.grid.web.ResourceHandler;45import org.openqa.selenium.grid.web.RoutableHttpClientFactory;46import org.openqa.selenium.internal.Require;47import org.openqa.selenium.json.Json;48import org.openqa.selenium.remote.http.Contents;49import org.openqa.selenium.remote.http.HttpClient;50import org.openqa.selenium.remote.http.HttpHandler;51import org.openqa.selenium.remote.http.HttpResponse;52import org.openqa.selenium.remote.http.Routable;53import org.openqa.selenium.remote.http.Route;54import org.openqa.selenium.remote.tracing.Tracer;55import java.net.MalformedURLException;56import java.net.URI;57import java.net.URL;58import java.util.Collections;59import java.util.Set;60import java.util.logging.Logger;61import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;62import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;63import static java.net.HttpURLConnection.HTTP_OK;64import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;65import static org.openqa.selenium.grid.config.StandardGridRoles.NODE_ROLE;66import static org.openqa.selenium.grid.config.StandardGridRoles.ROUTER_ROLE;67import static org.openqa.selenium.remote.http.Route.combine;68import static org.openqa.selenium.remote.http.Route.get;69@AutoService(CliCommand.class)70public class Standalone extends TemplateGridServerCommand {71 private static final Logger LOG = Logger.getLogger("selenium");72 @Override73 public String getName() {74 return "standalone";75 }76 @Override77 public String getDescription() {78 return "The selenium server, running everything in-process.";79 }80 @Override81 public Set<Role> getConfigurableRoles() {82 return ImmutableSet.of(HTTPD_ROLE, NODE_ROLE, ROUTER_ROLE);83 }84 @Override85 public Set<Object> getFlagObjects() {86 return Collections.singleton(new StandaloneFlags());87 }88 @Override89 protected String getSystemPropertiesConfigPrefix() {90 return "selenium";91 }92 @Override93 protected Config getDefaultConfig() {94 return new DefaultStandaloneConfig();95 }96 @Override97 protected Handlers createHandlers(Config config) {98 LoggingOptions loggingOptions = new LoggingOptions(config);99 Tracer tracer = loggingOptions.getTracer();100 EventBusOptions events = new EventBusOptions(config);101 EventBus bus = events.getEventBus();102 BaseServerOptions serverOptions = new BaseServerOptions(config);103 Secret registrationSecret = serverOptions.getRegistrationSecret();104 URI localhost = serverOptions.getExternalUri();105 URL localhostUrl;106 try {107 localhostUrl = localhost.toURL();108 } catch (MalformedURLException e) {109 throw new IllegalArgumentException(e);110 }111 NetworkOptions networkOptions = new NetworkOptions(config);112 CombinedHandler combinedHandler = new CombinedHandler();113 HttpClient.Factory clientFactory = new RoutableHttpClientFactory(114 localhostUrl,115 combinedHandler,116 networkOptions.getHttpClientFactory(tracer));117 SessionMap sessions = new LocalSessionMap(tracer, bus);118 combinedHandler.addHandler(sessions);119 Distributor distributor = new LocalDistributor(tracer, bus, clientFactory, sessions, registrationSecret);120 combinedHandler.addHandler(distributor);121 Routable router = new Router(tracer, clientFactory, sessions, distributor)122 .with(networkOptions.getSpecComplianceChecks());123 HttpHandler readinessCheck = req -> {124 boolean ready = sessions.isReady() && distributor.isReady() && bus.isReady();125 return new HttpResponse()126 .setStatus(ready ? HTTP_OK : HTTP_INTERNAL_ERROR)127 .setContent(Contents.utf8String("Standalone is " + ready));128 };129 GraphqlHandler graphqlHandler = new GraphqlHandler(distributor, serverOptions.getExternalUri());130 Routable ui;131 URL uiRoot = getClass().getResource("/javascript/grid-ui/build");132 if (uiRoot != null) {133 ResourceHandler uiHandler = new ResourceHandler(new ClassPathResource(uiRoot, "javascript/grid-ui/build"));134 ui = Route.combine(135 get("/").to(() -> req -> new HttpResponse().setStatus(HTTP_MOVED_TEMP).addHeader("Location", "/ui/index.html")),136 Route.prefix("/ui/").to(Route.matching(req -> true).to(() -> uiHandler)));137 } else {138 Json json = new Json();139 ui = Route.matching(req -> false).to(() -> new NoHandler(json));140 }141 HttpHandler httpHandler = combine(142 ui,143 router,144 Route.prefix("/wd/hub").to(combine(router)),145 Route.post("/graphql").to(() -> graphqlHandler),146 Route.get("/readyz").to(() -> readinessCheck));147 Node node = LocalNodeFactory.create(config);148 combinedHandler.addHandler(node);149 distributor.add(node);150 return new Handlers(httpHandler, new ProxyNodeCdp(clientFactory, node));151 }152 @Override153 protected void execute(Config config) {154 Require.nonNull("Config", config);155 Server<?> server = asServer(config).start();156 BuildInfo info = new BuildInfo();157 LOG.info(String.format(158 "Started Selenium standalone %s (revision %s): %s",159 info.getReleaseLabel(),160 info.getBuildRevision(),161 server.getUrl()));162 }163}...
Source:Hub.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.grid.commands;18import com.google.auto.service.AutoService;19import com.google.common.collect.ImmutableSet;20import org.openqa.selenium.BuildInfo;21import org.openqa.selenium.cli.CliCommand;22import org.openqa.selenium.events.EventBus;23import org.openqa.selenium.grid.TemplateGridServerCommand;24import org.openqa.selenium.grid.config.Config;25import org.openqa.selenium.grid.config.Role;26import org.openqa.selenium.grid.distributor.Distributor;27import org.openqa.selenium.grid.distributor.local.LocalDistributor;28import org.openqa.selenium.grid.graphql.GraphqlHandler;29import org.openqa.selenium.grid.log.LoggingOptions;30import org.openqa.selenium.grid.router.ProxyCdpIntoGrid;31import org.openqa.selenium.grid.router.Router;32import org.openqa.selenium.grid.server.BaseServerOptions;33import org.openqa.selenium.grid.server.EventBusOptions;34import org.openqa.selenium.grid.server.NetworkOptions;35import org.openqa.selenium.grid.server.Server;36import org.openqa.selenium.grid.sessionmap.SessionMap;37import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;38import org.openqa.selenium.grid.web.ClassPathResource;39import org.openqa.selenium.grid.web.CombinedHandler;40import org.openqa.selenium.grid.web.NoHandler;41import org.openqa.selenium.grid.web.ResourceHandler;42import org.openqa.selenium.grid.web.RoutableHttpClientFactory;43import org.openqa.selenium.internal.Require;44import org.openqa.selenium.json.Json;45import org.openqa.selenium.remote.http.Contents;46import org.openqa.selenium.remote.http.HttpClient;47import org.openqa.selenium.remote.http.HttpHandler;48import org.openqa.selenium.remote.http.HttpResponse;49import org.openqa.selenium.remote.http.Routable;50import org.openqa.selenium.remote.http.Route;51import org.openqa.selenium.remote.tracing.Tracer;52import java.net.MalformedURLException;53import java.net.URL;54import java.util.Collections;55import java.util.Set;56import java.util.logging.Logger;57import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;58import static java.net.HttpURLConnection.HTTP_MOVED_PERM;59import static java.net.HttpURLConnection.HTTP_OK;60import static org.openqa.selenium.grid.config.StandardGridRoles.EVENT_BUS_ROLE;61import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;62import static org.openqa.selenium.grid.config.StandardGridRoles.ROUTER_ROLE;63import static org.openqa.selenium.remote.http.Route.combine;64import static org.openqa.selenium.remote.http.Route.get;65@AutoService(CliCommand.class)66public class Hub extends TemplateGridServerCommand {67 private static final Logger LOG = Logger.getLogger(Hub.class.getName());68 @Override69 public String getName() {70 return "hub";71 }72 @Override73 public String getDescription() {74 return "A grid hub, composed of sessions, distributor, and router.";75 }76 @Override77 public Set<Role> getConfigurableRoles() {78 return ImmutableSet.of(EVENT_BUS_ROLE, HTTPD_ROLE, ROUTER_ROLE);79 }80 @Override81 public Set<Object> getFlagObjects() {82 return Collections.emptySet();83 }84 @Override85 protected String getSystemPropertiesConfigPrefix() {86 return "selenium";87 }88 @Override89 protected Config getDefaultConfig() {90 return new DefaultHubConfig();91 }92 @Override93 protected Handlers createHandlers(Config config) {94 LoggingOptions loggingOptions = new LoggingOptions(config);95 Tracer tracer = loggingOptions.getTracer();96 EventBusOptions events = new EventBusOptions(config);97 EventBus bus = events.getEventBus();98 CombinedHandler handler = new CombinedHandler();99 SessionMap sessions = new LocalSessionMap(tracer, bus);100 handler.addHandler(sessions);101 BaseServerOptions serverOptions = new BaseServerOptions(config);102 URL externalUrl;103 try {104 externalUrl = serverOptions.getExternalUri().toURL();105 } catch (MalformedURLException e) {106 throw new IllegalArgumentException(e);107 }108 NetworkOptions networkOptions = new NetworkOptions(config);109 HttpClient.Factory clientFactory = new RoutableHttpClientFactory(110 externalUrl,111 handler,112 networkOptions.getHttpClientFactory(tracer));113 Distributor distributor = new LocalDistributor(114 tracer,115 bus,116 clientFactory,117 sessions,118 serverOptions.getRegistrationSecret());119 handler.addHandler(distributor);120 Router router = new Router(tracer, clientFactory, sessions, distributor);121 GraphqlHandler graphqlHandler = new GraphqlHandler(distributor, serverOptions.getExternalUri());122 HttpHandler readinessCheck = req -> {123 boolean ready = router.isReady() && bus.isReady();124 return new HttpResponse()125 .setStatus(ready ? HTTP_OK : HTTP_INTERNAL_ERROR)126 .setContent(Contents.utf8String("Router is " + ready));127 };128 Routable ui;129 URL uiRoot = getClass().getResource("/javascript/grid-ui/build");130 if (uiRoot != null) {131 ResourceHandler132 uiHandler = new ResourceHandler(new ClassPathResource(uiRoot, "javascript/grid-ui/build"));133 ui = Route.combine(134 get("/grid/console").to(() -> req -> new HttpResponse().setStatus(HTTP_MOVED_PERM).addHeader("Location", "/ui/index.html")),135 Route.prefix("/ui/").to(Route.matching(req -> true).to(() -> uiHandler)));136 } else {137 Json json = new Json();138 ui = Route.matching(req -> false).to(() -> new NoHandler(json));139 }140 HttpHandler httpHandler = combine(141 ui,142 router.with(networkOptions.getSpecComplianceChecks()),143 Route.prefix("/wd/hub").to(combine(router.with(networkOptions.getSpecComplianceChecks()))),144 Route.post("/graphql").to(() -> graphqlHandler),145 Route.get("/readyz").to(() -> readinessCheck));146 return new Handlers(httpHandler, new ProxyCdpIntoGrid(clientFactory, sessions));147 }148 @Override149 protected void execute(Config config) {150 Require.nonNull("Config", config);151 Server<?> server = asServer(config).start();152 BuildInfo info = new BuildInfo();153 LOG.info(String.format(154 "Started Selenium hub %s (revision %s): %s",155 info.getReleaseLabel(),156 info.getBuildRevision(),157 server.getUrl()));158 }159}...
Source:JreAppServer.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.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}...
Source:DistributorServer.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.grid.distributor.httpd;18import com.google.auto.service.AutoService;19import com.google.common.collect.ImmutableMap;20import com.google.common.collect.ImmutableSet;21import com.google.common.net.MediaType;22import org.openqa.selenium.BuildInfo;23import org.openqa.selenium.cli.CliCommand;24import org.openqa.selenium.grid.TemplateGridCommand;25import org.openqa.selenium.grid.config.Config;26import org.openqa.selenium.grid.config.Role;27import org.openqa.selenium.grid.distributor.Distributor;28import org.openqa.selenium.grid.distributor.config.DistributorOptions;29import org.openqa.selenium.grid.server.BaseServerOptions;30import org.openqa.selenium.grid.server.Server;31import org.openqa.selenium.netty.server.NettyServer;32import org.openqa.selenium.remote.http.Contents;33import org.openqa.selenium.remote.http.HttpHandler;34import org.openqa.selenium.remote.http.HttpResponse;35import org.openqa.selenium.remote.http.Route;36import java.util.Collections;37import java.util.Set;38import java.util.logging.Logger;39import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;40import static java.net.HttpURLConnection.HTTP_OK;41import static org.openqa.selenium.grid.config.StandardGridRoles.EVENT_BUS_ROLE;42import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;43import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_MAP_ROLE;44import static org.openqa.selenium.remote.http.HttpMethod.GET;45import static org.openqa.selenium.remote.http.Route.get;46@AutoService(CliCommand.class)47public class DistributorServer extends TemplateGridCommand {48 private static final Logger LOG = Logger.getLogger(DistributorServer.class.getName());49 private static final String LOCAL_DISTRIBUTOR_SERVER = "org.openqa.selenium.grid.distributor.local.LocalDistributor";50 @Override51 public String getName() {52 return "distributor";53 }54 @Override55 public String getDescription() {56 return "Adds this server as the distributor in a selenium grid.";57 }58 @Override59 public Set<Role> getConfigurableRoles() {60 return ImmutableSet.of(EVENT_BUS_ROLE, HTTPD_ROLE, SESSION_MAP_ROLE);61 }62 @Override63 public Set<Object> getFlagObjects() {64 return Collections.emptySet();65 }66 @Override67 protected String getSystemPropertiesConfigPrefix() {68 return "distributor";69 }70 @Override71 protected Config getDefaultConfig() {72 return new DefaultDistributorConfig();73 }74 @Override75 protected void execute(Config config) {76 BaseServerOptions serverOptions = new BaseServerOptions(config);77 DistributorOptions distributorOptions = new DistributorOptions(config);78 Distributor distributor = distributorOptions.getDistributor(LOCAL_DISTRIBUTOR_SERVER);79 HttpHandler readinessCheck = req -> {80 boolean ready = distributor.isReady();81 return new HttpResponse()82 .setStatus(ready ? HTTP_OK : HTTP_INTERNAL_ERROR)83 .setHeader("Content-Type", MediaType.PLAIN_TEXT_UTF_8.toString())84 .setContent(Contents.utf8String("Distributor is " + ready));85 };86 Route handler = Route.combine(87 distributor,88 Route.matching(req -> GET.equals(req.getMethod()) && "/status".equals(req.getUri()))89 .to(() -> req -> new HttpResponse()90 .setContent(Contents.asJson(91 ImmutableMap.of("value", ImmutableMap.of(92 "ready", true,93 "message", "Distributor is ready"))))),94 get("/readyz").to(() -> readinessCheck));95 Server<?> server = new NettyServer(serverOptions, handler);96 server.start();97 BuildInfo info = new BuildInfo();98 LOG.info(String.format(99 "Started Selenium distributor %s (revision %s): %s",100 info.getReleaseLabel(),101 info.getBuildRevision(),102 server.getUrl()));103 }104}...
Source:BaseServerTest.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.grid.server;18import static java.net.HttpURLConnection.HTTP_OK;19import static org.junit.Assert.assertEquals;20import static org.openqa.selenium.grid.web.Routes.get;21import static org.openqa.selenium.remote.http.Contents.string;22import static org.openqa.selenium.remote.http.Contents.utf8String;23import static org.openqa.selenium.remote.http.HttpMethod.GET;24import com.google.common.collect.ImmutableMap;25import com.google.common.net.MediaType;26import org.assertj.core.api.Assertions;27import org.junit.Test;28import org.openqa.selenium.grid.config.MapConfig;29import org.openqa.selenium.remote.http.HttpClient;30import org.openqa.selenium.remote.http.HttpRequest;31import org.openqa.selenium.remote.http.HttpResponse;32import java.io.IOException;33import java.net.URL;34public class BaseServerTest {35 private BaseServerOptions emptyOptions = new BaseServerOptions(new MapConfig(ImmutableMap.of()));36 @Test37 public void baseServerStartsAndDoesNothing() throws IOException {38 Server<?> server = new BaseServer<>(emptyOptions).start();39 URL url = server.getUrl();40 HttpClient client = HttpClient.Factory.createDefault().createClient(url);41 HttpResponse response = client.execute(new HttpRequest(GET, "/status"));42 // Although we don't expect the server to be ready, we do expect the request to succeed.43 assertEquals(HTTP_OK, response.getStatus());44 // And we expect the content to be UTF-8 encoded JSON.45 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(response.getHeader("Content-Type")));46 }47 @Test48 public void shouldAllowAHandlerToBeRegistered() throws IOException {49 Server<?> server = new BaseServer<>(emptyOptions);50 server.addRoute(get("/cheese").using((req, res) -> res.setContent(utf8String("cheddar"))));51 server.start();52 URL url = server.getUrl();53 HttpClient client = HttpClient.Factory.createDefault().createClient(url);54 HttpResponse response = client.execute(new HttpRequest(GET, "/cheese"));55 assertEquals("cheddar", string(response));56 }57 @Test58 public void ifTwoHandlersRespondToTheSameRequestTheLastOneAddedWillBeUsed() throws IOException {59 Server<?> server = new BaseServer<>(emptyOptions);60 server.addRoute(get("/status").using((req, res) -> res.setContent(utf8String("one"))));61 server.addRoute(get("/status").using((req, res) -> res.setContent(utf8String("two"))));62 server.start();63 URL url = server.getUrl();64 HttpClient client = HttpClient.Factory.createDefault().createClient(url);65 HttpResponse response = client.execute(new HttpRequest(GET, "/status"));66 assertEquals("two", string(response));67 }68 @Test69 public void addHandlersOnceServerIsStartedIsAnError() {70 Server<BaseServer> server = new BaseServer<>(emptyOptions);71 server.start();72 Assertions.assertThatExceptionOfType(IllegalStateException.class).isThrownBy(73 () -> server.addRoute(get("/foo").using((req, res) -> {})));74 }75}...
options
Using AI Code Generation
1import org.openqa.selenium.remote.http.Route;2import org.openqa.selenium.remote.http.HttpMethod;3import org.openqa.selenium.remote.http.HttpRequest;4import org.openqa.selenium.remote.http.HttpResponse;5Route route = new Route(HttpMethod.GET, "/foo/bar");6HttpResponse response = route.execute(HttpRequest.GET("/foo/bar"));7System.out.println(response.getStatus());8Route route = new Route(HttpMethod.GET, "/foo/bar");9HttpResponse response = route.execute(HttpRequest.GET("/foo/bar/baz"));10System.out.println(response.getStatus());11Route route = new Route(HttpMethod.GET, "/foo/bar");12HttpResponse response = route.execute(HttpRequest.GET("/foo/bar/baz"));13System.out.println(response.getStatus());14import org.openqa.selenium.remote.http.Route;15import org.openqa.selenium.remote.http.HttpMethod;16import org.openqa.selenium.remote.http.HttpRequest;17import org.openqa.selenium.remote.http.HttpResponse;18Route route = new Route(HttpMethod.GET, "/foo/bar");19HttpResponse response = route.execute(HttpRequest.GET("/foo/bar"));20System.out.println(response.getStatus());21Route route = new Route(HttpMethod.GET, "/foo/bar");22HttpResponse response = route.execute(HttpRequest.GET("/foo/bar/baz"));23System.out.println(response.getStatus());24Route route = new Route(HttpMethod.GET, "/foo/bar");25HttpResponse response = route.execute(HttpRequest.GET("/foo/bar/baz"));26System.out.println(response.getStatus());27import org.openqa.selenium.remote.http.Route;28import org.openqa.selenium.remote.http.HttpMethod;29import org.openqa.selenium.remote.http.HttpRequest;30import org.openqa.selenium.remote.http.HttpResponse;31Route route = new Route(HttpMethod.GET, "/foo/bar");32HttpResponse response = route.execute(HttpRequest.GET("/foo/bar"));33System.out.println(response.getStatus());34Route route = new Route(HttpMethod.GET, "/foo/bar");35HttpResponse response = route.execute(HttpRequest.GET("/foo/bar/baz"));36System.out.println(response.getStatus());37Route route = new Route(HttpMethod.GET, "/foo/bar");38HttpResponse response = route.execute(HttpRequest.GET("/foo/bar/baz"));39System.out.println(response.getStatus());40import org.openqa.selenium.remote.http.Route;41import org.openqa.selenium.remote.http.HttpMethod;42import org.openqa.selenium.remote.http.HttpRequest;43import org.openqa.selenium.remote.http.HttpResponse;44Route route = new Route(HttpMethod.GET, "/foo/bar");45HttpResponse response = route.execute(HttpRequest.GET("/foo/bar"));46System.out.println(response.getStatus());47Route route = new Route(HttpMethod.GET, "/foo/bar");48HttpResponse response = route.execute(HttpRequest.GET("/foo/bar/baz"));49System.out.println(response.getStatus());
options
Using AI Code Generation
1Route.builder().options(new HttpHandler() {2 public HttpResponse execute(HttpRequest request) {3 return new HttpResponse().addHeader("Access-Control-Allow-Origin", "*")4 .addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")5 .addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");6 }7}).build();8Route.builder().options(new HttpHandler() {9 public HttpResponse execute(HttpRequest request) {10 return new HttpResponse()11 .addHeader("Access-Control-Allow-Origin", "*")12 .addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")13 .addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");14 }15}).build();16Route.builder().options(new HttpHandler() {17 public HttpResponse execute(HttpRequest request) {18 return new HttpResponse()19 .addHeader("Access-Control-Allow-Origin", "*")20 .addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")21 .addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");22 }23}).build();24Route.builder().options(new HttpHandler() {25 public HttpResponse execute(HttpRequest request) {26 return new HttpResponse()27 .addHeader("Access-Control-Allow-Origin", "*")28 .addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")29 .addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");30 }31}).build();32Route.builder().options(new HttpHandler() {33 public HttpResponse execute(HttpRequest request) {34 return new HttpResponse()35 .addHeader("Access-Control-Allow-Origin", "*")36 .addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")37 .addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");38 }39}).build();
options
Using AI Code Generation
1import org.openqa.selenium.remote.http.Route2import org.openqa.selenium.remote.http.HttpMethod3import org.openqa.selenium.remote.http.HttpRequest4import org.openqa.selenium.remote.http.HttpResponse5def options = new Route(HttpMethod.OPTIONS, "/options") {6 HttpResponse execute(HttpRequest request) {7 return new HttpResponse().addHeader("Access-Control-Allow-Origin", "*")8 }9}10def server = new Server()11server.createContext("/options", options)12server.start()13import org.openqa.selenium.remote.http.Route14import org.openqa.selenium.remote.http.HttpMethod15import org.openqa.selenium.remote.http.HttpRequest16import org.openqa.selenium.remote.http.HttpResponse17def options = new Route(HttpMethod.OPTIONS, "/options") {18 HttpResponse execute(HttpRequest request) {19 return new HttpResponse().addHeader("Access-Control-Allow-Origin", "*")20 }21}22def server = new Server()23server.createContext("/options", options)24server.start()25import org.openqa.selenium.remote.http.Route26import org.openqa.selenium.remote.http.HttpMethod27import org.openqa.selenium.remote.http.HttpRequest28import org.openqa.selenium.remote.http.HttpResponse29def options = new Route(HttpMethod.OPTIONS, "/options") {30 HttpResponse execute(HttpRequest request) {31 return new HttpResponse().addHeader("Access-Control-Allow-Origin", "*")32 }33}34def server = new Server()35server.createContext("/options", options)36server.start()37import org.openqa.selenium.remote.http.Route38import org.openqa.selenium.remote.http.HttpMethod39import org.openqa.selenium.remote.http.HttpRequest40import org.openqa.selenium.remote.http.HttpResponse41def options = new Route(HttpMethod.OPTIONS, "/options") {42 HttpResponse execute(HttpRequest request) {43 return new HttpResponse().addHeader("Access-Control-Allow-Origin", "*")44 }45}46def server = new Server()47server.createContext("/options", options)48server.start()49import org.openqa.selenium.remote.http
options
Using AI Code Generation
1package org.openqa.selenium.remote.http;2import org.openqa.selenium.remote.http.Route;3public class OptionsMethod {4 public static void main(String[] args) {5 Route route = new Route("/foo/bar")6 .to(() -> req -> new HttpResponse().setStatus(200))7 .with(Method.GET, Method.POST, Method.PUT);8 System.out.println(route.options());9 }10}
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!!