下面列出了怎么用org.openqa.selenium.net.PortProber的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
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();
}
}
@Override
public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {
Require.nonNull("Session creation request", sessionRequest);
DriverService service = createService.apply(sessionRequest.getCapabilities());
try {
service.start();
PortProber.waitForPortUp(service.getUrl().getPort(), 30, SECONDS);
URL url = service.getUrl();
return performHandshake(
tracer,
service,
url,
sessionRequest.getDownstreamDialects(),
sessionRequest.getCapabilities());
} catch (IOException | IllegalStateException | NullPointerException | InvalidArgumentException e) {
log.log(Level.INFO, e.getMessage(), e);
service.stop();
return Optional.empty();
}
}
@Parameterized.Parameters(name = "EventBus {0}")
public static Collection<Supplier<EventBus>> buildEventBuses() {
return ImmutableSet.of(
() -> ZeroMqEventBus.create(
new ZContext(),
"inproc://bus-pub",
"inproc://bus-sub",
true),
() -> ZeroMqEventBus.create(
new ZContext(),
"tcp://*:" + PortProber.findFreePort(),
"tcp://*:" + PortProber.findFreePort(),
true),
() -> ZeroMqEventBus.create(
new ZContext(),
"tcp://localhost:" + PortProber.findFreePort(),
"tcp://localhost:" + PortProber.findFreePort(),
true),
GuavaEventBus::new);
}
@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);
}
}
@Override
protected void waitUntilAvailable() {
try {
PortProber.waitForPortUp(getUrl().getPort(), (int) getTimeout().toMillis(), MILLISECONDS);
} catch (RuntimeException e) {
throw new WebDriverException(e);
}
}
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);
}
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);
}
@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");
}
@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();
}
}
public int getPort() {
if (port == -1) {
int newPort = config.getInt(SERVER_SECTION, "port")
.orElseGet(PortProber::findFreePort);
if (newPort < 0) {
throw new ConfigException("Port cannot be less than 0: " + newPort);
}
port = newPort;
}
return port;
}
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));
}
@Override
public JettyServer start() {
try {
// If there are no routes, we've done something terribly wrong.
if (handler == null) {
throw new IllegalStateException("There must be at least one route specified");
}
servletContextHandler.addServlet(
new ServletHolder(new HttpHandlerServlet(handler.with(new WrapExceptions().andThen(new AddWebDriverSpecHeaders())))),
"/*");
server.start();
PortProber.waitForPortUp(getUrl().getPort(), 10, SECONDS);
return this;
} catch (Exception e) {
try {
stop();
} catch (Exception ignore) {
}
if (e instanceof BindException) {
LOG.severe(String.format(
"Port %s is busy, please choose a free port and specify it using -port option",
getUrl().getPort()));
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
}
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();
}
private URI createUri() {
try {
return new URI("http://localhost:" + PortProber.findFreePort());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
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);
}
/**
* There is a bug between an OkHttp client and the Netty server where a TCP
* RST causes the same HTTP request to be generated twice. This is clearly
* less than desirable behaviour, so this test attempts to ensure the problem
* does not occur. I suspect the problem is to do with OkHttp's connection
* pool, but it seems cruel to make our users deal with this. Better to have
* it be something the server handles.
*/
@Test
public void ensureMultipleCallsWorkAsExpected() {
System.out.println("\n\n\n\nNetty!");
AtomicInteger count = new AtomicInteger(0);
Server<?> server = new NettyServer(
new BaseServerOptions(
new MapConfig(
ImmutableMap.of("server", ImmutableMap.of("port", PortProber.findFreePort())))),
req -> {
count.incrementAndGet();
return new HttpResponse().setContent(utf8String("Count is " + count.get()));
}
).start();
// TODO: avoid using netty for this
HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl());
HttpResponse res = client.execute(new HttpRequest(GET, "/does-not-matter"));
outputHeaders(res);
assertThat(count.get()).isEqualTo(1);
client.execute(new HttpRequest(GET, "/does-not-matter"));
outputHeaders(res);
assertThat(count.get()).isEqualTo(2);
}
/**
* 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();
}
private static void foo() throws Exception {
boolean debug = Boolean.parseBoolean(System.getProperty("debug", "false"));
String dockerHost = String.format("http://%s:%d", CENTOS, 2375);
DockerClient docker = null;
try {
docker = DefaultDockerClient.builder()
.uri(dockerHost).build();
Info info = docker.info();
System.err.println("Information : " + info);
if (debug) {
docker.pull(SELENIUM_STANDALONE_CHROME, new LoggingBuildHandler());
} else {
docker.pull(SELENIUM_STANDALONE_CHROME);
}
final ImageInfo imageInfo = docker.inspectImage(SELENIUM_STANDALONE_CHROME);
System.err.println("Information : " + imageInfo);
// Bind container ports to host ports
// final String[] ports = {Integer.toString(PortProber.findFreePort())};
final String[] ports = {"4444"};
final Map<String, List<PortBinding>> portBindings = new HashMap<>();
for (String port : ports) {
List<PortBinding> hostPorts = new ArrayList<>();
hostPorts.add(PortBinding.of("0.0.0.0", PortProber.findFreePort()));
portBindings.put(port, hostPorts);
}
// // Bind container port 443 to an automatically allocated available host port.
// List<PortBinding> randomPort = new ArrayList<>();
// randomPort.add(PortBinding.randomPort("0.0.0.0"));
// portBindings.put("443", randomPort);
System.err.println("Printing the port mappings : " + portBindings);
final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();
final ContainerConfig containerConfig = ContainerConfig.builder()
.hostConfig(hostConfig)
.image(SELENIUM_STANDALONE_CHROME).exposedPorts(ports)
.build();
final ContainerCreation creation = docker.createContainer(containerConfig);
final String id = creation.id();
// Inspect container
final ContainerInfo containerInfo = docker.inspectContainer(id);
System.err.println("Container Information " + containerInfo);
String msg = "Checking to see if the container with id [" + id + "] and name [" +
containerInfo.name() + "]...";
System.err.println(msg);
if (! containerInfo.state().running()) {
// Start container
docker.startContainer(id);
System.err.println(containerInfo.name() + " is now running.");
} else {
System.err.println(containerInfo.name() + " was already running.");
}
System.err.println("Lets wait here !!!");
} finally {
if (docker != null) {
docker.close();
}
}
}
@Override
protected void waitUntilAvailable() {
PortProber.waitForPortUp(getUrl().getPort(), (int) getTimeout().toMillis(), MILLISECONDS);
}
private static int getHttpPort() {
return getEnvValue(FIXED_HTTP_PORT_ENV_NAME).orElseGet(PortProber::findFreePort);
}
private static int getHttpsPort() {
return getEnvValue(FIXED_HTTPS_PORT_ENV_NAME).orElseGet(PortProber::findFreePort);
}
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});
}
@BeforeClass
public static void startRedisServer() throws URISyntaxException {
uri = new URI("redis://localhost:" + PortProber.findFreePort());
server = RedisServer.builder().port(uri.getPort()).build();
server.start();
}
@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();
}
}
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 };
}
private BaseServerOptions defaultOptions() {
return new BaseServerOptions(new MapConfig(
ImmutableMap.of("server", ImmutableMap.of(
"port", PortProber.findFreePort()
))));
}
/**
* 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;
}