Best Selenium code snippet using org.openqa.selenium.remote.http.Route.handle
Source:Route.java
...35import static org.openqa.selenium.remote.http.HttpMethod.POST;36import static org.openqa.selenium.remote.http.UrlPath.ROUTE_PREFIX_KEY;37import org.openqa.selenium.internal.Require;38public abstract class Route implements HttpHandler, Routable {39 public HttpHandler fallbackTo(Supplier<HttpHandler> handler) {40 Require.nonNull("Handler", handler);41 return req -> {42 if (matches(req)) {43 return Route.this.execute(req);44 }45 return Require.state("Handler", handler.get()).nonNull().execute(req);46 };47 }48 @Override49 public final HttpResponse execute(HttpRequest req) {50 if (!matches(req)) {51 return new HttpResponse()52 .setStatus(HTTP_NOT_FOUND)53 .setContent(asJson(ImmutableMap.of(54 "value", ImmutableMap.of(55 "error", "unknown command",56 "message", "Unable to find handler for " + req,57 "stacktrace", ""))));58 }59 HttpResponse res = handle(req);60 if (res != null) {61 return res;62 }63 return new HttpResponse()64 .setStatus(HTTP_INTERNAL_ERROR)65 .addHeader("WebDriver-Error", "unsupported operation")66 .addHeader("Selenium-Route", "NULL_RES")67 .setContent(asJson(ImmutableMap.of(68 "value", ImmutableMap.of(69 "error", "unsupported operation",70 "message", String.format("Found handler for %s, but nothing was returned", req),71 "stacktrace", ""))));72 }73 protected abstract HttpResponse handle(HttpRequest req);74 public static PredicatedConfig matching(Predicate<HttpRequest> predicate) {75 return new PredicatedConfig(Require.nonNull("Predicate", predicate));76 }77 public static TemplatizedRouteConfig delete(String template) {78 UrlTemplate urlTemplate = new UrlTemplate(Require.nonNull("URL template", template));79 return new TemplatizedRouteConfig(80 new MatchesHttpMethod(DELETE).and(new MatchesTemplate(urlTemplate)),81 urlTemplate);82 }83 public static TemplatizedRouteConfig get(String template) {84 UrlTemplate urlTemplate = new UrlTemplate(Require.nonNull("URL template", template));85 return new TemplatizedRouteConfig(86 new MatchesHttpMethod(GET).and(new MatchesTemplate(urlTemplate)),87 urlTemplate);88 }89 public static TemplatizedRouteConfig post(String template) {90 UrlTemplate urlTemplate = new UrlTemplate(Require.nonNull("URL template", template));91 return new TemplatizedRouteConfig(92 new MatchesHttpMethod(POST).and(new MatchesTemplate(urlTemplate)),93 urlTemplate);94 }95 public static TemplatizedRouteConfig options(String template) {96 UrlTemplate urlTemplate = new UrlTemplate(Require.nonNull("URL template", template));97 return new TemplatizedRouteConfig(98 new MatchesHttpMethod(OPTIONS).and(new MatchesTemplate(urlTemplate)),99 urlTemplate);100 }101 public static NestedRouteConfig prefix(String prefix) {102 Require.nonNull("Prefix", prefix);103 Require.stateCondition(!prefix.isEmpty(), "Prefix to use must not be of 0 length");104 return new NestedRouteConfig(prefix);105 }106 public static Route combine(Routable first, Routable... others) {107 Require.nonNull("At least one route", first);108 return new CombinedRoute(Stream.concat(Stream.of(first), Stream.of(others)));109 }110 public static Route combine(Iterable<Routable> routes) {111 Require.nonNull("At least one route", routes);112 return new CombinedRoute(StreamSupport.stream(routes.spliterator(), false));113 }114 public static class TemplatizedRouteConfig {115 private final Predicate<HttpRequest> predicate;116 private final UrlTemplate template;117 private TemplatizedRouteConfig(Predicate<HttpRequest> predicate, UrlTemplate template) {118 this.predicate = Require.nonNull("Predicate", predicate);119 this.template = Require.nonNull("URL template", template);120 }121 public Route to(Supplier<HttpHandler> handler) {122 Require.nonNull("Handler supplier", handler);123 return to(params -> handler.get());124 }125 public Route to(Function<Map<String, String>, HttpHandler> handlerFunc) {126 Require.nonNull("Handler creator", handlerFunc);127 return new TemplatizedRoute(template, predicate, handlerFunc);128 }129 }130 private static class TemplatizedRoute extends Route {131 private final UrlTemplate template;132 private final Predicate<HttpRequest> predicate;133 private final Function<Map<String, String>, HttpHandler> handlerFunction;134 private TemplatizedRoute(135 UrlTemplate template,136 Predicate<HttpRequest> predicate,137 Function<Map<String, String>, HttpHandler> handlerFunction) {138 this.template = Require.nonNull("URL template", template);139 this.predicate = Require.nonNull("Predicate", predicate);140 this.handlerFunction = Require.nonNull("Handler function", handlerFunction);141 }142 @Override143 public boolean matches(HttpRequest request) {144 return predicate.test(request);145 }146 @Override147 protected HttpResponse handle(HttpRequest req) {148 UrlTemplate.Match match = template.match(req.getUri());149 HttpHandler handler = handlerFunction.apply(150 match == null ? ImmutableMap.of() : match.getParameters());151 if (handler == null) {152 return new HttpResponse()153 .setStatus(HTTP_INTERNAL_ERROR)154 .setContent(utf8String("Unable to find handler for " + req));155 }156 return handler.execute(req);157 }158 }159 private static class MatchesHttpMethod implements Predicate<HttpRequest> {160 private final HttpMethod method;161 private MatchesHttpMethod(HttpMethod method) {162 this.method = Require.nonNull("HTTP method to test", method);163 }164 @Override165 public boolean test(HttpRequest request) {166 return method == request.getMethod();167 }168 }169 private static class MatchesTemplate implements Predicate<HttpRequest> {170 private final UrlTemplate template;171 private MatchesTemplate(UrlTemplate template) {172 this.template = Require.nonNull("URL template to test", template);173 }174 @Override175 public boolean test(HttpRequest request) {176 return template.match(request.getUri()) != null;177 }178 }179 public static class NestedRouteConfig {180 private final String prefix;181 private NestedRouteConfig(String prefix) {182 this.prefix = Require.nonNull("Prefix", prefix);183 }184 public Route to(Route route) {185 Require.nonNull("Target for requests", route);186 return new NestedRoute(prefix, route);187 }188 }189 private static class NestedRoute extends Route {190 private final String[] prefixPaths;191 private final String prefix;192 private final Route route;193 private NestedRoute(String prefix, Route route) {194 this.prefixPaths = Require.nonNull("Prefix", prefix).split("/");195 this.prefix = prefix;196 this.route = Require.nonNull("Target for requests", route);197 }198 @Override199 public boolean matches(HttpRequest request) {200 return hasPrefix(request) && route.matches(transform(request));201 }202 private boolean hasPrefix(HttpRequest request) {203 String[] parts = request.getUri().split("/");204 if (parts.length < prefixPaths.length) {205 return false;206 }207 for (int i = 0; i < prefixPaths.length; i++) {208 if (!prefixPaths[i].equals(parts[i])) {209 return false;210 }211 }212 return true;213 }214 @Override215 protected HttpResponse handle(HttpRequest req) {216 return route.execute(transform(req));217 }218 private HttpRequest transform(HttpRequest request) {219 // Strip the prefix from the existing request and forward it.220 String unprefixed = hasPrefix(request) ?221 request.getUri().substring(prefix.length()) :222 request.getUri();223 HttpRequest toForward = new HttpRequest(request.getMethod(), unprefixed);224 request.getHeaderNames().forEach(name -> {225 if (name == null) {226 return;227 }228 request.getHeaders(name).forEach(value -> toForward.addHeader(name, value));229 });230 request.getAttributeNames().forEach(231 attr -> toForward.setAttribute(attr, request.getAttribute(attr)));232 // Don't forget to register our prefix233 Object rawPrefixes = request.getAttribute(ROUTE_PREFIX_KEY);234 if (!(rawPrefixes instanceof List)) {235 rawPrefixes = new LinkedList<>();236 }237 List<String> prefixes = Stream.concat(((List<?>) rawPrefixes).stream(), Stream.of(prefix))238 .map(String::valueOf)239 .collect(toImmutableList());240 toForward.setAttribute(ROUTE_PREFIX_KEY, prefixes);241 request.getQueryParameterNames().forEach(name ->242 request.getQueryParameters(name).forEach(value -> toForward.addQueryParameter(name, value))243 );244 toForward.setContent(request.getContent());245 return toForward;246 }247 }248 private static class CombinedRoute extends Route {249 private final List<Routable> allRoutes;250 private CombinedRoute(Stream<Routable> routes) {251 // We want later routes to have a greater chance of being called so that we can override252 // routes as necessary.253 allRoutes = routes.collect(toImmutableList()).reverse();254 Require.stateCondition(!allRoutes.isEmpty(), "At least one route must be specified.");255 }256 @Override257 public boolean matches(HttpRequest request) {258 return allRoutes.stream().anyMatch(route -> route.matches(request));259 }260 @Override261 protected HttpResponse handle(HttpRequest req) {262 return allRoutes.stream()263 .filter(route -> route.matches(req))264 .findFirst()265 .map(route -> (HttpHandler) route)266 .orElse(request -> new HttpResponse()267 .setStatus(HTTP_NOT_FOUND)268 .setContent(utf8String("No handler found for " + request)))269 .execute(req);270 }271 }272 public static class PredicatedConfig {273 private final Predicate<HttpRequest> predicate;274 private PredicatedConfig(Predicate<HttpRequest> predicate) {275 this.predicate = Require.nonNull("Predicate", predicate);276 }277 public Route to(Supplier<HttpHandler> handler) {278 return new PredicatedRoute(predicate, Require.nonNull("Handler supplier", handler));279 }280 }281 private static class PredicatedRoute extends Route {282 private final Predicate<HttpRequest> predicate;283 private final Supplier<HttpHandler> supplier;284 private PredicatedRoute(Predicate<HttpRequest> predicate, Supplier<HttpHandler> supplier) {285 this.predicate = Require.nonNull("Predicate", predicate);286 this.supplier = Require.nonNull("Supplier", supplier);287 }288 @Override289 public boolean matches(HttpRequest httpRequest) {290 return predicate.test(httpRequest);291 }292 @Override293 protected HttpResponse handle(HttpRequest req) {294 HttpHandler handler = supplier.get();295 if (handler == null) {296 throw new IllegalStateException("No handler available.");297 }298 return handler.execute(req);299 }300 }301}...
Source:NetworkInterceptor.java
...22/**23 * Provides a mechanism for stubbing out responses to requests in drivers which24 * implement {@link HasDevTools}. Usage is done by specifying a {@link Route},25 * which will be checked for every request to see if that request should be26 * handled or not. Note that the URLs given to the {@code Route} will be fully27 * qualified.28 * <p>29 * Example usage:30 * <p>31 * <code>32 * Route route = Route.matching(req -> GET == req.getMethod() && req.getUri().endsWith("/example"))33 * .to(() -> req -> new HttpResponse().setContent(Contents.utf8String("Hello, World!")));34 *35 * try (NetworkInterceptor interceptor = new NetworkInterceptor(driver, route)) {36 * // Your code here.37 * }38 * </code>39 */40public class NetworkInterceptor implements Closeable {41 private static final Logger LOG = Logger.getLogger(NetworkInterceptor.class.getName());42 public static final HttpResponse PROCEED_WITH_REQUEST = new HttpResponse()43 .addHeader("Selenium-Interceptor", "Continue")44 .setContent(utf8String("Original request should proceed"));45 private final Route route;46 private final DevTools devTools;47 public NetworkInterceptor(WebDriver driver, Route route) {48 if (!(driver instanceof HasDevTools)) {49 throw new IllegalArgumentException("WebDriver instance must implement HasDevTools");50 }51 this.route = Objects.requireNonNull(route, "Route to use must be set.");52 devTools = ((HasDevTools) driver).getDevTools();53 devTools.createSession();54 devTools.addListener(Fetch.requestPaused(), this::handleRequest);55 devTools.send(Fetch.enable(56 Optional.empty(),57 Optional.of(false)));58 }59 @Override60 public void close() {61 }62 private void handleRequest(RequestPaused incoming) {63 // Only handle incoming requests. Diligently ignore responses.64 if (incoming.getResponseStatusCode() != null || incoming.getResponseErrorReason() != null) {65 return;66 }67 // The incoming request is fully qualified, so try and extract the bits68 // that make sense. We use URI since that doesn't need us to have network69 // handlers for all protocols.70 HttpRequest req;71 try {72 Request cdpReq = incoming.getRequest();73 req = new HttpRequest(74 HttpMethod.valueOf(cdpReq.getMethod()),75 cdpReq.getUrl() + (cdpReq.getUrlFragment() != null ? cdpReq.getUrlFragment() : ""));76 cdpReq.getHeaders().forEach((key, value) -> req.addHeader(key, String.valueOf(value)));77 if (!route.matches(req)) {78 continueRequest(incoming);79 return;80 }81 HttpResponse res = route.execute(req);82 // Yes! We are using an instance equality check. This is a magic value83 if (res == PROCEED_WITH_REQUEST) {...
Source:Router.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.router;18import org.openqa.selenium.grid.distributor.Distributor;19import org.openqa.selenium.grid.sessionmap.SessionMap;20import org.openqa.selenium.json.Json;21import org.openqa.selenium.remote.http.HttpClient;22import org.openqa.selenium.remote.http.HttpHandler;23import org.openqa.selenium.remote.http.HttpRequest;24import org.openqa.selenium.remote.http.HttpResponse;25import org.openqa.selenium.remote.http.Routable;26import org.openqa.selenium.remote.http.Route;27import org.openqa.selenium.remote.tracing.DistributedTracer;28import static org.openqa.selenium.remote.http.Route.combine;29import static org.openqa.selenium.remote.http.Route.get;30import static org.openqa.selenium.remote.http.Route.matching;31/**32 * A simple router that is aware of the selenium-protocol.33 */34public class Router implements Routable, HttpHandler {35 private final Route routes;36 public Router(37 DistributedTracer tracer,38 HttpClient.Factory clientFactory,39 SessionMap sessions,40 Distributor distributor) {41 routes = combine(42 get("/status")43 .to(() -> new GridStatusHandler(new Json(), clientFactory, distributor)),44 sessions,45 distributor,46 matching(req -> req.getUri().startsWith("/session/"))47 .to(() -> new HandleSession(tracer, clientFactory, sessions)));48 }49 @Override50 public boolean matches(HttpRequest req) {51 return routes.matches(req);52 }53 @Override54 public HttpResponse execute(HttpRequest req) {55 return routes.execute(req);56 }57}...
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!!