How to use getHostname method of org.openqa.selenium.grid.server.BaseServerOptions class

Best Selenium code snippet using org.openqa.selenium.grid.server.BaseServerOptions.getHostname

Source:JettyServer.java Github

copy

Full Screen

...55 private final HttpHandler handler;56 public JettyServer(BaseServerOptions options, HttpHandler handler) {57 this.handler = Objects.requireNonNull(handler, "Handler to use must be set.");58 int port = options.getPort() == 0 ? PortProber.findFreePort() : options.getPort();59 String host = options.getHostname().orElseGet(() -> {60 try {61 return new NetworkUtils().getNonLoopbackAddressOfThisMachine();62 } catch (WebDriverException ignored) {63 return "localhost";64 }65 });66 try {67 this.url = new URL("http", host, port, "");68 } catch (MalformedURLException e) {69 throw new UncheckedIOException(e);70 }71 Log.setLog(new JavaUtilLog());72 this.server = new org.eclipse.jetty.server.Server(73 new QueuedThreadPool(options.getMaxServerThreads()));74 this.servletContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);75 ConstraintSecurityHandler76 securityHandler =77 (ConstraintSecurityHandler) servletContextHandler.getSecurityHandler();78 Constraint disableTrace = new Constraint();79 disableTrace.setName("Disable TRACE");80 disableTrace.setAuthenticate(true);81 ConstraintMapping disableTraceMapping = new ConstraintMapping();82 disableTraceMapping.setConstraint(disableTrace);83 disableTraceMapping.setMethod("TRACE");84 disableTraceMapping.setPathSpec("/");85 securityHandler.addConstraintMapping(disableTraceMapping);86 Constraint enableOther = new Constraint();87 enableOther.setName("Enable everything but TRACE");88 ConstraintMapping enableOtherMapping = new ConstraintMapping();89 enableOtherMapping.setConstraint(enableOther);90 enableOtherMapping.setMethodOmissions(new String[]{"TRACE"});91 enableOtherMapping.setPathSpec("/");92 securityHandler.addConstraintMapping(enableOtherMapping);93 // Allow CORS: Whether the Selenium server should allow web browser connections from any host94 if (options.getAllowCORS()) {95 FilterHolder96 filterHolder = servletContextHandler.addFilter(CrossOriginFilter.class, "/*", EnumSet97 .of(DispatcherType.REQUEST));98 filterHolder.setInitParameter("allowedOrigins", "*");99 // Warning user100 LOG.warning("You have enabled CORS requests from any host. "101 + "Be careful not to visit sites which could maliciously "102 + "try to start Selenium sessions on your machine");103 }104 server.setHandler(servletContextHandler);105 HttpConfiguration httpConfig = new HttpConfiguration();106 httpConfig.setSecureScheme("https");107 ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));108 options.getHostname().ifPresent(http::setHost);109 http.setPort(getUrl().getPort());110 http.setIdleTimeout(500000);111 server.setConnectors(new Connector[]{http});112 }113 @Override114 public boolean isStarted() {115 return server.isStarted();116 }117 @Override118 public JettyServer start() {119 try {120 // If there are no routes, we've done something terribly wrong.121 if (handler == null) {122 throw new IllegalStateException("There must be at least one route specified");...

Full Screen

Full Screen

Source:NettyAppServer.java Github

copy

Full Screen

...53 Config config = createDefaultConfig();54 BaseServerOptions options = new BaseServerOptions(config);55 File tempDir = TemporaryFilesystem.getDefaultTmpFS().createTempDir("generated", "pages");56 HttpHandler handler = new HandlersForTests(57 options.getHostname().orElse("localhost"),58 options.getPort(),59 tempDir.toPath());60 server = new NettyServer(options, handler);61 Config secureConfig = new CompoundConfig(sslConfig, createDefaultConfig());62 BaseServerOptions secureOptions = new BaseServerOptions(secureConfig);63 HttpHandler secureHandler = new HandlersForTests(64 secureOptions.getHostname().orElse("localhost"),65 secureOptions.getPort(),66 tempDir.toPath());67 secure = new NettyServer(secureOptions, secureHandler);68 }69 public NettyAppServer(HttpHandler handler) {70 this(71 createDefaultConfig(),72 Require.nonNull("Handler", handler));73 }74 private NettyAppServer(Config config, HttpHandler handler) {75 Require.nonNull("Config", config);76 Require.nonNull("Handler", handler);77 server = new NettyServer(new BaseServerOptions(new MemoizedConfig(config)), handler);78 secure = null;79 }80 private static Config createDefaultConfig() {81 return new MemoizedConfig(new MapConfig(82 singletonMap("server", singletonMap("port", PortProber.findFreePort()))));83 }84 @Override85 public void start() {86 server.start();87 if (secure != null) {88 secure.start();89 }90 }91 @Override92 public void stop() {93 server.stop();94 if (secure != null) {95 secure.stop();96 }97 }98 @Override99 public String whereIs(String relativeUrl) {100 return createUrl(server, "http", getHostName(), relativeUrl);101 }102 @Override103 public String whereElseIs(String relativeUrl) {104 return createUrl(server, "http", getAlternateHostName(), relativeUrl);105 }106 @Override107 public String whereIsSecure(String relativeUrl) {108 if (secure == null) {109 throw new IllegalStateException("Server not configured to return HTTPS url");110 }111 return createUrl(secure, "https", getHostName(), relativeUrl);112 }113 @Override114 public String whereIsWithCredentials(String relativeUrl, String user, String password) {115 return String.format(116 "http://%s:%s@%s:%d/%s",117 user,118 password,119 getHostName(),120 server.getUrl().getPort(),121 relativeUrl);122 }123 private String createUrl(Server<?> server, String protocol, String hostName, String relativeUrl) {124 if (!relativeUrl.startsWith("/")) {125 relativeUrl = "/" + relativeUrl;126 }127 try {128 return new URL(129 protocol,130 hostName,131 server.getUrl().getPort(),132 relativeUrl133 ).toString();134 } catch (MalformedURLException e) {135 throw new UncheckedIOException(e);136 }137 }138 @Override139 public String create(Page page) {140 try (HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/")))) {141 HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage");142 request.setHeader(CONTENT_TYPE, JSON_UTF_8);143 request.setContent(Contents.asJson(ImmutableMap.of("content", page.toString())));144 HttpResponse response = client.execute(request);145 return string(response);146 } catch (IOException ex) {147 throw new RuntimeException(ex);148 }149 }150 @Override151 public String getHostName() {152 return AppServer.detectHostname();153 }154 @Override155 public String getAlternateHostName() {156 return AppServer.detectAlternateHostname();157 }158 public static void main(String[] args) {159 MemoizedConfig config = new MemoizedConfig(new MapConfig(singletonMap("server", singletonMap("port", 2310))));160 BaseServerOptions options = new BaseServerOptions(config);161 HttpHandler handler = new HandlersForTests(162 options.getHostname().orElse("localhost"),163 options.getPort(),164 TemporaryFilesystem.getDefaultTmpFS().createTempDir("netty", "server").toPath());165 NettyAppServer server = new NettyAppServer(166 config,167 handler);168 server.start();169 System.out.printf("Server started. Root URL: %s%n", server.whereIs("/"));170 }171}...

Full Screen

Full Screen

Source:JreAppServer.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.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.jre.server.JreServer;25import org.openqa.selenium.json.Json;26import org.openqa.selenium.net.PortProber;27import org.openqa.selenium.remote.http.HttpClient;28import org.openqa.selenium.remote.http.HttpHandler;29import org.openqa.selenium.remote.http.HttpMethod;30import org.openqa.selenium.remote.http.HttpRequest;31import org.openqa.selenium.remote.http.HttpResponse;32import org.openqa.selenium.remote.http.Route;33import java.io.IOException;34import java.io.UncheckedIOException;35import java.net.MalformedURLException;36import java.net.URL;37import java.nio.file.Path;38import java.util.Map;39import java.util.Objects;40import static com.google.common.net.HttpHeaders.CONTENT_TYPE;41import static com.google.common.net.MediaType.JSON_UTF_8;42import static java.nio.charset.StandardCharsets.UTF_8;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 Objects.requireNonNull(handler, "Handler to use must be set");56 int port = PortProber.findFreePort();57 server = new JreServer(58 new BaseServerOptions(new MapConfig(Map.of("server", Map.of("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}...

Full Screen

Full Screen

Source:BaseServerOptions.java Github

copy

Full Screen

...22 private final Config config;23 public BaseServerOptions(Config config) {24 this.config = config;25 }26 public Optional<String> getHostname() {27 return config.get("server", "hostname");28 }29 public int getPort() {30 int port = config.getInt("server", "port")31 .orElse(0);32 if (port < 0) {33 throw new ConfigException("Port cannot be less than 0: " + port);34 }35 return port;36 }37 public int getMaxServerThreads() {38 int count = config.getInt("server", "max-threads")39 .orElse(Runtime.getRuntime().availableProcessors() * 3);40 if (count < 0) {...

Full Screen

Full Screen

getHostname

Using AI Code Generation

copy

Full Screen

1package org.openqa.selenium.grid.server;2import org.openqa.selenium.Capabilities;3import org.openqa.selenium.ImmutableCapabilities;4import org.openqa.selenium.grid.config.Config;5import org.openqa.selenium.grid.config.ConfigException;6import org.openqa.selenium.grid.config.MemoizedConfig;7import org.openqa.selenium.grid.config.TomlConfig;8import org.openqa.selenium.grid.data.Session;9import org.openqa.selenium.grid.node.BaseNode;10import org.openqa.selenium.grid.node.Node;11import org.openqa.selenium.grid.node.NodeStatus;12import org.openqa.selenium.grid.node.local.LocalNode;13import org.openqa.selenium.grid.security.Secret;14import org.openqa.selenium.grid.security.SecretOptions;15import org.openqa.selenium.grid.sessionmap.SessionMap;16import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;17import org.openqa.selenium.grid.web.CommandHandler;18import org.openqa.selenium.grid.web.CommandHandlerException;19import org.openqa.selenium.grid.web.CommandHandlerResponse;20import org.openqa.selenium.grid.web.Routable;21import org.openqa.selenium.grid.web.Routes;22import org.openqa.selenium.internal.Require;23import org.openqa.selenium.json.Json;24import org.openqa.selenium.remote.Dialect;25import org.openqa.selenium.remote.http.Contents;26import org.openqa.selenium.remote.http.HttpMethod;27import org.openqa.selenium.remote.http.HttpResponse;28import org.openqa.selenium.remote.tracing.Tracer;29import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;30import java.io.IOException;31import java.io.UncheckedIOException;32import java.net.URI;33import java.net.URISyntaxException;34import java.net.URL;35import java.time.Duration;36import java.util.Collections;37import java.util.Map;38import java.util.Objects;39import java.util.Optional;40import java.util.Set;41import java.util.logging.Logger;42import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;43import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;44import static java.net.HttpURLConnection.HTTP_OK;45import static java.nio.charset.StandardCharsets.UTF_8;46import static org.openqa.selenium.grid.config.StandardGridRoles.SESSION_MAP_ROLE;47import static org.openqa.selenium.grid.data.Availability.DOWN;48import static org.openqa.selenium.grid.data.Availability.UP;49import static org.openqa.selenium.grid.web.Routes.combine;50import static org.openqa.selenium.remote.Dialect.OSS;51import static org.openqa.selenium.remote.Dialect.W3C;52public class GridServer implements CommandHandler {53 private static final Logger LOG = Logger.getLogger(GridServer.class.getName());54 private final Tracer tracer;55 private final SessionMap sessions;56 private final Node node;57 private final Json json;58 private final Secret registrationSecret;

Full Screen

Full Screen

getHostname

Using AI Code Generation

copy

Full Screen

1public class BaseServerOptionsTest {2 public void testGetHostname() {3 BaseServerOptions baseServerOptions = new BaseServerOptions();4 String hostName = baseServerOptions.getHostname();5 System.out.println(hostName);6 }7}

Full Screen

Full Screen

getHostname

Using AI Code Generation

copy

Full Screen

1public class BaseServerOptionsTest {2public static void main(String[] args) {3 BaseServerOptions baseServerOptions = new BaseServerOptions();4 baseServerOptions.setHost("localhost");5 baseServerOptions.setPort(4444);6 System.out.println("Hostname: "+baseServerOptions.getHostname());7}8}

Full Screen

Full Screen

getHostname

Using AI Code Generation

copy

Full Screen

1 BaseServerOptions baseServerOptions = new BaseServerOptions();2 String hostName = baseServerOptions.getHostname();3 String protocol = "http";4 String path = "/wd/hub";5 return url;6 }7}

Full Screen

Full Screen

getHostname

Using AI Code Generation

copy

Full Screen

1return getHostname();2return getHost();3return getPort();4return getExternalUri();5return getExternalUri(path);6return getExternalUri(path, query);7return getExternalUri(path, query, fragment);8return getExternalUri(query);

Full Screen

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful