Best Selenium code snippet using org.openqa.selenium.grid.router.ProxyWebsocketsIntoGrid
Source:NewSessionCreationTest.java
...107 .with(new EnsureSpecCompliantHeaders(ImmutableList.of(), ImmutableSet.of()));108 server = new NettyServer(109 new BaseServerOptions(new MapConfig(ImmutableMap.of())),110 router,111 new ProxyWebsocketsIntoGrid(clientFactory, sessions))112 .start();113 URI uri = server.getUrl().toURI();114 Node node = LocalNode.builder(115 tracer,116 events,117 uri,118 uri,119 registrationSecret)120 .add(121 Browser.detect().getCapabilities(),122 new TestSessionFactory(123 (id, caps) ->124 new Session(id, uri, Browser.detect().getCapabilities(), caps, Instant.now())))125 .build();...
Source:Hub.java
...36import org.openqa.selenium.grid.distributor.config.DistributorOptions;37import org.openqa.selenium.grid.distributor.local.LocalDistributor;38import org.openqa.selenium.grid.graphql.GraphqlHandler;39import org.openqa.selenium.grid.log.LoggingOptions;40import org.openqa.selenium.grid.router.ProxyWebsocketsIntoGrid;41import org.openqa.selenium.grid.router.Router;42import org.openqa.selenium.grid.security.BasicAuthenticationFilter;43import org.openqa.selenium.grid.security.Secret;44import org.openqa.selenium.grid.security.SecretOptions;45import org.openqa.selenium.grid.server.BaseServerOptions;46import org.openqa.selenium.grid.server.EventBusOptions;47import org.openqa.selenium.grid.server.NetworkOptions;48import org.openqa.selenium.grid.server.Server;49import org.openqa.selenium.grid.sessionmap.SessionMap;50import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;51import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;52import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;53import org.openqa.selenium.grid.sessionqueue.local.LocalNewSessionQueue;54import org.openqa.selenium.grid.web.CombinedHandler;55import org.openqa.selenium.grid.web.GridUiRoute;56import org.openqa.selenium.grid.web.RoutableHttpClientFactory;57import org.openqa.selenium.internal.Require;58import org.openqa.selenium.remote.http.Contents;59import org.openqa.selenium.remote.http.HttpClient;60import org.openqa.selenium.remote.http.HttpHandler;61import org.openqa.selenium.remote.http.HttpResponse;62import org.openqa.selenium.remote.http.Routable;63import org.openqa.selenium.remote.http.Route;64import org.openqa.selenium.remote.tracing.Tracer;65import java.net.MalformedURLException;66import java.net.URL;67import java.util.Collections;68import java.util.Set;69import java.util.logging.Logger;70@AutoService(CliCommand.class)71public class Hub extends TemplateGridServerCommand {72 private static final Logger LOG = Logger.getLogger(Hub.class.getName());73 @Override74 public String getName() {75 return "hub";76 }77 @Override78 public String getDescription() {79 return "A grid hub, composed of sessions, distributor, and router.";80 }81 @Override82 public Set<Role> getConfigurableRoles() {83 return ImmutableSet.of(84 DISTRIBUTOR_ROLE,85 EVENT_BUS_ROLE,86 HTTPD_ROLE,87 SESSION_QUEUE_ROLE,88 ROUTER_ROLE);89 }90 @Override91 public Set<Object> getFlagObjects() {92 return Collections.emptySet();93 }94 @Override95 protected String getSystemPropertiesConfigPrefix() {96 return "selenium";97 }98 @Override99 protected Config getDefaultConfig() {100 return new DefaultHubConfig();101 }102 @Override103 protected Handlers createHandlers(Config config) {104 LoggingOptions loggingOptions = new LoggingOptions(config);105 Tracer tracer = loggingOptions.getTracer();106 EventBusOptions events = new EventBusOptions(config);107 EventBus bus = events.getEventBus();108 CombinedHandler handler = new CombinedHandler();109 SessionMap sessions = new LocalSessionMap(tracer, bus);110 handler.addHandler(sessions);111 BaseServerOptions serverOptions = new BaseServerOptions(config);112 SecretOptions secretOptions = new SecretOptions(config);113 Secret secret = secretOptions.getRegistrationSecret();114 URL externalUrl;115 try {116 externalUrl = serverOptions.getExternalUri().toURL();117 } catch (MalformedURLException e) {118 throw new IllegalArgumentException(e);119 }120 NetworkOptions networkOptions = new NetworkOptions(config);121 HttpClient.Factory clientFactory = new RoutableHttpClientFactory(122 externalUrl,123 handler,124 networkOptions.getHttpClientFactory(tracer));125 DistributorOptions distributorOptions = new DistributorOptions(config);126 NewSessionQueueOptions newSessionRequestOptions = new NewSessionQueueOptions(config);127 NewSessionQueue queue = new LocalNewSessionQueue(128 tracer,129 bus,130 distributorOptions.getSlotMatcher(),131 newSessionRequestOptions.getSessionRequestRetryInterval(),132 newSessionRequestOptions.getSessionRequestTimeout(),133 secret);134 handler.addHandler(queue);135 Distributor distributor = new LocalDistributor(136 tracer,137 bus,138 clientFactory,139 sessions,140 queue,141 distributorOptions.getSlotSelector(),142 secret,143 distributorOptions.getHealthCheckInterval(),144 distributorOptions.shouldRejectUnsupportedCaps(),145 newSessionRequestOptions.getSessionRequestRetryInterval());146 handler.addHandler(distributor);147 Router router = new Router(tracer, clientFactory, sessions, queue, distributor);148 GraphqlHandler graphqlHandler = new GraphqlHandler(149 tracer,150 distributor,151 queue,152 serverOptions.getExternalUri(),153 getServerVersion());154 HttpHandler readinessCheck = req -> {155 boolean ready = router.isReady() && bus.isReady();156 return new HttpResponse()157 .setStatus(ready ? HTTP_OK : HTTP_INTERNAL_ERROR)158 .setContent(Contents.utf8String("Router is " + ready));159 };160 Routable ui = new GridUiRoute();161 Routable routerWithSpecChecks = router.with(networkOptions.getSpecComplianceChecks());162 Routable httpHandler = combine(163 ui,164 routerWithSpecChecks,165 Route.prefix("/wd/hub").to(combine(routerWithSpecChecks)),166 Route.options("/graphql").to(() -> graphqlHandler),167 Route.post("/graphql").to(() -> graphqlHandler));168 UsernameAndPassword uap = secretOptions.getServerAuthentication();169 if (uap != null) {170 LOG.info("Requiring authentication to connect");171 httpHandler = httpHandler.with(new BasicAuthenticationFilter(uap.username(), uap.password()));172 }173 // Allow the liveness endpoint to be reached, since k8s doesn't make it easy to authenticate these checks174 httpHandler = combine(httpHandler, Route.get("/readyz").to(() -> readinessCheck));175 return new Handlers(httpHandler, new ProxyWebsocketsIntoGrid(clientFactory, sessions));176 }177 @Override178 protected void execute(Config config) {179 Require.nonNull("Config", config);180 Server<?> server = asServer(config).start();181 LOG.info(String.format("Started Selenium Hub %s: %s", getServerVersion(), server.getUrl()));182 }183 private String getServerVersion() {184 BuildInfo info = new BuildInfo();185 return String.format("%s (revision %s)", info.getReleaseLabel(), info.getBuildRevision());186 }187}...
Source:ProxyCdpTest.java
...60 EventBus events = new GuavaEventBus();61 sessions = new LocalSessionMap(tracer, events);62 // Set up the proxy we'll be using63 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();64 ProxyWebsocketsIntoGrid proxy = new ProxyWebsocketsIntoGrid(clientFactory, sessions);65 proxyServer = new NettyServer(new BaseServerOptions(emptyConfig), nullHandler, proxy).start();66 }67 @After68 public void tearDown() {69 proxyServer.stop();70 }71 @Test72 public void shouldForwardTextMessageToServer() throws URISyntaxException, InterruptedException {73 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();74 // Create a backend server which will capture any incoming text message75 AtomicReference<String> text = new AtomicReference<>();76 CountDownLatch latch = new CountDownLatch(1);77 Server<?> backend = createBackendServer(latch, text, "", emptyConfig);78 // Push a session that resolves to the backend server into the session map79 SessionId id = new SessionId(UUID.randomUUID());80 sessions.add(new Session(id, backend.getUrl().toURI(), new ImmutableCapabilities(), new ImmutableCapabilities(), Instant.now()));81 // Now! Send a message. We expect it to eventually show up in the backend82 try (WebSocket socket = clientFactory.createClient(proxyServer.getUrl())83 .openSocket(new HttpRequest(GET, String.format("/session/%s/cdp", id)), new WebSocket.Listener(){})) {84 socket.sendText("Cheese!");85 assertThat(latch.await(5, SECONDS)).isTrue();86 assertThat(text.get()).isEqualTo("Cheese!");87 }88 }89 @Test90 public void shouldForwardTextMessageFromServerToLocalEnd() throws URISyntaxException, InterruptedException {91 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();92 Server<?> backend = createBackendServer(new CountDownLatch(1), new AtomicReference<>(), "Asiago", emptyConfig);93 // Push a session that resolves to the backend server into the session map94 SessionId id = new SessionId(UUID.randomUUID());95 sessions.add(new Session(id, backend.getUrl().toURI(), new ImmutableCapabilities(), new ImmutableCapabilities(), Instant.now()));96 // Now! Send a message. We expect it to eventually show up in the backend97 CountDownLatch latch = new CountDownLatch(1);98 AtomicReference<String> text = new AtomicReference<>();99 try(WebSocket socket = clientFactory.createClient(proxyServer.getUrl())100 .openSocket(new HttpRequest(GET, String.format("/session/%s/cdp", id)), new WebSocket.Listener() {101 @Override102 public void onText(CharSequence data) {103 text.set(data.toString());104 latch.countDown();105 }106 })) {107 socket.sendText("Cheese!");108 assertThat(latch.await(5, SECONDS)).isTrue();109 assertThat(text.get()).isEqualTo("Asiago");110 }111 }112 @Test113 public void shouldBeAbleToSendMessagesOverSecureWebSocket()114 throws URISyntaxException, InterruptedException {115 Config secureConfig = new MapConfig(ImmutableMap.of(116 "server", ImmutableMap.of(117 "https-self-signed", true)));118 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();119 ProxyWebsocketsIntoGrid proxy = new ProxyWebsocketsIntoGrid(clientFactory, sessions);120 Server<?> backend = createBackendServer(new CountDownLatch(1), new AtomicReference<>(), "Cheddar", emptyConfig);121 Server<?> secureProxyServer = new NettyServer(new BaseServerOptions(secureConfig), nullHandler, proxy);122 secureProxyServer.start();123 // Push a session that resolves to the backend server into the session map124 SessionId id = new SessionId(UUID.randomUUID());125 sessions.add(new Session(id, backend.getUrl().toURI(), new ImmutableCapabilities(), new ImmutableCapabilities(), Instant.now()));126 CountDownLatch latch = new CountDownLatch(1);127 AtomicReference<String> text = new AtomicReference<>();128 try (WebSocket socket = clientFactory.createClient(secureProxyServer.getUrl())129 .openSocket(new HttpRequest(GET, String.format("/session/%s/cdp", id)), new WebSocket.Listener() {130 @Override131 public void onText(CharSequence data) {132 text.set(data.toString());133 latch.countDown();...
Source:RouterServer.java
...38import org.openqa.selenium.grid.distributor.config.DistributorOptions;39import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;40import org.openqa.selenium.grid.graphql.GraphqlHandler;41import org.openqa.selenium.grid.log.LoggingOptions;42import org.openqa.selenium.grid.router.ProxyWebsocketsIntoGrid;43import org.openqa.selenium.grid.router.Router;44import org.openqa.selenium.grid.security.BasicAuthenticationFilter;45import org.openqa.selenium.grid.security.Secret;46import org.openqa.selenium.grid.security.SecretOptions;47import org.openqa.selenium.grid.server.BaseServerOptions;48import org.openqa.selenium.grid.server.NetworkOptions;49import org.openqa.selenium.grid.server.Server;50import org.openqa.selenium.grid.sessionmap.SessionMap;51import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;52import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;53import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;54import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue;55import org.openqa.selenium.grid.web.GridUiRoute;56import org.openqa.selenium.internal.Require;57import org.openqa.selenium.remote.http.ClientConfig;58import org.openqa.selenium.remote.http.HttpClient;59import org.openqa.selenium.remote.http.HttpResponse;60import org.openqa.selenium.remote.http.Routable;61import org.openqa.selenium.remote.http.Route;62import org.openqa.selenium.remote.tracing.Tracer;63import java.net.URL;64import java.time.Duration;65import java.util.Collections;66import java.util.Set;67import java.util.logging.Logger;68@AutoService(CliCommand.class)69public class RouterServer extends TemplateGridServerCommand {70 private static final Logger LOG = Logger.getLogger(RouterServer.class.getName());71 @Override72 public String getName() {73 return "router";74 }75 @Override76 public String getDescription() {77 return "Creates a router to front the selenium grid.";78 }79 @Override80 public Set<Role> getConfigurableRoles() {81 return ImmutableSet.of(82 DISTRIBUTOR_ROLE,83 HTTPD_ROLE,84 ROUTER_ROLE,85 SESSION_MAP_ROLE,86 SESSION_QUEUE_ROLE);87 }88 @Override89 public Set<Object> getFlagObjects() {90 return Collections.emptySet();91 }92 @Override93 protected String getSystemPropertiesConfigPrefix() {94 return "router";95 }96 @Override97 protected Config getDefaultConfig() {98 return new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", 4444)));99 }100 @Override101 protected Handlers createHandlers(Config config) {102 LoggingOptions loggingOptions = new LoggingOptions(config);103 Tracer tracer = loggingOptions.getTracer();104 NetworkOptions networkOptions = new NetworkOptions(config);105 HttpClient.Factory clientFactory = networkOptions.getHttpClientFactory(tracer);106 BaseServerOptions serverOptions = new BaseServerOptions(config);107 SecretOptions secretOptions = new SecretOptions(config);108 Secret secret = secretOptions.getRegistrationSecret();109 SessionMapOptions sessionsOptions = new SessionMapOptions(config);110 SessionMap sessions = sessionsOptions.getSessionMap();111 NewSessionQueueOptions newSessionQueueOptions = new NewSessionQueueOptions(config);112 URL sessionQueueUrl = fromUri(newSessionQueueOptions.getSessionQueueUri());113 Duration sessionRequestTimeout = newSessionQueueOptions.getSessionRequestTimeout();114 ClientConfig httpClientConfig = ClientConfig115 .defaultConfig()116 .baseUrl(sessionQueueUrl)117 .readTimeout(sessionRequestTimeout);118 NewSessionQueue queue = new RemoteNewSessionQueue(119 tracer,120 clientFactory.createClient(httpClientConfig),121 secret);122 DistributorOptions distributorOptions = new DistributorOptions(config);123 URL distributorUrl = fromUri(distributorOptions.getDistributorUri());124 Distributor distributor = new RemoteDistributor(125 tracer,126 clientFactory,127 distributorUrl,128 secret);129 GraphqlHandler graphqlHandler = new GraphqlHandler(130 tracer,131 distributor,132 queue,133 serverOptions.getExternalUri(),134 getServerVersion());135 Routable ui = new GridUiRoute();136 Routable routerWithSpecChecks = new Router(tracer, clientFactory, sessions, queue, distributor)137 .with(networkOptions.getSpecComplianceChecks());138 Routable route = Route.combine(139 ui,140 routerWithSpecChecks,141 Route.prefix("/wd/hub").to(combine(routerWithSpecChecks)),142 Route.options("/graphql").to(() -> graphqlHandler),143 Route.post("/graphql").to(() -> graphqlHandler));144 UsernameAndPassword uap = secretOptions.getServerAuthentication();145 if (uap != null) {146 LOG.info("Requiring authentication to connect");147 route = route.with(new BasicAuthenticationFilter(uap.username(), uap.password()));148 }149 // Since k8s doesn't make it easy to do an authenticated liveness probe, allow unauthenticated access to it.150 Routable routeWithLiveness = Route.combine(151 route,152 get("/readyz").to(() -> req -> new HttpResponse().setStatus(HTTP_NO_CONTENT)));153 return new Handlers(routeWithLiveness, new ProxyWebsocketsIntoGrid(clientFactory, sessions));154 }155 @Override156 protected void execute(Config config) {157 Require.nonNull("Config", config);158 Server<?> server = asServer(config).start();159 LOG.info(String.format(160 "Started Selenium Router %s: %s", getServerVersion(), server.getUrl()));161 }162 private String getServerVersion() {163 BuildInfo info = new BuildInfo();164 return String.format("%s (revision %s)", info.getReleaseLabel(), info.getBuildRevision());165 }166}...
Source:ProxyWebsocketsIntoGrid.java
...34import java.util.function.Consumer;35import java.util.logging.Level;36import java.util.logging.Logger;37import static org.openqa.selenium.remote.http.HttpMethod.GET;38public class ProxyWebsocketsIntoGrid implements BiFunction<String, Consumer<Message>,39 Optional<Consumer<Message>>> {40 private static final Logger LOG = Logger.getLogger(ProxyWebsocketsIntoGrid.class.getName());41 private final HttpClient.Factory clientFactory;42 private final SessionMap sessions;43 public ProxyWebsocketsIntoGrid(HttpClient.Factory clientFactory, SessionMap sessions) {44 this.clientFactory = Objects.requireNonNull(clientFactory);45 this.sessions = Objects.requireNonNull(sessions);46 }47 @Override48 public Optional<Consumer<Message>> apply(String uri, Consumer<Message> downstream) {49 Objects.requireNonNull(uri);50 Objects.requireNonNull(downstream);51 Optional<SessionId> sessionId = HttpSessionId.getSessionId(uri).map(SessionId::new);52 if (!sessionId.isPresent()) {53 return Optional.empty();54 }55 try {56 Session session = sessions.get(sessionId.get());57 HttpClient client = clientFactory.createClient(ClientConfig.defaultConfig().baseUri(session.getUri()));...
ProxyWebsocketsIntoGrid
Using AI Code Generation
1package org.openqa.selenium.grid.router;2import org.openqa.selenium.grid.config.Config;3import org.openqa.selenium.grid.config.MemoizedConfig;4import org.openqa.selenium.grid.config.TomlConfig;5import org.openqa.selenium.grid.security.Secret;6import org.openqa.selenium.grid.security.Secrets;7import org.openqa.selenium.grid.security.TlsCertificates;8import org.openqa.selenium.grid.server.BaseServerOptions;9import org.openqa.selenium.grid.server.Server;10import org.openqa.selenium.grid.server.ServerFlags;11import org.openqa.selenium.grid.server.ServerSecretOptions;12import org.openqa.selenium.grid.web.Values;13import org.openqa.selenium.internal.Require;14import org.openqa.selenium.net.PortProber;15import org.openqa.selenium.net.UrlChecker;16import org.openqa.selenium.remote.http.HttpClient;17import org.openqa.selenium.remote.http.HttpMethod;18import org.openqa.selenium.remote.http.HttpRequest;19import org.openqa.selenium.remote.http.HttpResponse;20import org.openqa.selenium.remote.tracing.Tracer;21import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;22import java.io.IOException;23import java.net.URI;24import java.net.URISyntaxException;25import java.nio.file.Path;26import java.nio.file.Paths;27import java.time.Duration;28import java.util.HashMap;29import java.util.Map;30import java.util.Objects;31import java.util.Optional;32import java.util.logging.Logger;33import static org.openqa.selenium.grid.config.StandardGridRoles.ROUTER_ROLE;34import static org.openqa.selenium.grid.config.StandardGridRoles.getRole;35import static org.openqa.selenium.remote.http.Contents.utf8String;36import static org.openqa.selenium.remote.http.Route.combine;37import static org.openqa.selenium.remote.http.Route.get;38public class ProxyWebsocketsIntoGrid {39 private static final Logger LOG = Logger.getLogger(ProxyWebsocketsIntoGrid.class.getName());40 private static final String DEFAULT_CONFIG = "config.toml";41 private static final String DEFAULT_HOST = "localhost";42 private static final String DEFAULT_PORT = "4444";43 private static final String DEFAULT_PATH = "/wd/hub";44 private static final String DEFAULT_PROXY_PATH = "/wd/hub";45 private static final String DEFAULT_PROXY_HOST = "localhost";46 private static final String DEFAULT_PROXY_PORT = "4444";47 private static final String DEFAULT_PROXY_PROTOCOL = "http";48 private static final String DEFAULT_PROXY_SSL = "false";49 private static final String DEFAULT_PROXY_SSL_CA = "";50 private static final String DEFAULT_PROXY_SSL_CA_CERT = "";51 private static final String DEFAULT_PROXY_SSL_CA_KEY = "";
ProxyWebsocketsIntoGrid
Using AI Code Generation
1import org.openqa.selenium.grid.router.ProxyWebsocketsIntoGrid;2import org.openqa.selenium.grid.router.Router;3import org.openqa.selenium.grid.web.Routable;4import org.openqa.selenium.remote.http.HttpHandler;5import org.openqa.selenium.remote.http.Route;6import org.openqa.selenium.remote.http.WebSocket;7import java.util.function.Supplier;8public class ProxyWebsocketsIntoGridExample {9 public static void main(String[] args) {10 Router router = new Router();11 ProxyWebsocketsIntoGrid proxy = new ProxyWebsocketsIntoGrid(router);12 Routable route = Route.matching(req -> req.getUri().startsWith("/"))13 .to((Supplier<HttpHandler>) () -> proxy);14 router.add(route);15 WebSocket ws = WebSocket.createWebSocket(16 req -> req.getUri().startsWith("/"),17 (req, res) -> {18 System.out.println("Websocket connected");19 return null;20 });21 router.add(ws);22 router.start();23 }24}25import org.openqa.selenium.grid.router.ProxyWebsocketsIntoGrid;26import org.openqa.selenium.grid.router.Router;27import org.openqa.selenium.grid.web.Routable;28import org.openqa.selenium.remote.http.HttpHandler;29import org.openqa.selenium.remote.http.Route;30import org.openqa.selenium.remote.http.WebSocket;31import java.util.function.Supplier;32public class ProxyWebsocketsIntoGridExample {33 public static void main(String[] args) {34 Router router = new Router();35 ProxyWebsocketsIntoGrid proxy = new ProxyWebsocketsIntoGrid(router);36 Routable route = Route.matching(req -> req.getUri().startsWith("/"))37 .to((Supplier<HttpHandler>) () -> proxy);38 router.add(route);39 WebSocket ws = WebSocket.createWebSocket(40 req -> req.getUri().startsWith("/"),41 (req, res) -> {42 System.out.println("Websocket connected");43 return null;44 });45 router.add(ws);
ProxyWebsocketsIntoGrid
Using AI Code Generation
1import org.openqa.selenium.grid.router.ProxyWebsocketsIntoGrid;2import java.net.URI;3import java.net.URISyntaxException;4public class ProxyWebsocketsIntoGridExample {5 public static void main(String[] args) throws URISyntaxException {6 proxyWebsocketsIntoGrid.start();7 }8}9proxyWebsocketsIntoGrid.start();10proxyWebsocketsIntoGrid.stop();11proxyWebsocketsIntoGrid.start();
ProxyWebsocketsIntoGrid
Using AI Code Generation
1package com.selenium.grid;2import org.openqa.selenium.grid.router.ProxyWebsocketsIntoGrid;3import org.openqa.selenium.grid.router.Router;4import org.openqa.selenium.grid.web.Routable;5import org.openqa.selenium.grid.web.Values;6import org.openqa.selenium.net.PortProber;7import org.openqa.selenium.remote.http.HttpClient;8import org.openqa.selenium.remote.http.HttpMethod;9import org.openqa.selenium.remote.http.HttpRequest;10import org.openqa.selenium.remote.http.HttpResponse;11import org.openqa.selenium.remote.http.Route;12import org.openqa.selenium.remote.tracing.Tracer;13import java.io.IOException;14import java.net.URI;15import java.net.URISyntaxException;16import java.util.Objects;17import java.util.function.Predicate;18public class CustomProxyWebsocketsIntoGrid implements Routable {19 private final HttpClient.Factory clientFactory;20 private final Predicate<URI> shouldProxy;21 private final Tracer tracer;22 public CustomProxyWebsocketsIntoGrid(HttpClient.Factory clientFactory, Predicate<URI> shouldProxy, Tracer tracer) {23 this.clientFactory = Objects.requireNonNull(clientFactory);24 this.shouldProxy = Objects.requireNonNull(shouldProxy);25 this.tracer = Objects.requireNonNull(tracer);26 }27 public void execute(HttpRequest req, HttpResponse resp) throws IOException {28 if (req.getMethod() != HttpMethod.GET) {29 resp.setStatus(404);30 return;31 }32 if (!"websocket".equalsIgnoreCase(req.getHeader("Upgrade"))) {33 resp.setStatus(404);34 return;35 }36 URI downstream;37 try {38 downstream = new URI(req.getHeader("Sec-WebSocket-Protocol"));39 } catch (URISyntaxException e) {40 resp.setStatus(404);41 return;42 }43 if (!shouldProxy.test(downstream)) {44 resp.setStatus(404);45 return;46 }47 ProxyWebsocketsIntoGrid proxy = new ProxyWebsocketsIntoGrid(clientFactory, tracer);48 proxy.execute(req, resp);49 }50 public Route getRoute() {51 return new Route(52 new Values<>(Values::nonNull, "sessionId", "nodeId"));53 }54}55package com.selenium.grid;56import org.openqa.selenium.grid.config.Config;57import org.openqa.selenium.grid.config.ConfigException;58import org.openqa.selenium.grid.config.MemoizedConfig;59import org.openqa.selenium.grid.config.TomlConfig;60import
ProxyWebsocketsIntoGrid
Using AI Code Generation
1package org.openqa.selenium.grid.router;2import org.openqa.selenium.grid.data.Session;3import org.openqa.selenium.grid.web.CommandHandler;4import org.openqa.selenium.grid.web.Routable;5import org.openqa.selenium.grid.web.Routes;6import org.openqa.selenium.internal.Require;7import org.openqa.selenium.remote.http.HttpHandler;8import org.openqa.selenium.remote.http.HttpRequest;9import org.openqa.selenium.remote.http.HttpResponse;10import org.openqa.selenium.remote.tracing.Tracer;11import java.util.Objects;12import java.util.function.Function;13public class ProxyWebsocketsIntoGrid implements Routable {14 private final Tracer tracer;15 private final Function<Session, CommandHandler> downstream;16 public ProxyWebsocketsIntoGrid(Tracer tracer, Function<Session, CommandHandler> downstream) {17 this.tracer = Require.nonNull("Tracer", tracer);18 this.downstream = Require.nonNull("Downstream function", downstream);19 }20 public void addRoutes(Routes routes) {21 Require.nonNull("Routes", routes);22 routes.add(Route.post("/se/grid/router/session/{sessionId}/se/grid/router/websocket")23 .to(() -> new CommandHandler() {24 public void execute(HttpRequest req, HttpResponse resp) {25 }26 }));27 routes.add(Route.get("/se/grid/router/session/{sessionId}/se/grid/router/websocket")28 .to(() -> new CommandHandler() {29 public void execute(HttpRequest req, HttpResponse resp) {30 String id = Objects.requireNonNull(req.getPath().get("sessionId"));31 Session session = new Session(id);32 downstream.apply(session).execute(req, resp);33 }34 }));35 }36}37[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ selenium ---
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!!