How to use PortProber class of org.openqa.selenium.net package

Best Selenium code snippet using org.openqa.selenium.net.PortProber

Source:TestServerUtils.java Github

copy

Full Screen

...13| the specific language governing permissions and limitations under the License. |14\*-------------------------------------------------------------------------------------------------------------------*/15package com.paypal.selion;16import org.openqa.selenium.net.NetworkUtils;17import org.openqa.selenium.net.PortProber;18import org.seleniumhq.jetty9.server.Server;19import org.seleniumhq.jetty9.server.handler.ResourceHandler;20import com.paypal.selion.configuration.Config;21import com.paypal.selion.configuration.Config.ConfigProperty;22import com.paypal.selion.logger.SeLionLogger;23public class TestServerUtils {24 public static final String TEST_PAGE_DIR = "src/test/resources/testPages";25 private static final String DATE_PICKER_FILE = "/datePicker.html";26 private static final String CONTAINER_FILE = "/ContainerTest.html";27 private static final String TEST_EDITABLE_FILE = "/test_editable.html";28 29 private static final int[] sauceConnectPorts = { 2000, 2001, 2020, 2109, 2222, 2310, 3000, 3001, 3030, 3210, 3333, 4000,30 4001, 4040, 4321, 4502, 4503, 4567, 5000, 5001, 5050, 5432, 6000, 6001, 6060, 6666, 6543, 7000, 7070,31 7774, 7777, 8000, 8001, 8003, 8031, 8080, 8081, 8765, 8777, 8888, 9000, 9001, 9080, 9090, 9876, 9877, 9999,32 49221, 55001 };33 private static final int lowerBoundConnectPort = 10000;34 private static final int upperBoundConnectPort = 14000;35 private static int serverPort;36 private static String localIP;37 private static Server server;38 private static void createServer() {39 if (! Config.getBoolConfigProperty(ConfigProperty.SELENIUM_USE_SAUCELAB_GRID)) {40 for (int port = lowerBoundConnectPort; port <= upperBoundConnectPort; port++) {41 if (PortProber.pollPort(port)) {42 serverPort = port;43 break;44 }45 }46 }47 else {48 //use a port Sauce Connect can reach49 for (int port : sauceConnectPorts) {50 if (PortProber.pollPort(port)) {51 serverPort = port;52 break;53 }54 }55 }56 //last hope, any free port will have to do57 if (serverPort == 0) {58 serverPort = PortProber.findFreePort();59 }60 localIP = new NetworkUtils().getIp4NonLoopbackAddressOfThisMachine().getHostAddress();61 initServer();62 }63 private static void initServer() {64 server = new Server(serverPort);65 ResourceHandler handler = new ResourceHandler();66 handler.setDirectoriesListed(true);67 handler.setResourceBase(TEST_PAGE_DIR);68 server.setHandler(handler);69 }70 public static void startServer() throws Exception {71 if (server == null) {72 createServer();...

Full Screen

Full Screen

Source:AppTest.java Github

copy

Full Screen

...9import org.openqa.selenium.WebDriver;10import org.openqa.selenium.WebElement;11import org.openqa.selenium.chrome.ChromeDriver;12import org.openqa.selenium.chrome.ChromeOptions;13import org.openqa.selenium.net.PortProber;14// observed exception in setup:15// java.lang.NoClassDefFoundError: Could not initialize class org.openqa.selenium.net.PortProber16// Exception in thread "main" java.lang.NoSuchMethodError: java.io.FileReader.<init>(Ljava/io/File;Ljava/nio/charset/Charset;)V17// https://www.programcreek.com/java-api-examples/?api=org.openqa.selenium.net.PortProber18// https://github.com/SeleniumHQ/selenium/issues/708919import java.io.File;20import java.util.ArrayList;21import java.util.HashMap;22import java.util.List;23import java.util.Map;24import java.util.concurrent.TimeUnit;25public class AppTest {26 private WebDriver driver;27 private static final String chromeDriverPath = System.getProperty("user.home") + "/Downloads/" + "chromedriver";28 private static String url = "http://www.juliodelima.com.br/taskit";29 private static final List<String> plugins_disabled = new ArrayList<>();30 static {31 plugins_disabled.add("Chrome PDF Viewer");32 };33 private static final String downloadDirectory = System.getenv("DOWNLOAD_DIRECTORY");34 private static Map<String, Object> prefs = new HashMap<>();35 static {36 prefs.put("profile.default_content_settings.popups", 0);37 prefs.put("download.default_directory", downloadDirectory != null ? downloadDirectory : "/tmp");38 prefs.put("download.prompt_for_download", false);39 prefs.put("download.directory_upgrade", true);40 prefs.put("safebrowsing.enabled", false);41 prefs.put("plugins.always_open_pdf_externally", true);42 prefs.put("plugins.plugins_disabled", plugins_disabled);43 };44 @Before45 public void setUp() {46 // Open the visual driver47 System.setProperty("webdriver.chrome.driver", chromeDriverPath);48 ChromeOptions chromeOptions = new ChromeOptions();49 chromeOptions.setExperimentalOption("prefs", prefs);50 PortProber.findFreePort();51 driver = new ChromeDriver(chromeOptions);52 driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);53 }54 @Test55 public void downloadPDF() {56 url = "http://www.africau.edu/images/default/sample.pdf";57 driver.get(url);58 try {59 Thread.sleep(5000);60 } catch (InterruptedException e) {61 }62 String downloadDirectoryUsed = downloadDirectory != null ? downloadDirectory : "/tmp";63 File file = new File(downloadDirectoryUsed + "/" + "sample.pdf");64 assertThat("download file expected to exist", file.exists(), is(true));...

Full Screen

Full Screen

Source:App.java Github

copy

Full Screen

...10import java.util.HashMap;11import java.util.List;12import java.util.Map;13import java.util.concurrent.TimeUnit;14import org.openqa.selenium.net.PortProber;15public class App {16 private static WebDriver driver;17 private static final String chromeDriverPath = System.getProperty("chromeDriverPath",18 Paths.get(System.getProperty("user.home")).resolve("Downloads").resolve("chromedriver").toAbsolutePath()19 .toString());20 private static String url = null;21 private static final List<String> plugins_disabled = new ArrayList<>();22 static {23 plugins_disabled.add("Chrome PDF Viewer");24 };25 private static Map<String, Object> prefs = new HashMap<>();26 private static final String downloadDirectory = System.getenv("DOWNLOAD_DIRECTORY");27 static {28 prefs.put("profile.default_content_settings.popups", 0);29 prefs.put("download.default_directory", downloadDirectory != null ? downloadDirectory : "/tmp");30 prefs.put("download.prompt_for_download", false);31 prefs.put("download.directory_upgrade", true);32 prefs.put("safebrowsing.enabled", false);33 prefs.put("plugins.always_open_pdf_externally", true);34 prefs.put("plugins.plugins_disabled", plugins_disabled);35 };36 public static void main(String[] args) throws InterruptedException, IOException {37 System.setProperty("webdriver.chrome.driver", chromeDriverPath);38 ChromeOptions chromeOptions = new ChromeOptions();39 for (String optionAgrument : (new String[] { "--headless", "--window-size=1200x800", "--no-sandbox",40 "--remote-debugging-address=0.0.0.0", "--remote-debugging-port=9222", "--disable-gpu" })) {41 chromeOptions.addArguments(optionAgrument);42 }43 chromeOptions.setExperimentalOption("prefs", prefs);44 driver = new ChromeDriver(chromeOptions);45 // add code that was failing in JDK 846 // the exception cannot be handled without upgrading47 // Exception in thread "main" java.lang.NoSuchMethodError: java.io.FileReader.<init>(Ljava/io/File;Ljava/nio/charset/Charset;)V48 // at org.openqa.selenium.net.LinuxEphemeralPortRangeDetector.getInstance(LinuxEphemeralPortRangeDetector.java:36)49 // at org.openqa.selenium.net.PortProber.<clinit>(PortProber.java:42)50 try {51 int port = PortProber.findFreePort() ;52 System.err.println("PortProber findFreePort -> " + port);53 } catch (Exception e){54 System.err.println("Exception: " + e.toString());55 }56 driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);57 url = "http://www.juliodelima.com.br/taskit";58 driver.get(url);59 driver.findElement(By.linkText("Sign in")).click();60 WebElement formSignInBox = driver.findElement(By.id("signinbox"));61 formSignInBox.findElement(By.name("login")).sendKeys("julio0001");62 formSignInBox.findElement(By.name("password")).sendKeys("123456");63 driver.findElement(By.linkText("SIGN IN")).click();64 WebElement me = driver.findElement(By.className("me"));65 String text = me.getText();66 System.err.println(text);...

Full Screen

Full Screen

Source:SelendroidJarSpawnerTest.java Github

copy

Full Screen

...15package com.paypal.selion.grid;16import static org.testng.Assert.assertFalse;17import static org.testng.Assert.fail;18import org.openqa.selenium.net.NetworkUtils;19import org.openqa.selenium.net.PortProber;20import org.testng.annotations.BeforeClass;21import org.testng.annotations.Test;22@Test(singleThreaded = true, groups = { "android-only", "downloads-dependencies" })23public class SelendroidJarSpawnerTest {24 private Thread thread;25 private RunnableLauncher spawner;26 @BeforeClass27 public void beforeClass() {28 String host = new NetworkUtils().getIpOfLoopBackIp4();29 int port = PortProber.findFreePort();30 spawner = new SelendroidJarSpawner(new String[] { "-host", host, "-port", String.valueOf(port) },31 new ProcessLauncherConfiguration().setContinuouslyRestart(false).setIncludeJavaSystemProperties(false)32 .setIncludeParentProcessClassPath(false));33 thread = new Thread(spawner);34 }35 @Test36 public void testStartServer() throws Exception {37 thread.start();38 // wait for it to start, max 120 seconds39 int attempts = 0;40 while (!spawner.isRunning() && (attempts < 12)) {41 Thread.sleep(10000);42 attempts += 1;43 }...

Full Screen

Full Screen

Source:IOSDriverJarSpawnerTest.java Github

copy

Full Screen

...15package com.paypal.selion.grid;16import static org.testng.Assert.assertFalse;17import static org.testng.Assert.fail;18import org.openqa.selenium.net.NetworkUtils;19import org.openqa.selenium.net.PortProber;20import org.testng.annotations.BeforeClass;21import org.testng.annotations.Test;22@Test(singleThreaded = true, groups = { "ios-only", "downloads-dependencies" })23public class IOSDriverJarSpawnerTest {24 private Thread thread;25 private RunnableLauncher spawner;26 @BeforeClass27 public void beforeClass() {28 String host = new NetworkUtils().getIpOfLoopBackIp4();29 int port = PortProber.findFreePort();30 spawner = new IOSDriverJarSpawner(new String[] { "-host", host, "-port", String.valueOf(port) },31 new ProcessLauncherConfiguration().setContinuouslyRestart(false).setIncludeJavaSystemProperties(false)32 .setIncludeParentProcessClassPath(false));33 thread = new Thread(spawner);34 }35 @Test36 public void testStartServer() throws Exception {37 thread.start();38 // wait for it to start, max 120 seconds39 int attempts = 0;40 while (!spawner.isRunning() && (attempts < 12)) {41 Thread.sleep(10000);42 attempts += 1;43 }...

Full Screen

Full Screen

Source:SeleniumServerStarter.java Github

copy

Full Screen

...7import java.io.IOException;89import org.openqa.selenium.Build;10import org.openqa.selenium.os.CommandLine;11import org.openqa.selenium.net.PortProber;12import org.openqa.selenium.net.NetworkUtils;1314import static java.util.concurrent.TimeUnit.*;15import static org.openqa.selenium.TestWaiter.waitFor;16import static org.openqa.selenium.net.PortProber.freeLocalPort;17import static org.openqa.selenium.net.PortProber.pollPort;1819@SuppressWarnings({"UnusedDeclaration"})20public class SeleniumServerStarter extends TestSetup {2122 private static final NetworkUtils networkUtils = new NetworkUtils();23 private static final String SELENIUM_JAR = "build/java/server/test/org/openqa/selenium/server-with-tests-standalone.jar";24 private CommandLine command;2526 public SeleniumServerStarter(Test test) {27 super(test);28 }2930 @Override31 protected void setUp() throws Exception {32 // Walk up the path until we find the "third_party/selenium" directory33 File seleniumJar = findSeleniumJar();3435 if (!seleniumJar.exists()) {36 new Build().of("//java/server/test/org/openqa/selenium:server-with-tests:uber").go();37 if (!seleniumJar.exists()) {38 throw new IllegalStateException("Cannot locate selenium jar");39 }40 }4142 String port = startSeleniumServer(seleniumJar);4344 // Wait until the server process is running (port 4444)45 if (!pollPort(Integer.valueOf(port))) {46 throw new RuntimeException("Unable to start selenium server");47 }4849 super.setUp();50 }5152 @SuppressWarnings({"UseOfSystemOutOrSystemErr"})53 private String startSeleniumServer(File seleniumJar) throws IOException {5455 final String port = getPortString();56 command = new CommandLine("java", "-jar", seleniumJar.getAbsolutePath(), "-port", port);57 if (Boolean.getBoolean("webdriver.debug")) {58 command.copyOutputTo(System.err);59 }60 command.executeAsync();6162 PortProber.pollPort(getPort(port));6364 return port;65 }6667 private int getPort(String portString) {68 return Integer.parseInt(portString);69 }7071 private String getPortString() {72 return System.getProperty("webdriver.selenium.server.port", "5555");73 }7475 private File findSeleniumJar() {76 File dir = new File("."); ...

Full Screen

Full Screen

Source:SeleniumServerInstance.java Github

copy

Full Screen

2import java.net.MalformedURLException;3import java.net.URL;4import java.util.Map;5import com.google.common.collect.Maps;6import org.openqa.selenium.net.PortProber;7import org.openqa.selenium.remote.DesiredCapabilities;8import org.openqa.selenium.remote.HttpRequest;9import org.openqa.selenium.server.RemoteControlConfiguration;10import org.openqa.selenium.server.SeleniumServer;11import static org.openqa.selenium.DevMode.isInDevMode;12import static org.openqa.selenium.net.PortProber.pollPort;13public class SeleniumServerInstance {14 private SeleniumServer seleniumServer;15 private int serverPort;16 public void start() throws Exception {17 serverPort = PortProber.findFreePort();18 RemoteControlConfiguration config = new RemoteControlConfiguration();19 config.setPort(serverPort);20 seleniumServer = new SeleniumServer(config);21 seleniumServer.boot();22 23 pollPort(serverPort);24 25 if (isInDevMode()) {26 Map<String, Object> payload = Maps.newHashMap();27 payload.put("capabilities", DesiredCapabilities.firefox());28 payload.put("class", "org.openqa.selenium.firefox.FirefoxDriverTestSuite$TestFirefoxDriver");29 HttpRequest request = new HttpRequest(30 HttpRequest.Method.POST, 31 String.format("http://localhost:%d/wd/hub/config/drivers", serverPort),...

Full Screen

Full Screen

Source:FreeportProber.java Github

copy

Full Screen

2import lombok.Getter;3import lombok.RequiredArgsConstructor;4import lombok.extern.slf4j.Slf4j;5import org.junit.rules.ExternalResource;6import org.openqa.selenium.net.PortProber;7@RequiredArgsConstructor8@Slf4j9public class FreeportProber extends ExternalResource {10 @Getter11 private int port;12 @Override13 protected void before() throws Throwable {14 port=PortProber.findFreePort();15 log.info("found free port: {}",port);16 }17}...

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.

Most used methods in PortProber

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