Java Code Examples

These java code examples uses a Gridlastic selenium grid V3 for browser execution, see V4 examples. The selenium grid hub endpoint, the video url and grid hub credentials are displayed after launching your Gridlastic grid.

Example for Selenium version 3.14

test.java

// NOTE: RUN THIS EXAMPLE AS A MAVEN PROJECT WITH THE HUB AND VIDEO URL PARAMETERS LIKE
// GOAL: test -Dhub=https://USERNAME:ACCESS_KEY@HUB_SUBDOMAIN.gridlastic.com/wd/hub -DvideoUrl=VIDEO_URL
// USERNAME:ACCESS_KEY@HUB_SUBDOMAIN and VIDEO_URL is found in the Gridlastic dashboard after you start your selenium grid.


package java_example;

import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.testng.ITestContext;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class test {

	private RemoteWebDriver driver;
	ITestContext myTestContext;

	@Parameters({ "browser-name", "platform-name", "browser-version", "hub","videoUrl", "record-video" })
	@BeforeMethod(alwaysRun = true)
	public void beforeMethod(String browser_name, String platform_name, String browser_version, String hub, String videoUrl, String record_video,ITestContext myTestContext) throws Exception {	


		//CHROME specifics
		if (browser_name.equalsIgnoreCase("chrome")){	
			ChromeOptions options = new ChromeOptions();
			options.setCapability("version", browser_version); 
			options.setCapability("platform", platform_name);
			if (!platform_name.equalsIgnoreCase("linux")){
			options.setCapability("platformName", "windows"); //required from selenium version 3.9.1 when testing with firefox or IE. Required when testing with Chrome 77+.
			}
			options.setCapability("video", record_video); // NOTE: case sensitive string, not boolean.


			// On Linux start-maximized does not expand browser window to max screen size. Always set a window size.
			if (platform_name.equalsIgnoreCase("linux")) {
				options.addArguments(Arrays.asList("--window-position=0,0"));
				options.addArguments(Arrays.asList("--window-size=1840,1080"));	// starting with Chrome version 83, use width of 1840 instead of 1920 to capture the entire webpage on video recording.
			} else {
				options.addArguments(Arrays.asList("--start-maximized"));
			}
			driver = new RemoteWebDriver(new URL(hub),options);
		} 



		//FIREFOX version 55+ specifics
		if (browser_name.equalsIgnoreCase("firefox")){
			FirefoxOptions options = new FirefoxOptions();
			options.setCapability("version", browser_version); 
			options.setCapability("platform", platform_name);
			if (!platform_name.equalsIgnoreCase("linux")){
			options.setCapability("platformName", "windows");
			}
			options.setCapability("video", record_video); 

			// Required to specify firefox binary location on Gridlastic grid nodes starting from selenium version 3.5.3+, see firefox documentation https://www.gridlastic.com/test-environments.html#firefox_testing				
			if (!browser_version.equalsIgnoreCase("latest")) {
			if (platform_name.equalsIgnoreCase("linux")){
				options.setBinary("/home/ubuntu/Downloads/firefox"+browser_version+"/firefox");
			} else {
				options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox"+browser_version+"\\firefox.exe");
			}	
			}			
			driver = new RemoteWebDriver(new URL(hub),options);
		}

		
		// INTERNER EXPLORER specifics
		if (browser_name.equalsIgnoreCase("internet explorer")) {
			InternetExplorerOptions options = new InternetExplorerOptions();
			options.setCapability("version", browser_version);
			options.setCapability("platform", platform_name);
			options.setCapability("platformName", "windows"); // required from selenium version 3.9.1 when testing with
																// firefox or IE. Required when testing with Chrome 77+.
			options.setCapability("video", record_video); // NOTE: case sensitive string, not boolean.

			driver = new RemoteWebDriver(new URL(hub), options);
		}
	
		
		// MICROSOFT EDGE specifics
		if (browser_name.equalsIgnoreCase("MicrosoftEdge")) {
			EdgeOptions options = new EdgeOptions();
			options.setCapability("version", browser_version);
			options.setCapability("platform", platform_name);
			options.setCapability("platformName", "windows"); // required from selenium version 3.9.1 when testing with
																// firefox or IE. Required when testing with Chrome 77+.
			options.setCapability("video", record_video); // NOTE: case sensitive string, not boolean.

			driver = new RemoteWebDriver(new URL(hub), options);
			driver.manage().window().maximize();
		}
		
		
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

		// On LINUX/FIREFOX the "driver.manage().window().maximize()" option does not expand browser window to max screen size. Always set a window size.
		if (platform_name.equalsIgnoreCase("linux") && browser_name.equalsIgnoreCase("firefox")) {
			driver.manage().window().setSize(new Dimension(1920, 1080));	
		}

  		// VIDEO URL
        if(record_video.equals("True")){
        myTestContext.setAttribute("video_url", videoUrl+"/play.html?" + ((RemoteWebDriver) driver).getSessionId()); 
        } else {
        myTestContext.removeAttribute("video_url");	
        }

	}

	@Parameters({"test-title"})  
	@Test
	   public void test_site(String test_title, ITestContext myTestContext) throws Exception  { 	
		driver.get("https://www.google.com/ncr");
		Thread.sleep(10000); //slow down for demo purposes
		WebElement element = driver.findElement(By.name("q"));
		element.sendKeys("webdriver");
		element.submit();
		Thread.sleep(5000); //slow down for demo purposes
	}

	@AfterMethod(alwaysRun = true)
	public void tearDown() throws Exception {
		driver.quit();
	}

}

testng.xml

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" thread-count="5">

	<listeners>
		<listener class-name="java_example.CustomListener" />
	</listeners>


	
	<!-- ******************************************** CHROME ***************************************************************************** -->
	<test name="Test chrome on windows 10">
		<parameter name="test-title" value="Test chrome on windows 10" />
		<parameter name="browser-name" value="chrome" />
		<parameter name="platform-name" value="WIN10" />
		<parameter name="browser-version" value="latest" />
		<parameter name="record-video" value="True" />
		<classes>
			<class name="java_example.test" />
		</classes>
	</test>
	 <test name="Test chrome on linux">
		<parameter name="test-title" value="Test chrome on linux" />
		<parameter name="browser-name" value="chrome" />
		<parameter name="platform-name" value="LINUX" />
		<parameter name="browser-version" value="latest" />
		<parameter name="record-video" value="True" />
		<classes>
			<class name="java_example.test" />
		</classes>
	</test>
	


	
	<!-- ******************************************** FIREFOX ***************************************************************************** -->
	<test name="Test firefox on windows 10">
		<parameter name="test-title" value="Test firefox on windows 10" />
		<parameter name="browser-name" value="firefox" />
		<parameter name="platform-name" value="WIN10" />
		<parameter name="browser-version" value="latest" />
		<parameter name="record-video" value="True" />
		<classes>
			<class name="java_example.test" />
		</classes>
	</test>
	 <test name="Test firefox on linux">
		<parameter name="test-title" value="Test firefox on linux" />
		<parameter name="browser-name" value="firefox" />
		<parameter name="platform-name" value="LINUX" />
		<parameter name="browser-version" value="latest" />
		<parameter name="record-video" value="True" />
		<classes>
			<class name="java_example.test" />
		</classes>
	</test>


  
	<!-- ******************************************** INTERNET EXPLORER ***************************************************************************** -->
	<test name="Test internet explorer on windows 10">
		<parameter name="test-title" value="Test internet explorer on windows 10" />
		<parameter name="browser-name" value="internet explorer" />
		<parameter name="platform-name" value="WIN10" />
		<parameter name="browser-version" value="11" />
		<parameter name="record-video" value="True" />
		<classes>
			<class name="java_example.test" />
		</classes>
	</test>


	
	<!-- ******************************************** MICROSOFT EDGE ***************************************************************************** -->
	 <test name="Test Microsoft Edge on windows 10">
		<parameter name="test-title" value="Test Microsoft Edge on windows 10" />
		<parameter name="browser-name" value="MicrosoftEdge" />
		<parameter name="platform-name" value="WIN10" />
		<parameter name="browser-version" value="latest" />
		<parameter name="record-video" value="True" />
		<classes>
			<class name="java_example.test" />
		</classes>
	</test>
	
</suite>

CustomListener.java

package java_example;


import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

public class CustomListener extends TestListenerAdapter{
    private int m_count = 0;
	 
    @Override
    public void onTestFailure(ITestResult tr) {  	
    System.out.println("******************** FAILURE: " + tr.getTestContext().getCurrentXmlTest().getParameter("test-title") + " " +tr.getTestContext().getCurrentXmlTest().getParameter("platform-name") + " TEST METHOD: "+tr.getMethod().getMethodName() +" REASON:"+tr.getThrowable().getMessage().substring(0, 30).trim()+"... VIDEO: "+tr.getTestContext().getAttribute("video_url"));
      
    }
	 
    @Override
    public void onTestSkipped(ITestResult tr) {
        log(tr.getName()+ "--Test method skipped\n");
    }
	 
    
    @Override
    public void onTestSuccess(ITestResult tr) {
    if(tr.getTestContext().getCurrentXmlTest().getParameter("record-video").equalsIgnoreCase("True")){
    System.out.println("SUCCESS: " + tr.getTestContext().getCurrentXmlTest().getParameter("test-title") + " TEST METHOD: "+tr.getMethod().getMethodName() +"... VIDEO: "+tr.getTestContext().getAttribute("video_url"));
    } else {
        System.out.println("SUCCESS: " + tr.getTestContext().getCurrentXmlTest().getParameter("test-title") + " TEST METHOD: "+tr.getMethod().getMethodName());
        }
    }
    
  	 
    private void log(String string) {
        System.out.print(string);
        if (++m_count % 40 == 0) {
	    System.out.println("");
        }
    }
    
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>selenium-grid-java-example</groupId>
	<artifactId>selenium-grid-java-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>32.0.0-jre</version>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>7.7.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>3.14.0</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>3.0.0-M4</version>
				<configuration>
					<suiteXmlFiles>
						<suiteXmlFile>${basedir}/src/test/java/java_example/testng.xml</suiteXmlFile>
					</suiteXmlFiles>
					<systemPropertyVariables>
						<hub>${hub}</hub>
						<videoUrl>${videoUrl}</videoUrl>
					</systemPropertyVariables>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

You can download this java TestNG code example as a maven project at Github.



Example for Selenium version 3.53-3.9.1

Selenium java TestNG Chrome and firefox Example

// NOTE: replace USERNAME:ACCESS_KEY@HUB_SUBDOMAIN and VIDEO_URL with your credentials found in the Gridlastic dashboard
// ALSO SEE https://github.com/Gridlastic/demo1 FOR JAVA TESTNG EXAMPLES WITH PARALLEL TEST EXECUTIONS

package java_example;

import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;


public class test {

	// VIDEO_URL set to like "https://s3-ap-southeast-2.amazonaws.com/b2729248-ak68-6948-a2y8-80e7479te16a/9ag7b09j-6a38-58w2-bb01-17qw724ce46t/play.html?".
	// Find this VIDEO_URL value in your Gridlastic dashboard.
	private static final String VIDEO_URL = null; 
	private RemoteWebDriver driver;

	@BeforeMethod(alwaysRun = true)
	public void beforeMethod() throws Exception {

		// Example test environment. NOTE: Gridlastic auto scaling requires all
		// these 3 environment variables in each request.
		// see test environments for capabilities to use https://www.gridlastic.com/test-environments.html
		String platform_name = "win10";
		String browser_name = "chrome";
		String browser_version = "119";

		// optional video recording
		String record_video = "True";

		DesiredCapabilities capabilities = new DesiredCapabilities();
		if (platform_name.equalsIgnoreCase("win10")) {
			capabilities.setPlatform(Platform.WIN10);
			capabilities.setCapability("platformName", "windows"); //required from selenium version 3.9.1 when testing with firefox or IE. Required when testing with Chrome 77+.
			}
		}
		if (platform_name.equalsIgnoreCase("linux")) {
			capabilities.setPlatform(Platform.LINUX);
		}
		capabilities.setBrowserName(browser_name);
		capabilities.setVersion(browser_version);

		// video record
		if (record_video.equalsIgnoreCase("True")) {
			capabilities.setCapability("video", "True"); // NOTE: "True" is a case sensitive string, not boolean.
		} else {
			capabilities.setCapability("video", "False"); // NOTE: "False" is a case sensitive string, not boolean.
		}
		
		//Chrome specifics
		if (browser_name.equalsIgnoreCase("chrome")){
			ChromeOptions options = new ChromeOptions();
			
			// On Linux start-maximized does not expand browser window to max screen size. Always set a window size and position.
			if (platform_name.equalsIgnoreCase("linux")) {
				options.addArguments(Arrays.asList("--window-position=0,0"));
				options.addArguments(Arrays.asList("--window-size=1840,1080"));	// starting with Chrome version 83, use width of 1840 instead of 1920 to capture the entire webpage on video recording.
				} else {
				options.addArguments(Arrays.asList("--start-maximized"));
				}
			capabilities.setCapability(ChromeOptions.CAPABILITY, options);
			} 
	

		//Firefox version 55+ specifics
		if (browser_name.equalsIgnoreCase("firefox")){
		FirefoxOptions ffOptions = new FirefoxOptions();
				
				// Required to specify firefox binary location on Gridlastic grid nodes starting from selenium version 3.5.3+, see firefox documentation https://www.gridlastic.com/test-environments.html#firefox_testing				
				 if (!browser_version.equalsIgnoreCase("latest")) {
				 if (platform_name.equalsIgnoreCase("linux")){
					 ffOptions.setBinary("/home/ubuntu/Downloads/firefox"+browser_version+"/firefox");
				 } else {
					 ffOptions.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox"+browser_version+"\\firefox.exe");
				 }	
				}				 
				capabilities.setCapability("moz:firefoxOptions", ffOptions);

		}
		
		
		//replace USERNAME:ACCESS_KEY@SUBDOMAIN with your credentials found in the Gridlastic dashboard
		driver = new RemoteWebDriver(new URL("https://USERNAME:ACCESS_KEY@HUB_SUBDOMAIN.gridlastic.com/wd/hub"),capabilities);
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		
		// On LINUX/FIREFOX the "driver.manage().window().maximize()" option does not expand browser window to max screen size. Always set a window size.
		if (platform_name.equalsIgnoreCase("linux") && browser_name.equalsIgnoreCase("firefox")) {
			driver.manage().window().setSize(new Dimension(1920, 1080));	
		}
        

		if (record_video.equalsIgnoreCase("True")) {
			System.out.println("Test Video: " + VIDEO_URL + ((RemoteWebDriver) driver).getSessionId());
		}
	}

	@Test(enabled = true)
	 public void test_site() throws Exception  { 	
        driver.get("https://www.google.com/ncr");
        Thread.sleep(10000); //slow down for demo purposes
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys("webdriver");
        element.submit();
        Thread.sleep(5000);
	}

	@AfterMethod(alwaysRun = true)
	public void tearDown() throws Exception {
		driver.quit();
	}

}

You can download this java TestNG code example as a maven project at Github.



Example for Selenium version below 3.53

Selenium java TestNG Chrome Example

// NOTE: replace USERNAME:ACCESS_KEY@HUB_SUBDOMAIN and VIDEO_URL with your credentials found in the Gridlastic dashboard
// ALSO SEE https://github.com/Gridlastic/demo1 FOR JAVA TESTNG EXAMPLES WITH PARALLEL TEST EXECUTIONS

package java_example;

import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class test {

	// VIDEO_URL set to like "https://s3-ap-southeast-2.amazonaws.com/b2729248-ak68-6948-a2y8-80e7479te16a/9ag7b09j-6a38-58w2-bb01-17qw724ce46t/play.html?".
	// Find this VIDEO_URL value in your Gridlastic dashboard.
	private static final String VIDEO_URL = null; 
	private RemoteWebDriver driver;

	@BeforeMethod(alwaysRun = true)
	public void beforeMethod() throws Exception {

		// Example test environment. NOTE: Gridlastic auto scaling requires all
		// these 3 environment variables in each request.
		// see test environments for capabilities to use https://www.gridlastic.com/test-environments.html
		String platform_name = "win10";
		String browser_name = "chrome";
		String browser_version = "119";

		// optional video recording
		String record_video = "True";

		DesiredCapabilities capabilities = new DesiredCapabilities();
		if (platform_name.equalsIgnoreCase("win10")) {
			capabilities.setPlatform(Platform.WIN10);
			capabilities.setCapability("platformName", "windows"); //required from selenium version 3.9.1 when testing with firefox or IE. Required when testing with Chrome 77+.
			}
		}
		if (platform_name.equalsIgnoreCase("linux")) {
			capabilities.setPlatform(Platform.LINUX);
		}
		capabilities.setBrowserName(browser_name);
		capabilities.setVersion(browser_version);

		// video record
		if (record_video.equalsIgnoreCase("True")) {
			capabilities.setCapability("video", "True"); // NOTE: "True" is a case sensitive string, not boolean.
		} else {
			capabilities.setCapability("video", "False"); // NOTE: "False" is a case sensitive string, not boolean.
		}
		
		//Chrome specifics
		if (browser_name.equalsIgnoreCase("chrome")){
			ChromeOptions options = new ChromeOptions();
			options.addArguments("disable-infobars"); // starting from Chrome 57 the info bar displays with "Chrome is being controlled by automated test software."
			// On Linux start-maximized does not expand browser window to max screen size. Always set a window size and position.
			if (platform_name.equalsIgnoreCase("linux")) {
				options.addArguments(Arrays.asList("--window-position=0,0"));
				options.addArguments(Arrays.asList("--window-size=1840,1080"));	// starting with Chrome version 83, use width of 1840 instead of 1920 to capture the entire webpage on video recording.
				} else {
				options.addArguments(Arrays.asList("--start-maximized"));
				}
			capabilities.setCapability(ChromeOptions.CAPABILITY, options);
			} 
		
		//Firefox specifics
		if (browser_name.equalsIgnoreCase("firefox")){
				// If you are using selenium 3 and test Firefox versions below version 48
				if(Integer.parseInt(browser_version)<48){
				capabilities.setCapability("marionette", false);
				}
		}
	
		//replace USERNAME:ACCESS_KEY@SUBDOMAIN with your credentials found in the Gridlastic dashboard
		driver = new RemoteWebDriver(new URL("https://USERNAME:ACCESS_KEY@HUB_SUBDOMAIN.gridlastic.com/wd/hub"),capabilities);
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		
		// On LINUX/FIREFOX the "driver.manage().window().maximize()" option does not expand browser window to max screen size. Always set a window size.
		if (platform_name.equalsIgnoreCase("linux") && browser_name.equalsIgnoreCase("firefox")) {
			driver.manage().window().setSize(new Dimension(1920, 1080));	
		}
        

		if (record_video.equalsIgnoreCase("True")) {
			System.out.println("Test Video: " + VIDEO_URL + ((RemoteWebDriver) driver).getSessionId());
		}
	}

	@Test(enabled = true)
	 public void test_site() throws Exception  { 	
        driver.get("https://www.google.com/ncr");
        Thread.sleep(10000); //slow down for demo purposes
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys("webdriver");
        element.submit();
        Thread.sleep(5000);
	}

	@AfterMethod(alwaysRun = true)
	public void tearDown() throws Exception {
		driver.quit();
	}

}



Java Selenium Proxy Example

Use a selenium proxy to route your tests via our hosted Squid proxy or use your own proxy locally to test behind firewall internal sites using Gridlastic Connect Proxy Setup.

String proxy_server = "hub_subdomain.gridlastic.com:8001"; // hosted Squid proxy on your selenium grid hub
//String proxy_server = "your_gridlastic_connect_subdomain.gridlastic.com:9999"; // An example Gridlastic Connect endpoint

org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(proxy_server).setFtpProxy(proxy_server).setSslProxy(proxy_server);
capabilities.setCapability(CapabilityType.PROXY, proxy)


NOTE: Gridlastic auto scaling requires all 3 test environment parameters platform, browser and browser version to be specified in each request in order to launch test nodes to fulfill test demand. Video recording is optional. See test environments for capabilities options.
It is important to ensure that "driver.quit()" is always called for proper test execution and creation of video recordings of failed tests.