How to use ResourceHandler class of org.openqa.selenium.grid.web package

Best Selenium code snippet using org.openqa.selenium.grid.web.ResourceHandler

Source:Standalone.java Github

copy

Full Screen

...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);...

Full Screen

Full Screen

Source:Hub.java Github

copy

Full Screen

...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));...

Full Screen

Full Screen

Source:JreAppServer.java Github

copy

Full Screen

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

Full Screen

Full Screen

Source:HandlersForTests.java Github

copy

Full Screen

...18import com.google.common.net.MediaType;19import org.openqa.selenium.build.InProject;20import org.openqa.selenium.grid.security.BasicAuthenticationFilter;21import org.openqa.selenium.grid.web.PathResource;22import org.openqa.selenium.grid.web.ResourceHandler;23import org.openqa.selenium.remote.http.Contents;24import org.openqa.selenium.remote.http.HttpRequest;25import org.openqa.selenium.remote.http.HttpResponse;26import org.openqa.selenium.remote.http.Routable;27import org.openqa.selenium.remote.http.Route;28import java.io.UncheckedIOException;29import java.nio.file.Path;30import static java.nio.charset.StandardCharsets.UTF_8;31import static org.openqa.selenium.remote.http.HttpMethod.GET;32public class HandlersForTests implements Routable {33 private static final String TEMP_SRC_CONTEXT_PATH = "/temp";34 private final Route delegate;35 public HandlersForTests(String hostname, int port, Path tempPageDir) {36 CreatePageHandler createPageHandler = new CreatePageHandler(37 tempPageDir,38 hostname,39 port,40 TEMP_SRC_CONTEXT_PATH);41 Routable generatedPages = new ResourceHandler(new PathResource(tempPageDir));42 Path webSrc = InProject.locate("common/src/web");43 Route route = Route.combine(44 Route.get("/basicAuth").to(() -> req ->45 new HttpResponse()46 .addHeader("Content-Type", MediaType.HTML_UTF_8.toString())47 .setContent(Contents.string("<h1>authorized</h1>", UTF_8)))48 .with(new BasicAuthenticationFilter("test", "test")),49 Route.get("/echo").to(EchoHandler::new),50 Route.get("/cookie").to(CookieHandler::new),51 Route.get("/encoding").to(EncodingHandler::new),52 Route.matching(req -> req.getUri().startsWith("/generated/")).to(() -> new GeneratedJsTestHandler("/generated")),53 Route.matching(req -> req.getUri().startsWith("/page/") && req.getMethod() == GET).to(PageHandler::new),54 Route.post("/createPage").to(() -> createPageHandler),55 Route.get("/redirect").to(RedirectHandler::new),...

Full Screen

Full Screen

Source:CommonWebResources.java Github

copy

Full Screen

...18import org.openqa.selenium.build.InProject;19import org.openqa.selenium.grid.web.MergedResource;20import org.openqa.selenium.grid.web.PathResource;21import org.openqa.selenium.grid.web.Resource;22import org.openqa.selenium.grid.web.ResourceHandler;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 java.io.UncheckedIOException;28import java.nio.file.Path;29import static org.openqa.selenium.build.InProject.locate;30public class CommonWebResources implements Routable {31 private final Routable delegate;32 public CommonWebResources() {33 Resource resources = new MergedResource(new PathResource(locate("common/src/web")))34 .alsoCheck(new PathResource(locate("javascript").getParent()).limit("javascript"))35 .alsoCheck(new PathResource(locate("third_party/closure/goog").getParent()).limit("goog"))36 .alsoCheck(new PathResource(locate("third_party/js").getParent()).limit("js"));37 Path runfiles = InProject.findRunfilesRoot();38 if (runfiles != null) {39 ResourceHandler handler = new ResourceHandler(new PathResource(runfiles));40 delegate = Route.combine(41 new ResourceHandler(resources),42 Route.prefix("/filez").to(Route.combine(handler))43 );44 } else {45 delegate = new ResourceHandler(resources);46 }47 }48 @Override49 public boolean matches(HttpRequest req) {50 return delegate.matches(req);51 }52 @Override53 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {54 return delegate.execute(req);55 }56}...

Full Screen

Full Screen

ResourceHandler

Using AI Code Generation

copy

Full Screen

1ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));2route.addRoute(“/resource”, resourceHandler);3router.addRoute(route);4server.addRouter(router);5ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));6server.addHandler(“/resource”, resourceHandler);7ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));8server.addHandler(“/resource”, resourceHandler);9ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));10server.addHandler(“/resource”, resourceHandler);11ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));12server.addHandler(“/resource”, resourceHandler);13ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));14server.addHandler(“/resource”, resourceHandler);15ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));16server.addHandler(“/resource”, resourceHandler);17ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));18server.addHandler(“/resource”, resourceHandler);19ResourceHandler resourceHandler = new ResourceHandler(new File(“/path/to/your/resource”));20server.addHandler(“/resource”, resourceHandler);

Full Screen

Full Screen
copy
1@RequestMapping(value = "/download", method = RequestMethod.GET)2public ResponseEntity<byte[]> getDownloadData() throws Exception {34 String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";5 byte[] output = regData.getBytes();67 HttpHeaders responseHeaders = new HttpHeaders();8 responseHeaders.set("charset", "utf-8");9 responseHeaders.setContentType(MediaType.valueOf("text/html"));10 responseHeaders.setContentLength(output.length);11 responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");1213 return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);14}15
Full Screen
copy
1request.getRequestDispatcher("/downloads/<RANDOM-FILENAME>.pdf").forward(request, response);2
Full Screen
copy
1 @RequestMapping(value="/download")2 public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {3 try {45 String fileName="archivo demo.pdf";6 String filePathToBeServed = "C:\\software\\Tomcat 7.0\\tmpFiles\\";7 File fileToDownload = new File(filePathToBeServed+fileName);89 InputStream inputStream = new FileInputStream(fileToDownload);10 response.setContentType("application/force-download");11 response.setHeader("Content-Disposition", "attachment; filename="+fileName); 12 IOUtils.copy(inputStream, response.getOutputStream());13 response.flushBuffer();14 inputStream.close();15 } catch (Exception exception){16 System.out.println(exception.getMessage());17 }1819 }20
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 ResourceHandler

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