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

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

Source:JettyServer.java Github

copy

Full Screen

...54 private final URL url;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");123 }124 servletContextHandler.addServlet(125 new ServletHolder(new HttpHandlerServlet(handler.with(new WrapExceptions().andThen(new AddWebDriverSpecHeaders())))),126 "/*");127 server.start();128 PortProber.waitForPortUp(getUrl().getPort(), 10, SECONDS);129 return this;130 } catch (Exception e) {131 try {132 stop();133 } catch (Exception ignore) {134 }135 if (e instanceof BindException) {136 LOG.severe(String.format(137 "Port %s is busy, please choose a free port and specify it using -port option",138 getUrl().getPort()));139 }140 if (e instanceof RuntimeException) {141 throw (RuntimeException) e;142 }143 throw new RuntimeException(e);144 }145 }146 @Override147 public void stop() {148 int numTries = 0;149 Exception shutDownException = null;150 // shut down the jetty server (try try again)151 while (numTries <= MAX_SHUTDOWN_RETRIES) {152 numTries++;...

Full Screen

Full Screen

Source:NettyAppServer.java Github

copy

Full Screen

...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:SeleniumServer.java Github

copy

Full Screen

...93 route = combine(route, rcHandler);94 }95 setHandler(route);96 super.start();97 LOG.info(String.format("Selenium Server is up and running on port %s", configuration.getPort()));98 return this;99 }100 /**101 * Stops the Jetty server102 */103 @Override104 public void stop() {105 try {106 super.stop();107 } finally {108 new JMXHelper().unregister(objectName);109 stopAllBrowsers();110 }111 }...

Full Screen

Full Screen

Source:NettyServer.java Github

copy

Full Screen

...47 Objects.requireNonNull(handler, "Handler to use must be set.");48 this.handler = handler.with(new WrapExceptions().andThen(new AddWebDriverSpecHeaders()));49 bossGroup = new NioEventLoopGroup(1);50 workerGroup = new NioEventLoopGroup();51 port = options.getPort();52 try {53 externalUrl = options.getExternalUri().toURL();54 } catch (MalformedURLException e) {55 throw new UncheckedIOException("Server URI is not a valid URL: " + options.getExternalUri(), e);56 }57 }58 @Override59 public boolean isStarted() {60 return channel != null;61 }62 @Override63 public URL getUrl() {64 return externalUrl;65 }...

Full Screen

Full Screen

Source:JreServer.java Github

copy

Full Screen

...37 Objects.requireNonNull(options);38 Objects.requireNonNull(handler);39 try {40 url = options.getExternalUri().toURL();41 server = HttpServer.create(new InetSocketAddress(url.getPort()), 0);42 } catch (IOException e) {43 throw new UncheckedIOException(e);44 }45 server.setExecutor(null);46 server.createContext(47 "/", httpExchange -> {48 HttpRequest req = JreMessages.asRequest(httpExchange);49 HttpResponse res = handler.execute(req);50 res.getHeaderNames().forEach(51 name -> res.getHeaders(name).forEach(value -> httpExchange.getResponseHeaders().add(name, value)));52 httpExchange.sendResponseHeaders(res.getStatus(), 0);53 try (InputStream in = res.getContent().get();54 OutputStream out = httpExchange.getResponseBody()) {55 ByteStreams.copy(in, out);...

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1public int getPort() {2 return getInt("port");3}4public String getHost() {5 return getString("host");6}7public URL getServerUrl() {8 try {9 return new URL("http", getHost(), getPort(), "/");10 } catch (MalformedURLException e) {11 throw new RuntimeException(e);12 }13}14public Duration getTimeout() {15 return Duration.ofSeconds(getInt("timeout"));16}17public URL getGridServerUrl() {18 String url = getString("grid-url");19 try {20 return new URL(url);21 } catch (MalformedURLException e) {22 throw new RuntimeException(e);23 }24}25public Logger getLog() {26 return Logger.getLogger(getClass().getName());27}28public void printHelp() {29 HelpFormatter formatter = new HelpFormatter();30 formatter.printHelp("selenium-standalone", getHelp());31}32public void printVersion() {33 System.out.println("Selenium standalone server version: " + getClass().getPackage().getImplementationVersion());34}35public void printUsage() {36 HelpFormatter formatter = new HelpFormatter();37 formatter.printUsage(new PrintWriter(System.out), 80, "selenium-standalone", getOptions());38}39public void printHelpAndExit() {40 printHelp();41 System.exit(0);42}43public void printVersionAndExit() {44 printVersion();45 System.exit(0);46}47public void printUsageAndExit() {48 printUsage();49 System.exit(1);

Full Screen

Full Screen

getPort

Using AI Code Generation

copy

Full Screen

1 import org.openqa.selenium.grid.config.Config;2 import org.openqa.selenium.grid.config.ConfigException;3 import org.openqa.selenium.grid.server.BaseServerOptions;4 import org.openqa.selenium.grid.server.Server;5 import org.openqa.selenium.grid.server.ServerFlags;6 import org.openqa.selenium.grid.web.Routable;7 import org.openqa.selenium.net.PortProber;8 import org.openqa.selenium.remote.http.HttpHandler;9 import org.openqa.selenium.remote.http.HttpRequest;10 import org.openqa.selenium.remote.http.HttpResponse;11 import org.openqa.selenium.remote.http.Route;12 import org.openqa.selenium.remote.tracing.Tracer;13 import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;14 import org.openqa.selenium.remote.tracing.opentelemetry.config.OpenTelemetryConfiguration;15 import java.io.IOException;16 import java.net.URL;17 import java.util.Objects;18 import java.util.Optional;19 import java.util.logging.Logger;20 import static org.openqa.selenium.remote.http.Contents.asJson;21 import static org.openqa.selenium.remote.http.Contents.utf8String;22 import static org.openqa.selenium.remote.http.HttpMethod.GET;23 import static org.openqa.selenium.remote.http.HttpMethod.POST;24 import static org.openqa.selenium.remote.http.Route.combine;25 import static org.openqa.selenium.remote.http.Route.get;26 import static org.openqa.selenium.remote.http.Route.post;27 public class Main {28 private static final Logger LOG = Logger.getLogger(Main.class.getName());29 public static void main(String[] args) throws IOException {30 ServerFlags flags = new ServerFlags();31 flags.parse(args);

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