How to use getPath method of org.openqa.selenium.firefox.FirefoxBinary class

Best Selenium code snippet using org.openqa.selenium.firefox.FirefoxBinary.getPath

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package com.zel.market.crawler.downloader;
2
3import org.openqa.selenium.firefox.FirefoxBinary;
4import org.openqa.selenium.firefox.FirefoxDriver;
5import org.openqa.selenium.firefox.FirefoxOptions;
6import org.openqa.selenium.remote.CapabilityType;
7import org.openqa.selenium.remote.DesiredCapabilities;
8
9/**
10 * Description:
11 *
12 * @author csy
13 * @version 1.0.0
14 * @since 2021/3/27
15 */
16public class FirefoxDriverRequest extends SeleniumRequest {
17
18
19    @Override
20    public void init(boolean headless) {
21        String driverpath = this.getClass().getClassLoader().getResource("driver/geckodriver.exe").getPath();
22        System.setProperty("webdriver.gecko.driver", driverpath);
23
24        DesiredCapabilities cap = new DesiredCapabilities();
25        if (proxy != null) {
26            cap.setCapability(CapabilityType.PROXY, proxy);
27        }
28        cap.setAcceptInsecureCerts(true);
29
30        FirefoxBinary firefoxBinary = new FirefoxBinary();
31        if (headless) {
32            firefoxBinary.addCommandLineOptions("--headless");
33        }
34        firefoxBinary.addCommandLineOptions("--disable-web-security");
35        //firefoxBinary.addCommandLineOptions("");
36        FirefoxOptions firefoxOptions = new FirefoxOptions();
37        firefoxOptions.setBinary(firefoxBinary);
38        firefoxOptions.addCapabilities(cap);
39        synchronized (this) {
40            driver = new FirefoxDriver(firefoxOptions);
41        }
42        //((FirefoxDriver) driver).setLogLevel(Level.INFO);
43    }
44
45    @Override
46    public  String getHtml(String url)  {
47        driver.get(url);
48        String html = (String) ((FirefoxDriver) driver).executeScript("return document.documentElement.outerHTML");
49
50        return html;
51    }
52}
53
Full Screen
copy
1package com.ericsson.ei.config;
2
3import com.ericsson.ei.frontend.exception.OSNotSupportedException;
4import com.ericsson.ei.frontend.exception.PropertiesNotLoadedException;
5import com.google.common.io.Files;
6import org.apache.commons.lang3.SystemUtils;
7import org.openqa.selenium.firefox.FirefoxBinary;
8import org.openqa.selenium.firefox.FirefoxDriver;
9import org.openqa.selenium.firefox.FirefoxOptions;
10import org.openqa.selenium.firefox.FirefoxProfile;
11
12import org.slf4j.Logger;
13import org.slf4j.LoggerFactory;
14import org.apache.commons.io.FilenameUtils;
15import org.apache.commons.lang3.StringUtils;
16
17import java.util.Properties;
18
19import java.io.File;
20
21public class SeleniumConfig {
22    private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumConfig.class);
23
24    private static String propertiesPath = String.join(File.separator, "src", "functionaltest", "resources");
25    private static String propertiesFile = "functional-test.properties";
26
27    private static String firefoxBZip2FileUrlLinux = "";
28
29    private static File tempDownloadDirectory = Files.createTempDir();
30    private static FirefoxDriver driver;
31
32    public static FirefoxDriver initFirefoxDriver() throws PropertiesNotLoadedException, OSNotSupportedException {
33        if (driver != null) {
34            return driver;
35        }
36
37        FirefoxProfile firefoxProfile = new FirefoxProfile();
38        firefoxProfile.setPreference("browser.download.folderList", 2);
39        firefoxProfile.setPreference("browser.download.dir", tempDownloadDirectory.getPath());
40        firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/json");
41
42        FirefoxOptions firefoxOptions = new FirefoxOptions()
43                .setHeadless(true)
44                .setProfile(firefoxProfile);
45
46        boolean successfullyLoadedProperties = loadProperties();
47        if (!successfullyLoadedProperties) {
48            LOGGER.error("Properties was not properly loaded.");
49            throw new PropertiesNotLoadedException();
50        };
51
52        if (SystemUtils.IS_OS_LINUX) {
53            FirefoxBinary firefoxBinary = installFirefoxBinary();
54            firefoxOptions.setBinary(firefoxBinary);
55
56            System.setProperty("webdriver.gecko.driver", "src/functionaltest/resources/geckodriver");
57        } else if (SystemUtils.IS_OS_WINDOWS) {
58            System.setProperty("webdriver.gecko.driver", "src/functionaltest/resources/geckodriver.exe");
59        } else {
60            LOGGER.error(SystemUtils.OS_NAME + " currently not supported.");
61            throw new OSNotSupportedException();
62        }
63
64        driver = new FirefoxDriver(firefoxOptions);
65
66        //Make sure all firefox browsers are closed after all tests have finished
67        Runtime.getRuntime().addShutdownHook(new Thread(() -> driver.quit()));
68        return driver;
69    }
70
71    public static File getTempDownloadDirectory() {
72        return tempDownloadDirectory;
73    }
74
75    public static String getBaseUrl(int randomServerPort) {
76        return "http://localhost:" + randomServerPort;
77    }
78
79    private static FirefoxBinary installFirefoxBinary() {
80        String firefoxBZip2FileNameLinux = FilenameUtils.getName(firefoxBZip2FileUrlLinux);
81
82        String firefoxBZip2FilePath = String.join(
83                File.separator, tempDownloadDirectory.getPath(), firefoxBZip2FileNameLinux);
84        Utils.downloadFileFromUrlToDestination(firefoxBZip2FileUrlLinux, firefoxBZip2FilePath);
85        Utils.extractBZip2InDir(firefoxBZip2FilePath, tempDownloadDirectory.getPath());
86        File firefoxBinaryFilePath = new File(
87                String.join(File.separator, tempDownloadDirectory.getPath(), "firefox", "firefox"));
88        Utils.makeBinFileExecutable(firefoxBinaryFilePath);
89        FirefoxBinary firefoxBinary = new FirefoxBinary(firefoxBinaryFilePath);
90        return firefoxBinary;
91    }
92    private static boolean loadProperties() {
93        final String propertiesFilePath = String.join(File.separator, propertiesPath, propertiesFile);
94        final Properties properties = Utils.getProperties(propertiesFilePath);
95
96        firefoxBZip2FileUrlLinux = properties.getProperty("test.selenium.firefox.BZip2File.url.linux");
97
98        if (StringUtils.isEmpty(firefoxBZip2FileUrlLinux)) {
99            LOGGER.error("Failed to load properties, firefoxBZip2FileUrlLinux is not set.");
100            return false;
101        } else {
102            LOGGER.debug("Properties have been loaded.");
103            return true;
104        }
105    }
106}
107
Full Screen
copy
1package qa.TestBase;
2
3import java.io.FileInputStream;
4import java.io.FileNotFoundException;
5import java.io.IOException;
6import java.util.HashMap;
7import java.util.Properties;
8
9import org.openqa.selenium.WebDriver;
10import org.openqa.selenium.chrome.ChromeDriver;
11import org.openqa.selenium.chrome.ChromeOptions;
12import org.openqa.selenium.firefox.FirefoxBinary;
13import org.openqa.selenium.firefox.FirefoxDriver;
14import org.openqa.selenium.firefox.FirefoxOptions;
15import org.openqa.selenium.firefox.FirefoxProfile;
16import org.openqa.selenium.remote.DesiredCapabilities;
17import org.openqa.selenium.support.events.EventFiringWebDriver;
18
19import qa.Listners.EventHandler;
20import qa.Report.LogStatus;
21
22
23public class TestBase {
24	
25	public static WebDriver driver;
26	
27	private TestBase()
28	{
29		String browser=TestBase.get("Browser");
30		String headless=TestBase.get("HeadlessMode");
31		String imageDisable=TestBase.get("DisableImage");
32		if(browser.equalsIgnoreCase("chrome")|| browser.toUpperCase().contains("CHROME"))
33		{
34			try{
35				
36				System.setProperty("webdriver.chrome.driver",TestBase.getPath(browser));
37				ChromeOptions options=new ChromeOptions();
38				options.addArguments("--incognito");
39				if(imageDisable.equalsIgnoreCase("yes"))
40				{
41					TestBase.disableImg(options);
42				}
43				/*if(headless.equalsIgnoreCase("yes"))
44				{
45					new HeadlessMode().headless(options);
46				}*/
47				DesiredCapabilities capabilites=DesiredCapabilities.chrome();
48				capabilites.setCapability(ChromeOptions.CAPABILITY, options);
49				driver=new ChromeDriver(options);
50				
51				LogStatus.pass("Chrome drive launched with headless mode = "+headless.toUpperCase()+", Image Disable mode = "+imageDisable.toUpperCase());
52								
53			}
54			catch (Exception e)
55			{
56				e.printStackTrace();
57			}
58		}
59		else if (browser.equalsIgnoreCase("FF")|| browser.toUpperCase().contains("FIRE")) 
60		{
61			try
62			{
63				
64				System.setProperty("webdriver.gecko.driver",TestBase.getPath(browser));
65				FirefoxOptions FFoptions=new FirefoxOptions();
66				if(imageDisable.equalsIgnoreCase("yes"))
67				{
68					TestBase.disableImg(FFoptions);
69				}
70				if(headless.equalsIgnoreCase("yes"))
71				{
72					 TestBase.headless(FFoptions);
73				}
74				
75				driver=new FirefoxDriver(FFoptions);
76				
77				
78				LogStatus.pass("FF drive launched with headless mode = "+headless.toUpperCase()+", Image Disable mode = "+imageDisable.toUpperCase());
79				
80				
81			}
82			catch(Exception e)
83			{
84				e.printStackTrace();
85				LogStatus.fail(e);
86			}
87		}
88		
89	}
90	
91	//Function to read the property file and load into application
92	public static String get(String PropertyName)
93	{
94		String returnProperty="";
95		Properties property = new Properties();
96		try {
97			FileInputStream file =
98					new FileInputStream(System.getProperty("user.dir")+"//src//main//resources//TestRunDetails.properties");
99			property.load(file);
100			returnProperty=property.getProperty(PropertyName);
101			if(returnProperty==null)
102			{
103				throw new Exception("Property with name : "+PropertyName+" not found in "+System.getProperty("user.dir")+"\\src//main//resources//TestRunDetails.properties Please check again");
104			}
105		
106		} catch (FileNotFoundException e) {
107			e.printStackTrace();
108			System.out.println("File not found");
109		} catch (IOException e) {
110			e.printStackTrace();
111		} catch (Exception e) {
112			e.printStackTrace();
113		}
114		return returnProperty;
115	}
116
117// Function to set the browser executable
118	
119	public static String getPath(String browser) 
120	{
121		String OS=System.getProperty("os.name");
122		String driverPath=null;
123		if(OS.toUpperCase().contains("Windows"))
124		{
125			if(browser.toUpperCase().contains("CHROME"))
126			{
127				driverPath=".//src//main//resources//chromedriver.exe";
128			}
129			else if(browser.toUpperCase().contains("FF")||browser.toUpperCase().contains("FIRE"))
130			{
131				driverPath=".//src//main//resources//geckodriver.exe";
132				
133			}
134		}
135		else if(OS.toUpperCase().contains("MAC"))
136		{
137			if(browser.toUpperCase().contains("CHROME"))
138			{
139				driverPath=".//src//main//resources//chromedriver";
140			}
141			else if(browser.toUpperCase().contains("FF")||browser.toUpperCase().contains("FIRE"))
142			{
143				driverPath=".//src//main//resources//geckodriver";
144			}
145		}
146		else
147		{
148			if(browser.toUpperCase().contains("CHROME"))
149			{
150				driverPath="/home/deepak/Jars/chromedriver";
151			}
152			else if(browser.toUpperCase().contains("FF")||browser.toUpperCase().contains("FIRE"))
153			{
154				driverPath="home/deepak/Jars/geckodriver";
155			}
156		}
157		return driverPath;
158	}
159
160	// function to set up head less options
161	
162	public static void headless(ChromeOptions options)
163	{
164		options.addArguments("window-size=1400,800");
165		options.addArguments("headless");
166	}
167	//Configures FireFox to run in headless mode
168	public static void headless(FirefoxOptions options)
169	{
170		FirefoxBinary firefoxBinary=new FirefoxBinary();
171		firefoxBinary.addCommandLineOptions("--headless");
172		options.setBinary(firefoxBinary);
173	}
174	public static void disableImg(ChromeOptions options)
175	{
176		HashMap<String, Object> images=new HashMap<String, Object>();
177		images.put("images", 2);
178		HashMap<String, Object> pref=new HashMap<String, Object>();
179		pref.put("profile.default_content_setting_values", images);
180		options.setExperimentalOption("prefs", pref);
181	}
182	//disables images in Firefox browser
183	public static void disableImg(FirefoxOptions options)
184	{
185		FirefoxProfile profile=new FirefoxProfile();
186		profile.setPreference("permissions.default.image", 2);
187		options.setProfile(profile);
188		options.setCapability(FirefoxDriver.PROFILE, profile);
189	}
190	public static void initialize()
191	{
192		new TestBase();
193	}
194	//quits browser
195	public static void quit()
196	{
197		driver.quit();
198	}
199	//initializes WebDriver EventListner
200	public void EventHandlerInit()
201	{
202		EventFiringWebDriver eventHandle=new EventFiringWebDriver(driver);
203		EventHandler handler=new EventHandler();
204		eventHandle.register(handler);
205		driver=eventHandle;
206	}
207	
208
209}
210
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger getPath code on LambdaTest Cloud Grid

Execute automation tests with getPath on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie