Java Code Examples for org.openqa.selenium.net.PortProber#findFreePort()
The following examples show how to use
org.openqa.selenium.net.PortProber#findFreePort() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DriverService.java From selenium with Apache License 2.0 | 6 votes |
/** * Creates a new service to manage the driver server. Before creating a new service, the * builder will find a port for the server to listen to. * * @return The new service object. */ public DS build() { if (port == 0) { port = PortProber.findFreePort(); } if (exe == null) { exe = findDefaultExecutable(); } if (timeout == null) { timeout = getDefaultTimeout(); } List<String> args = createArgs(); DS service = createDriverService(exe, port, timeout, args, environment); port = 0; // reset port to allow reusing this builder return service; }
Example 2
Source File: HttpClientTestBase.java From selenium with Apache License 2.0 | 6 votes |
private HttpResponse executeWithinServer(HttpRequest request, HttpServlet servlet) throws Exception { Server server = new Server(PortProber.findFreePort()); ServletContextHandler handler = new ServletContextHandler(); handler.setContextPath(""); ServletHolder holder = new ServletHolder(servlet); handler.addServlet(holder, "/*"); server.setHandler(handler); server.start(); try { HttpClient client = createFactory().createClient(fromUri(server.getURI())); return client.execute(request); } finally { server.stop(); } }
Example 3
Source File: ReferrerTest.java From selenium with Apache License 2.0 | 5 votes |
ServerResource() { this.server = new Server(); ServerConnector http = new ServerConnector(server); int port = PortProber.findFreePort(); http.setPort(port); http.setIdleTimeout(500000); this.server.addConnector(http); this.hostAndPort = HostAndPort.fromParts(JettyAppServer.detectHostname(), port); }
Example 4
Source File: JreAppServer.java From selenium with Apache License 2.0 | 5 votes |
public JreAppServer(HttpHandler handler) { Require.nonNull("Handler", handler); int port = PortProber.findFreePort(); server = new JreServer( new BaseServerOptions(new MapConfig(singletonMap("server", singletonMap("port", port)))), handler); }
Example 5
Source File: SafariDriverTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void canStartADriverUsingAService() throws IOException { removeDriver(); int port = PortProber.findFreePort(); service = new SafariDriverService.Builder().usingPort(port).build(); service.start(); driver2 = new SafariDriver(service); driver2.get(pages.xhtmlTestPage); assertThat(driver2.getTitle()).isEqualTo("XHTML Test Page"); }
Example 6
Source File: HttpClientTestBase.java From selenium with Apache License 2.0 | 5 votes |
@Test public void shouldAllowUrlsWithSchemesToBeUsed() throws Exception { Server server = new Server(PortProber.findFreePort()); ServletContextHandler handler = new ServletContextHandler(); handler.setContextPath(""); class Canned extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try (PrintWriter writer = resp.getWriter()) { writer.append("Hello, World!"); } } } ServletHolder holder = new ServletHolder(new Canned()); handler.addServlet(holder, "/*"); server.setHandler(handler); server.start(); try { // This is a terrible choice of URL HttpClient client = createFactory().createClient(new URL("http://example.com")); URI uri = server.getURI(); HttpRequest request = new HttpRequest( GET, String.format("http://%s:%s/hello", uri.getHost(), uri.getPort())); HttpResponse response = client.execute(request); assertThat(string(response)).isEqualTo("Hello, World!"); } finally { server.stop(); } }
Example 7
Source File: HTMLLauncher.java From selenium with Apache License 2.0 | 5 votes |
private URL determineSuiteUrl(String startURL, String suiteURL) throws IOException { if (suiteURL.startsWith("https://") || suiteURL.startsWith("http://")) { return verifySuiteUrl(new URL(suiteURL)); } // Is the suiteURL a file? Path path = Paths.get(suiteURL).toAbsolutePath(); if (Files.exists(path)) { // Not all drivers can read files from the disk, so we need to host the suite somewhere. int port = PortProber.findFreePort(); BaseServerOptions options = new BaseServerOptions( new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", port)))); Json json = new Json(); server = new JreServer( options, Route.prefix("/test") .to(Route.combine(new ResourceHandler(new PathResource(path.getParent())))) .fallbackTo(() -> new NoHandler(json))); PortProber.waitForPortUp(port, 15, SECONDS); URL serverUrl = server.getUrl(); return new URL(serverUrl.getProtocol(), serverUrl.getHost(), serverUrl.getPort(), "/tests/"); } // Well then, it must be a URL relative to whatever the browserUrl. Probe and find out. URL browser = new URL(startURL); return verifySuiteUrl(new URL(browser, suiteURL)); }
Example 8
Source File: JvmBasedSeleniumServer.java From just-ask with Apache License 2.0 | 5 votes |
@Override public int startServer(TestSession session) throws ServerException { port = PortProber.findFreePort(); String[] args = getArgs(port); if (LOG.isLoggable(Level.INFO)) { LOG.info(String.format("Spawning a Selenium server using the arguments [%s]", Arrays.toString(args))); } ProcessBuilder pb = new ProcessBuilder(getArgs(port)); try { this.process = pb.start(); return port; } catch (Exception e) { throw new ServerException(e.getMessage(), e); } }
Example 9
Source File: ReverseProxyHandlerTest.java From selenium with Apache License 2.0 | 5 votes |
public Server() throws IOException { int port = PortProber.findFreePort(); String address = new NetworkUtils().getPrivateLocalAddress(); url = new URL("http", address, port, "/ok"); server = HttpServer.create(new InetSocketAddress(address, port), 0); server.createContext("/ok", ex -> { lastRequest = new HttpRequest( HttpMethod.valueOf(ex.getRequestMethod()), ex.getRequestURI().getPath()); Headers headers = ex.getRequestHeaders(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { for (String value : entry.getValue()) { lastRequest.addHeader(entry.getKey().toLowerCase(), value); } } try (InputStream in = ex.getRequestBody()) { lastRequest.setContent(bytes(ByteStreams.toByteArray(in))); } byte[] payload = "I like cheese".getBytes(UTF_8); ex.sendResponseHeaders(HTTP_OK, payload.length); try (OutputStream out = ex.getResponseBody()) { out.write(payload); } }); server.start(); }
Example 10
Source File: DistributorTest.java From selenium with Apache License 2.0 | 5 votes |
private URI createUri() { try { return new URI("http://localhost:" + PortProber.findFreePort()); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
Example 11
Source File: TestPortFinder.java From googleads-java-lib with Apache License 2.0 | 5 votes |
/** * Checks out the next available unused port. Callers should send the returned port * back to {@link #releaseUnusedPort(int)} when it's no longer being used. * * @throws NoSuchElementException if no unused port is available. */ public synchronized int checkOutUnusedPort() { if (availablePorts == null) { return PortProber.findFreePort(); } else if (availablePorts.isEmpty()) { // All available ports are checked out. throw new NoSuchElementException("No unused ports are available"); } return availablePorts.pop(); }
Example 12
Source File: EndToEndTest.java From selenium with Apache License 2.0 | 5 votes |
private static Server<?> createServer(HttpHandler handler) { int port = PortProber.findFreePort(); return new NettyServer( new BaseServerOptions( new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", port)))), handler); }
Example 13
Source File: AbstractCapabilities.java From carina with Apache License 2.0 | 4 votes |
/** * Generate default default Carina FirefoxProfile. * * @return Firefox profile. */ // keep it public to be bale to get default and override on client layerI public FirefoxProfile getDefaultFirefoxProfile() { FirefoxProfile profile = new FirefoxProfile(); // update browser language String browserLang = Configuration.get(Parameter.BROWSER_LANGUAGE); if (!browserLang.isEmpty()) { LOGGER.info("Set Firefox lanaguage to: " + browserLang); profile.setPreference("intl.accept_languages", browserLang); } boolean generated = false; int newPort = 7055; int i = 100; while (!generated && (--i > 0)) { newPort = PortProber.findFreePort(); generated = firefoxPorts.add(newPort); } if (!generated) { newPort = 7055; } if (firefoxPorts.size() > 20) { firefoxPorts.remove(0); } profile.setPreference(FirefoxProfile.PORT_PREFERENCE, newPort); LOGGER.debug("FireFox profile will use '" + newPort + "' port number."); profile.setPreference("dom.max_chrome_script_run_time", 0); profile.setPreference("dom.max_script_run_time", 0); if (Configuration.getBoolean(Configuration.Parameter.AUTO_DOWNLOAD) && !(Configuration.isNull(Configuration.Parameter.AUTO_DOWNLOAD_APPS) || "".equals(Configuration.get(Configuration.Parameter.AUTO_DOWNLOAD_APPS)))) { profile.setPreference("browser.download.folderList", 2); profile.setPreference("browser.download.dir", getAutoDownloadFolderPath()); profile.setPreference("browser.helperApps.neverAsk.saveToDisk", Configuration.get(Configuration.Parameter.AUTO_DOWNLOAD_APPS)); profile.setPreference("browser.download.manager.showWhenStarting", false); profile.setPreference("browser.download.saveLinkAsFilenameTimeout", 1); profile.setPreference("pdfjs.disabled", true); profile.setPreference("plugin.scan.plid.all", false); profile.setPreference("plugin.scan.Acrobat", "99.0"); } else if (Configuration.getBoolean(Configuration.Parameter.AUTO_DOWNLOAD) && Configuration.isNull(Configuration.Parameter.AUTO_DOWNLOAD_APPS) || "".equals(Configuration.get(Configuration.Parameter.AUTO_DOWNLOAD_APPS))) { LOGGER.warn( "If you want to enable auto-download for FF please specify '" + Configuration.Parameter.AUTO_DOWNLOAD_APPS.getKey() + "' param"); } profile.setAcceptUntrustedCertificates(true); profile.setAssumeUntrustedCertificateIssuer(true); // TODO: implement support of custom args if any return profile; }
Example 14
Source File: EndToEndTest.java From selenium with Apache License 2.0 | 4 votes |
private static Object[] createRemotes() throws URISyntaxException { Tracer tracer = DefaultTestTracer.createTracer(); EventBus bus = ZeroMqEventBus.create( new ZContext(), "tcp://localhost:" + PortProber.findFreePort(), "tcp://localhost:" + PortProber.findFreePort(), true); LocalSessionMap localSessions = new LocalSessionMap(tracer, bus); HttpClient.Factory clientFactory = HttpClient.Factory.createDefault(); Server<?> sessionServer = createServer(localSessions); sessionServer.start(); HttpClient client = HttpClient.Factory.createDefault().createClient(sessionServer.getUrl()); SessionMap sessions = new RemoteSessionMap(tracer, client); LocalDistributor localDistributor = new LocalDistributor( tracer, bus, clientFactory, sessions, null); Server<?> distributorServer = createServer(localDistributor); distributorServer.start(); Distributor distributor = new RemoteDistributor( tracer, HttpClient.Factory.createDefault(), distributorServer.getUrl()); int port = PortProber.findFreePort(); URI nodeUri = new URI("http://localhost:" + port); LocalNode localNode = LocalNode.builder(tracer, bus, nodeUri, nodeUri, null) .add(CAPS, createFactory(nodeUri)) .build(); Server<?> nodeServer = new NettyServer( new BaseServerOptions( new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", port)))), localNode); nodeServer.start(); distributor.add(localNode); Router router = new Router(tracer, clientFactory, sessions, distributor); Server<?> routerServer = createServer(router); routerServer.start(); return new Object[] { routerServer, clientFactory }; }
Example 15
Source File: DistributedCdpTest.java From selenium with Apache License 2.0 | 4 votes |
@Test public void ensureBasicFunctionality() throws MalformedURLException, InterruptedException { Browser browser = Objects.requireNonNull(Browser.detect()); assumeThat(browser.supportsCdp()).isTrue(); int eventPublishPort = PortProber.findFreePort(); int eventSubscribePort = PortProber.findFreePort(); String[] eventBusFlags = new String[]{"--publish-events", "tcp://*:" + eventPublishPort, "--subscribe-events", "tcp://*:" + eventSubscribePort}; int eventBusPort = PortProber.findFreePort(); new EventBusCommand().configure( System.out, System.err, mergeArgs(eventBusFlags, "--port", "" + eventBusPort)).run(); waitUntilUp(eventBusPort); int sessionsPort = PortProber.findFreePort(); new SessionMapServer().configure( System.out, System.err, mergeArgs(eventBusFlags, "--bind-bus", "false", "--port", "" + sessionsPort)).run(); waitUntilUp(sessionsPort); int distributorPort = PortProber.findFreePort(); new DistributorServer().configure( System.out, System.err, mergeArgs(eventBusFlags, "--bind-bus", "false", "--port", "" + distributorPort, "-s", "http://localhost:" + sessionsPort)).run(); waitUntilUp(distributorPort); int routerPort = PortProber.findFreePort(); new RouterServer().configure( System.out, System.err, "--port", "" + routerPort, "-s", "http://localhost:" + sessionsPort, "-d", "http://localhost:" + distributorPort).run(); waitUntilUp(routerPort); int nodePort = PortProber.findFreePort(); new NodeServer().configure( System.out, System.err, mergeArgs(eventBusFlags, "--port", "" + nodePort, "-I", getBrowserShortName(), "--public-url", "http://localhost:" + routerPort)).run(); waitUntilUp(nodePort); HttpClient client = HttpClient.Factory.createDefault().createClient(new URL("http://localhost:" + routerPort)); new FluentWait<>(client).withTimeout(ofSeconds(10)).until(c -> { HttpResponse res = c.execute(new HttpRequest(GET, "/status")); if (!res.isSuccessful()) { return false; } Map<String, Object> value = Values.get(res, MAP_TYPE); if (value == null) { return false; } return Boolean.TRUE.equals(value.get("ready")); }); Server<?> server = new NettyServer( new BaseServerOptions(new MapConfig(ImmutableMap.of())), req -> new HttpResponse().setContent(Contents.utf8String("I like cheese"))) .start(); WebDriver driver = new RemoteWebDriver(new URL("http://localhost:" + routerPort), browser.getCapabilities()); driver = new Augmenter().augment(driver); CountDownLatch latch = new CountDownLatch(1); try (DevTools devTools = ((HasDevTools) driver).getDevTools()) { devTools.createSessionIfThereIsNotOne(); devTools.send(Page.enable()); devTools.addListener(Network.loadingFinished(), res -> latch.countDown()); devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty())); devTools.send(Page.navigate(server.getUrl().toString(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())); assertThat(latch.await(10, SECONDS)).isTrue(); } }
Example 16
Source File: RedisBackedSessionMapTest.java From selenium with Apache License 2.0 | 4 votes |
@BeforeClass public static void startRedisServer() throws URISyntaxException { uri = new URI("redis://localhost:" + PortProber.findFreePort()); server = RedisServer.builder().port(uri.getPort()).build(); server.start(); }
Example 17
Source File: JettyServer.java From selenium with Apache License 2.0 | 4 votes |
public JettyServer(BaseServerOptions options, HttpHandler handler) { this.handler = Require.nonNull("Handler", handler); int port = options.getPort() == 0 ? PortProber.findFreePort() : options.getPort(); String host = options.getHostname().orElseGet(() -> { try { return new NetworkUtils().getNonLoopbackAddressOfThisMachine(); } catch (WebDriverException ignored) { return "localhost"; } }); try { this.url = new URL("http", host, port, ""); } catch (MalformedURLException e) { throw new UncheckedIOException(e); } Log.setLog(new JavaUtilLog()); this.server = new org.eclipse.jetty.server.Server( new QueuedThreadPool(options.getMaxServerThreads())); this.servletContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY); ConstraintSecurityHandler securityHandler = (ConstraintSecurityHandler) servletContextHandler.getSecurityHandler(); Constraint disableTrace = new Constraint(); disableTrace.setName("Disable TRACE"); disableTrace.setAuthenticate(true); ConstraintMapping disableTraceMapping = new ConstraintMapping(); disableTraceMapping.setConstraint(disableTrace); disableTraceMapping.setMethod("TRACE"); disableTraceMapping.setPathSpec("/"); securityHandler.addConstraintMapping(disableTraceMapping); Constraint enableOther = new Constraint(); enableOther.setName("Enable everything but TRACE"); ConstraintMapping enableOtherMapping = new ConstraintMapping(); enableOtherMapping.setConstraint(enableOther); enableOtherMapping.setMethodOmissions(new String[]{"TRACE"}); enableOtherMapping.setPathSpec("/"); securityHandler.addConstraintMapping(enableOtherMapping); // Allow CORS: Whether the Selenium server should allow web browser connections from any host if (options.getAllowCORS()) { FilterHolder filterHolder = servletContextHandler.addFilter(CrossOriginFilter.class, "/*", EnumSet .of(DispatcherType.REQUEST)); filterHolder.setInitParameter("allowedMethods", "GET,POST,PUT,DELETE,HEAD"); // Warning user LOG.warning("You have enabled CORS requests from any host. " + "Be careful not to visit sites which could maliciously " + "try to start Selenium sessions on your machine"); } server.setHandler(servletContextHandler); HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setSecureScheme("https"); ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); options.getHostname().ifPresent(http::setHost); http.setPort(getUrl().getPort()); http.setIdleTimeout(500000); server.setConnectors(new Connector[]{http}); }