Source:How to convert one enum to another enum in java?
System.setProperty("webdriver.chrome.driver", "/path/to/your/chrome/driver");
WebDriver driver = new ChromeDriver();
Best Selenium code snippet using org.openqa.selenium.Enum Architecture
Source:Utilities.java  
1/**2 * NoraUi is licensed under the license GNU AFFERO GENERAL PUBLIC LICENSE3 *4 * @author Nicolas HALLOUIN5 * @author Stéphane GRILLON6 */7package com.github.noraui.utils;89import java.util.Arrays;10import java.util.HashSet;11import java.util.List;12import java.util.Map;13import java.util.Map.Entry;14import java.util.Set;15import java.util.concurrent.TimeUnit;1617import org.ini4j.Ini;18import org.junit.Assert;19import org.openqa.selenium.By;20import org.openqa.selenium.WebDriver;21import org.openqa.selenium.WebElement;22import org.slf4j.Logger;2324import com.github.noraui.application.page.Page;25import com.github.noraui.application.page.Page.PageElement;26import com.github.noraui.browser.DriverFactory;27import com.github.noraui.log.annotation.Loggable;2829@Loggable30public class Utilities {3132    static Logger log;3334    /**35     * @param applicationKey36     *            is key of application37     * @param code38     *            is key of selector (CAUTION: if you use any % char. {@link String#format(String, Object...)})39     * @param args40     *            is list of args ({@link String#format(String, Object...)})41     * @return the selector42     */43    public static String getSelectorValue(String applicationKey, String code, Object... args) {44        String selector = "";45        log.debug("getLocator with this application key : {}", applicationKey);46        log.debug("getLocator with this locator file : {}", Context.iniFiles.get(applicationKey));47        final Ini ini = Context.iniFiles.get(applicationKey);4849        final Map<String, String> section = ini.get(code);50        if (section != null) {51            final Entry<String, String> entry = section.entrySet().iterator().next();52            selector = String.format(entry.getValue(), args);53        }54        return selector;55    }5657    /**58     * @param element59     *            is a PageElement60     * @param args61     *            is list of args ({@link String#format(String, Object...)})62     * @return the selector63     */64    public static String getLocatorValue(PageElement element, Object... args) {65        return getSelectorValue(element.getPage().getApplication(), element.getPage().getPageKey() + element.getKey(), args);66    }6768    /**69     * This method read a application descriptor file and return a {@link org.openqa.selenium.By} object (xpath, id, link ...).70     *71     * @param applicationKey72     *            Name of application. Each application has its fair description file.73     * @param code74     *            Name of element on the web Page.75     * @param args76     *            list of description (xpath, id, link ...) for code.77     * @return a {@link org.openqa.selenium.By} object (xpath, id, link ...)78     */79    public static By getLocator(String applicationKey, String code, Object... args) {80        By locator = null;81        log.debug("getLocator with this application key : {}", applicationKey);82        log.debug("getLocator with this code : {}", code);83        log.debug("getLocator with this locator file : {}", Context.iniFiles.get(applicationKey));84        final Ini ini = Context.iniFiles.get(applicationKey);85        final Map<String, String> section = ini.get(code);86        if (section != null) {87            final Entry<String, String> entry = section.entrySet().iterator().next();88            final String selector = String.format(entry.getValue(), args);89            if ("css".equals(entry.getKey())) {90                locator = By.cssSelector(selector);91            } else if ("link".equals(entry.getKey())) {92                locator = By.linkText(selector);93            } else if ("id".equals(entry.getKey())) {94                locator = By.id(selector);95            } else if ("name".equals(entry.getKey())) {96                locator = By.name(selector);97            } else if ("xpath".equals(entry.getKey())) {98                locator = By.xpath(selector);99            } else if ("class".equals(entry.getKey())) {100                locator = By.className(selector);101            } else {102                Assert.fail(entry.getKey() + " NOT implemented!");103            }104        } else {105            Assert.fail("[" + code + "] NOT implemented in ini file " + Context.iniFiles.get(applicationKey) + "!");106        }107        return locator;108    }109110    /**111     * This method read a application descriptor file and return a {@link org.openqa.selenium.By} object (xpath, id, link ...).112     *113     * @param page114     *            is target page115     * @param code116     *            Name of element on the web Page.117     * @param args118     *            list of description (xpath, id, link ...) for code.119     * @return a {@link org.openqa.selenium.By} object (xpath, id, link ...)120     */121    public static By getLocator(Page page, String code, Object... args) {122        return getLocator(page.getApplication(), page.getPageKey() + code, args);123    }124125    /**126     * This method read a application descriptor file and return a {@link org.openqa.selenium.By} object (xpath, id, link ...).127     *128     * @param element129     *            is PageElement find in page.130     * @param args131     *            list of description (xpath, id, link ...) for code.132     * @return a {@link org.openqa.selenium.By} object (xpath, id, link ...)133     */134    public static By getLocator(PageElement element, Object... args) {135        log.debug("getLocator [{}]", element.getPage().getApplication());136        log.debug("getLocator [{}]", element.getPage().getPageKey());137        log.debug("getLocator [{}]", element.getKey());138        return getLocator(element.getPage().getApplication(), element.getPage().getPageKey() + element.getKey(), args);139    }140141    /**142     * Find the first {@link WebElement} using the given method.143     * This method is affected by the 'implicit wait' times in force at the time of execution.144     * The findElement(..) invocation will return a matching row, or try again repeatedly until145     * the configured timeout is reached.146     *147     * @param webDriver148     *            instance of webDriver149     * @param applicationKey150     *            key of application151     * @param code152     *            Name of element on the web Page.153     * @param args154     *            can be a index i155     * @return the first {@link WebElement} using the given method156     */157    public static WebElement findElement(WebDriver webDriver, String applicationKey, String code, Object... args) {158        return webDriver.findElement(getLocator(applicationKey, code, args));159    }160161    /**162     * Find the first {@link WebElement} using the given method.163     * This method is affected by the 'implicit wait' times in force at the time of execution.164     * The findElement(..) invocation will return a matching row, or try again repeatedly until165     * the configured timeout is reached.166     *167     * @param page168     *            is target page169     * @param code170     *            Name of element on the web Page.171     * @param args172     *            can be a index i173     * @return the first {@link WebElement} using the given method174     */175    public static WebElement findElement(Page page, String code, Object... args) {176        return Context.getDriver().findElement(getLocator(page.getApplication(), page.getPageKey() + code, args));177    }178179    /**180     * Find the first {@link WebElement} using the given method.181     * This method is affected by the 'implicit wait' times in force at the time of execution.182     * The findElement(..) invocation will return a matching row, or try again repeatedly until183     * the configured timeout is reached.184     *185     * @param element186     *            is PageElement find in page.187     * @param args188     *            can be a index i189     * @return the first {@link WebElement} using the given method190     */191    public static WebElement findElement(PageElement element, Object... args) {192        return Context.getDriver().findElement(getLocator(element.getPage().getApplication(), element.getPage().getPageKey() + element.getKey(), args));193    }194195    /**196     * Set value to a variable (null is forbiden, so set default value).197     *198     * @param value199     *            is value setted if value is not null.200     * @param defValue201     *            is value setted if value is null.202     * @return a {link java.lang.String} with the value not null.203     */204    public static String setProperty(String value, String defValue) {205        if (value != null && !"".equals(value)) {206            return value;207        }208        return defValue;209    }210211    /**212     * Check if element present and get first one.213     *214     * @param element215     *            is {link org.openqa.selenium.By} find in page.216     * @return first {link org.openqa.selenium.WebElement} finded present element.217     */218    public static WebElement isElementPresentAndGetFirstOne(By element) {219220        final WebDriver webDriver = Context.getDriver();221222        webDriver.manage().timeouts().implicitlyWait(DriverFactory.IMPLICIT_WAIT * 2, TimeUnit.MICROSECONDS);223224        final List<WebElement> foundElements = webDriver.findElements(element);225        final boolean exists = !foundElements.isEmpty();226227        webDriver.manage().timeouts().implicitlyWait(DriverFactory.IMPLICIT_WAIT, TimeUnit.MICROSECONDS);228229        if (exists) {230            return foundElements.get(0);231        } else {232            return null;233        }234235    }236237    /**238     * Check if element {link org.openqa.selenium.By} is present.239     *240     * @param element241     *            is {link org.openqa.selenium.By} find in page.242     * @return a boolean with the result.243     */244    public static boolean isElementPresent(By element) {245        return isElementPresentAndGetFirstOne(element) != null;246    }247248    public enum OperatingSystem {249250        WINDOWS("windows", "windows", ".exe"), LINUX("linux", "linux", ""), MAC("mac", "mac", "");251252        private final String operatingSystemName;253        private final String operatingSystemDir;254        private final String suffixBinary;255256        OperatingSystem(String operatingSystemName, String operatingSystemDir, String suffixBinary) {257            this.operatingSystemName = operatingSystemName;258            this.operatingSystemDir = operatingSystemDir;259            this.suffixBinary = suffixBinary;260        }261262        public static OperatingSystem getOperatingSystem(String osName) {263            for (final OperatingSystem operatingSystemName : values()) {264                if (osName.toLowerCase().contains(operatingSystemName.getOperatingSystemName())) {265                    return operatingSystemName;266                }267            }268            throw new IllegalArgumentException("Unrecognised operating system name '" + osName + "'");269        }270271        public static Set<OperatingSystem> getCurrentOperatingSystemAsAHashSet() {272            final String currentOperatingSystemName = System.getProperties().getProperty("os.name");273274            final Set<OperatingSystem> listOfOperatingSystems = new HashSet<>();275            listOfOperatingSystems.add(getOperatingSystem(currentOperatingSystemName));276277            return listOfOperatingSystems;278        }279280        public static OperatingSystem getCurrentOperatingSystem() {281            final String currentOperatingSystemName = System.getProperties().getProperty("os.name");282            return getOperatingSystem(currentOperatingSystemName);283        }284285        public String getOperatingSystemName() {286            return operatingSystemName;287        }288289        public String getOperatingSystemDir() {290            return operatingSystemDir;291        }292293        public String getSuffixBinary() {294            return suffixBinary;295        }296297    }298299    public enum SystemArchitecture {300301        ARCHITECTURE_64_BIT("64bit"), ARCHITECTURE_32_BIT("32bit");302303        private final String systemArchitectureName;304        private static final SystemArchitecture defaultSystemArchitecture = ARCHITECTURE_32_BIT;305        private static List<String> architecture64bitNames = Arrays.asList("amd64", "x86_64");306307        SystemArchitecture(String systemArchitectureName) {308            this.systemArchitectureName = systemArchitectureName;309        }310311        public String getSystemArchitectureName() {312            return systemArchitectureName;313        }314315        public static SystemArchitecture getSystemArchitecture(String currentArchitecture) {316            SystemArchitecture result = defaultSystemArchitecture;317            if (architecture64bitNames.contains(currentArchitecture)) {318                result = ARCHITECTURE_64_BIT;319            }320            return result;321        }322323        public static SystemArchitecture getCurrentSystemArchitecture() {324            final String currentArchitecture = System.getProperties().getProperty("os.arch");325            log.info("os.arch: {}", currentArchitecture);326            return getSystemArchitecture(currentArchitecture);327        }328329    }330
...Source:BrowserFactory.java  
1package co.uk.gel.config;2import co.uk.gel.jira.config.AppConfig;3import co.uk.gel.jira.util.Debugger;4import com.gargoylesoftware.htmlunit.BrowserVersion;5import com.gargoylesoftware.htmlunit.SilentCssErrorHandler;6import com.gargoylesoftware.htmlunit.WebClient;7import org.junit.Assert;8import org.openqa.selenium.Dimension;9import org.openqa.selenium.Platform;10import org.openqa.selenium.Rotatable;11import org.openqa.selenium.WebDriver;12import org.openqa.selenium.chrome.ChromeDriver;13import org.openqa.selenium.chrome.ChromeOptions;14import org.openqa.selenium.edge.EdgeDriver;15import org.openqa.selenium.edge.EdgeOptions;16import org.openqa.selenium.firefox.FirefoxDriver;17import org.openqa.selenium.firefox.FirefoxOptions;18import org.openqa.selenium.firefox.FirefoxProfile;19import org.openqa.selenium.htmlunit.HtmlUnitDriver;20import org.openqa.selenium.ie.InternetExplorerDriver;21import org.openqa.selenium.logging.LogType;22import org.openqa.selenium.logging.LoggingPreferences;23import org.openqa.selenium.phantomjs.PhantomJSDriver;24import org.openqa.selenium.phantomjs.PhantomJSDriverService;25import org.openqa.selenium.remote.CapabilityType;26import org.openqa.selenium.remote.DesiredCapabilities;27import org.openqa.selenium.remote.RemoteWebDriver;28import org.openqa.selenium.safari.SafariDriver;29import io.github.bonigarcia.wdm.WebDriverManager;30import java.io.File;31import java.net.URL;32import java.util.Arrays;33import java.util.HashMap;34import java.util.concurrent.TimeUnit;35import java.util.logging.Level;36public class BrowserFactory {37    WebDriver driver;38    public WebDriver getDriver() {39        return getDriver(AppConfig.getDevice(), BrowserConfig.getBrowser(), true);40    }41    public WebDriver getDriver(String device, String browser,42                               boolean javascriptEnabled) {43        DeviceType deviceType = DeviceType.valueOf(device.toUpperCase());44        BrowserEnum browserEnum = BrowserEnum.valueOf(browser.toUpperCase());45        switch (deviceType) {46            case DESKTOP:47                switch (browserEnum) {48                    case CHROME:49                        WebDriverManager.chromedriver().clearPreferences();50                        WebDriverManager.chromedriver().setup();51                        driver = getChromeDriver(null, javascriptEnabled);52                        break;53                    case FIREFOX:54                        driver = getFirefoxDriver(null, javascriptEnabled);55                        break;56                    case SAFARI:57                        driver = getSafariDriver(null, javascriptEnabled);58                        break;59                    case EDGE:60                        WebDriverManager.edgedriver().clearPreferences();61                        WebDriverManager.edgedriver().forceDownload().setup();62                        driver = getEdge(null, javascriptEnabled);63                        break;64                    default:65                      Debugger.println("Invalid Browser information");66                        Assert.fail();67                        break;68                }69                break;70            default:71                Debugger.println("Invalid Browser information");72                break;73        }74        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);75        if (driver instanceof RemoteWebDriver) {76            ((RemoteWebDriver) driver).setLogLevel(Level.INFO);77        }78        if (AppConfig.device.equalsIgnoreCase("DESKTOP")) {79            driver.manage().window().maximize();80            return driver;81        }82        if (driver instanceof RemoteWebDriver && !(driver instanceof Rotatable)) {83            Dimension dim = new Dimension(480, 800);84            driver.manage().window().setSize(dim);85        }86        return driver;87    }88    private WebDriver getSafariDriver(Object object,89                                      boolean javascriptEnabled) {90        DesiredCapabilities safariCaps = DesiredCapabilities.safari();91        safariCaps.setCapability("safari.cleanSession", true);92        return new SafariDriver(safariCaps);93    }94    private WebDriver getFirefoxDriver(String userAgent,95                                       boolean javascriptEnabled) {96        String osName = System.getProperty("os.name");97        String osArchitecture = System.getProperty("os.arch");98        if (osName.toLowerCase().contains("windows")) {99            if (osArchitecture.contains("64")) {100                System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver.exe");101            } else {102                System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver-v0.23.0-win32.exe");103            }104        } else {105            if (osArchitecture.contains("64")) {106                System.setProperty("webdriver.gecko.driver", "drivers/geckodriver-v0.23.0-linux64");107            } else {108                System.setProperty("webdriver.gecko.driver", "drivers/geckodriver-v0.23.0-linux32");109            }110        }111        //FirefoxDriverService ffDriverService = FirefoxDriverService.CreateDefaultService(<driver path>);112        return new FirefoxDriver(getFirefoxOptions(userAgent, javascriptEnabled));113    }114    private FirefoxOptions getFirefoxOptions(String userAgent,115                                             boolean javascriptEnabled) {116        FirefoxProfile profile = new FirefoxProfile();117        profile.setAcceptUntrustedCertificates (true);118//			profile.setEnableNativeEvents(true);119        profile.shouldLoadNoFocusLib();120        profile.setAssumeUntrustedCertificateIssuer(true);121        profile.setPreference("javascript.enabled", javascriptEnabled);122        String downloadFilepath = System.getProperty("user.dir") + File.separator +"downloads"+File.separator;123        Debugger.println("PATH: "+downloadFilepath);124        try{125            File download_loc = new File(downloadFilepath);126            if(!download_loc.exists()){127                download_loc.mkdirs();128            }129            profile.setPreference("browser.download.folderList", 2);130            profile.setPreference("browser.download.folderList", 2);131            profile.setPreference("browser.download.dir",downloadFilepath);132            // profile.setPreference( "layout.css.devPixelsPerPx", "0.6" );133            profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/json, application/ris, participant_id/csv, image/png, application/pdf, participant_id/html, participant_id/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ");134            if (null != userAgent) {135                profile.setPreference("general.useragent.override", userAgent);136            }137        }catch(Exception exp){138            System.out.println("Exception in creating download directory..."+exp);139        }140        FirefoxOptions firefoxOptions = new FirefoxOptions();141        firefoxOptions.setProfile(profile);142        firefoxOptions.setCapability("marionette", true);143        return firefoxOptions;144    }145    private WebDriver getEdge(String userAgent, boolean javascriptEnabled) {146        EdgeOptions edgeOptions = getEdgeLocalOptions(userAgent,javascriptEnabled);147        return driver = new EdgeDriver(edgeOptions);148    }149    private EdgeOptions getEdgeLocalOptions(String userAgent, boolean javascriptEnabled) {150        EdgeOptions edgeLocalOptions = new EdgeOptions();151        edgeLocalOptions.setCapability("prefs", downloadPathSetup());152        return edgeLocalOptions;153    }154//    private ChromeOptions getChromeOptions(String userAgent,155//                                           boolean javascriptEnabled) {156//        ChromeOptions opts = new ChromeOptions();157//        opts.addArguments("--disable-gpu");158//        opts.addArguments("--whitelisted-ips");159//        opts.addArguments("--no-sandbox");160//        if (null != userAgent) {161//            opts.addArguments("user-agent=" + userAgent);162//        }163//        opts.setExperimentalOption("prefs", downloadPathSetup());164//        if (!javascriptEnabled) {165//            opts.addArguments("disable-javascript");166//        }167//        DesiredCapabilities capabilities = DesiredCapabilities.chrome();168//        capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);169//        capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));170//        opts.merge(capabilities);171//        return opts;172//    }173    private WebDriver getChromeDriver(String userAgent, boolean javascriptEnabled) {174        return new ChromeDriver(getChromeLocalOptions(userAgent, javascriptEnabled));175    }176    private ChromeOptions getChromeLocalOptions(String userAgent,177                                                boolean javascriptEnabled) {178        ChromeOptions chromeLocalOptions = new ChromeOptions();179        chromeLocalOptions.addArguments("--disable-gpu");180        chromeLocalOptions.addArguments("--no-sandbox");181//        chromeLocalOptions.addArguments("--whitelisted-ips");182        if (null != userAgent) {183            chromeLocalOptions.addArguments("user-agent=" + userAgent);184        }185        chromeLocalOptions.setExperimentalOption("prefs", downloadPathSetup());186        if (!javascriptEnabled) {187            chromeLocalOptions.addArguments("disable-javascript");188        }189        LoggingPreferences logPrefs = new LoggingPreferences();190        logPrefs.enable(LogType.PERFORMANCE, Level.ALL);191        chromeLocalOptions.setCapability("goog:loggingPrefs", logPrefs);192        return chromeLocalOptions;193    }194    private HashMap downloadPathSetup() {195        String downloadFilePath = System.getProperty("user.dir") + File.separator + "downloads" + File.separator;196        File location = new File(downloadFilePath);197        if (!location.exists()) {198            location.mkdirs();199        }200        HashMap<String, Object> pathPrefs = new HashMap<String, Object>();201        pathPrefs.put("profile.default_content_settings.popups", 0);202        pathPrefs.put("download.default_directory", downloadFilePath);203        return pathPrefs;204    }205}//end...Source:SystemSummaryPage.java  
1/*2 * #%L3 * share-po4 * %%5 * Copyright (C) 2005 - 2016 Alfresco Software Limited6 * %%7 * This file is part of the Alfresco software. 8 * If the software was purchased under a paid Alfresco license, the terms of 9 * the paid license agreement will prevail.  Otherwise, the software is 10 * provided under the following open source license terms:11 * 12 * Alfresco is free software: you can redistribute it and/or modify13 * it under the terms of the GNU Lesser General Public License as published by14 * the Free Software Foundation, either version 3 of the License, or15 * (at your option) any later version.16 * 17 * Alfresco is distributed in the hope that it will be useful,18 * but WITHOUT ANY WARRANTY; without even the implied warranty of19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the20 * GNU Lesser General Public License for more details.21 * 22 * You should have received a copy of the GNU Lesser General Public License23 * along with Alfresco. If not, see <http://www.gnu.org/licenses/>.24 * #L%25 */26package org.alfresco.po.share.systemsummary;27import java.util.ArrayList;28import java.util.List;29import org.alfresco.po.exception.PageOperationException;30import org.openqa.selenium.By;31import org.openqa.selenium.NoSuchElementException;32import org.openqa.selenium.WebElement;33/**34 * @author sergey.kardash on 4/14/14.35 */36@SuppressWarnings("unchecked")37public class SystemSummaryPage extends AdvancedAdminConsolePage38{39    public final By AUT_DIRECTORIES_HEAD = By.cssSelector("tbody>tr>th");40    public final By AUT_DIRECTORIES = By.cssSelector("tbody>tr>td");41    public static enum systemInformation {42        AlfreacoHome("//span[contains(text(), 'Alfresco Home:')]/.."),43        AlfreacoEdition("//span[contains(text(), 'Alfresco Edition:')]/.."),44        AlfreacoVersion("//span[contains(text(), 'Alfresco Version:')]/.."),45        JavaHome("//span[contains(text(), 'Java Home:')]/.."),46        JavaVersion("//span[contains(text(), 'Java Version:')]/.."),47        JavaVmVendor("//span[contains(text(), 'Java VM Vendor:')]/.."),48        OperatingSystem("//span[contains(text(), 'Operating System:')]/.."),49        Version("//span[text()='Version:']/.."),50        Architecture("//span[contains(text(), 'Architecture:')]/.."),51        FreeMemory("//span[contains(text(), 'Architecture:')]/.."),52        MaximumMemory("//span[contains(text(), 'Architecture:')]/.."),53        TotalMemory("//span[contains(text(), 'Architecture:')]/..");54        String get;55        systemInformation(String get){56            this.get = get;57        }58        public String get(){59            return get;60        }61    }62    public static enum fileSystems {63        CIFS("//span[contains(text(), 'CIFS:')]/.."),64        FTP("//span[contains(text(), 'FTP:')]/.."),65        NFS("//span[contains(text(), 'NFS:')]/.."),66        WebDAV("//span[contains(text(), 'WebDAV:')]/.."),67        SPP("//span[contains(text(), 'SPP:')]/..");68        String get;69        fileSystems(String get){70            this.get = get;71        }72        public String get(){73            return get;74        }75    }76    public static enum email {77        Inbound("//span[contains(text(), 'Inbound:')]/.."),78        IMAP("//span[contains(text(), 'IMAP:')]/..");79        String get;80        email(String get){81            this.get = get;82        }83        public String get(){84            return get;85        }86    }87    public static enum transformationServices {88        OpenOfficeDirect("//span[contains(text(), 'Office Suite:')]/.."),89        JODConverter("//span[contains(text(), 'JOD Converter:')]/.."),90        SWFTools("//span[contains(text(), 'SWF Tools:')]/.."),91        FFMpeg("//span[contains(text(), 'FFMpeg:')]/.."),92        ImageMagic("//span[contains(text(), 'ImageMagic:')]/..");93        String get;94        transformationServices(String get){95            this.get = get;96        }97        public String get(){98            return get;99        }100    }101    public static enum auditingServices {102        Audit("//span[contains(text(), 'Audit:')]/.."),103        CMISChangeLog("//span[contains(text(), 'CMIS Change Log:')]/.."),104        AlfrescoAccess("//span[contains(text(), 'Alfresco Access:')]/.."),105        Tagging("//span[contains(text(), 'Tagging:')]/.."),106        Sync("//span[contains(text(), 'Sync:')]/..");107        String get;108        auditingServices(String get){109            this.get = get;110        }111        public String get(){112            return get;113        }114    }115    public static enum indexingSubsystem {116        Solr("//span[contains(text(), 'Solr:')]/.."),117        Solr4("//span[contains(text(), 'Solr 4:')]/.."),118        Lucene("//span[contains(text(), 'Lucene:')]/.."),119        NoIndex("//span[contains(text(), 'No Index:')]/..");120        String get;121        indexingSubsystem(String get){122            this.get = get;123        }124        public String get(){125            return get;126        }127        public String getStatus(){128            return get+"/span/img/following-sibling::span";129        }130    }131    public static enum contentStores {132        StorePath("//span[contains(text(),'Store Path:')]/.."),133        SpaceUsed("//span[contains(text(), 'Space Used (MB):')]/.."),134        SpaceAvailable("//span[contains(text(), 'Space Available (MB):')]/..");135        String get;136        contentStores(String get){137            this.get = get;138        }139        public String get(){140            return get;141        }142    }143    public static enum repositoryClustering {144        Clustering("//span[contains(text(), 'Clustering:')]/.."),145        ClusterName("//span[contains(text(), 'Cluster Name:')]/.."),146        ClusterMembers("//span[contains(text(), 'Cluster Members:')]/..");147        String get;148        repositoryClustering(String get){149            this.get = get;150        }151        public String get(){152            return get;153        }154    }155    public static enum activitiesFeed {156        Feed("//span[contains(text(), 'Feed:')]/..");157        String get;158        activitiesFeed(String get){159            this.get = get;160        }161        public String get(){162            return get;163        }164    }165    public static enum modulePackages {166        CurrentlyInstalled("//span[contains(text(), 'Currently Installed:')]/.."),167        PreviouslyInstalled("//span[contains(text(), 'Previously Installed:')]/..");168        String get;169        modulePackages(String get){170            this.get = get;171        }172        public String get(){173            return get;174        }175    }176    public static enum usersAndGroups {177        Users("//span[contains(text(), 'Users:')]/.."),178        Groups("//span[contains(text(), 'Groups:')]/..");179        String get;180        usersAndGroups(String get){181            this.get = get;182        }183        public String get(){184            return get;185        }186    }187    /**188     * Gets header names of the Authentication Directories table189     *190     * @return names of Authentication Directories table header191     */192    public List<String> getAutHeadDirectories()193    {194        List<String> columnNames = new ArrayList<String>();195        try196        {197            List<WebElement> elements = driver.findElements(AUT_DIRECTORIES_HEAD);198            for (WebElement webElement : elements)199            {200                columnNames.add(webElement.getText());201            }202            return columnNames;203        }204        catch (NoSuchElementException nse)205        {206            throw new PageOperationException("Unable to find elements", nse);207        }208    }209    /**210     * Gets list of the Authentication Directories211     *212     * @return names of the Authentication Directories213     */214    public List<String> getAutDirectoriesNames()215    {216        List<String> columnNames = new ArrayList<String>();217        try218        {219            List<WebElement> elements = driver.findElements(AUT_DIRECTORIES);220            for (WebElement webElement : elements)221            {222                columnNames.add(webElement.getText());223            }224            return columnNames;225        }226        catch (NoSuchElementException nse)227        {228            throw new PageOperationException("Unable to find elements", nse);229        }230    }231}...Source:DriverProvider.java  
1package net.testaholic.core.driver;2//https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/3import io.appium.java_client.android.AndroidDriver;4import io.appium.java_client.android.AndroidElement;5import io.appium.java_client.ios.IOSDriver;6import io.appium.java_client.ios.IOSElement;7import net.testaholic.core.config.SeleniumConfig;8import net.testaholic.core.utils.OperatingSystem;9import org.openqa.selenium.Proxy;10import org.openqa.selenium.WebDriver;11import org.openqa.selenium.chrome.ChromeDriver;12import org.openqa.selenium.firefox.FirefoxDriver;13import org.openqa.selenium.ie.InternetExplorerDriver;14import org.openqa.selenium.opera.OperaDriver;15import org.openqa.selenium.phantomjs.PhantomJSDriver;16import org.openqa.selenium.remote.DesiredCapabilities;17import org.openqa.selenium.safari.SafariDriver;18import org.openqa.selenium.support.events.EventFiringWebDriver;19import java.io.File;20import java.io.IOException;21import java.util.List;22import static org.openqa.selenium.remote.CapabilityType.PROXY;23public enum DriverProvider implements DriverType {24    ANDROID {25        public WebDriver getDriverObject() {26            return new AndroidDriver<AndroidElement>(SeleniumConfig.getInstance().getDefinedCapabilities().getDesiredCapabilities());27        }28    },29    IOS {30        public WebDriver getDriverObject() {31            return new IOSDriver<IOSElement>(SeleniumConfig.getInstance().getDefinedCapabilities().getDesiredCapabilities());32        }33    },34    FIREFOX {35        public WebDriver getDriverObject() {36             validateFireFoxEnvironment();37            return new EventFiringWebDriver(new FirefoxDriver(SeleniumConfig.getInstance().getDefinedCapabilities().getDesiredCapabilities()));38        }39    },40    CHROME {41        public WebDriver getDriverObject() {42            String chromeBinaryPath = "";43            if (OperatingSystem.isWindowsOperatingSystem()) {44                switch (OperatingSystem.getSystemArchitecture()){45                    case X64:46                        chromeBinaryPath = "/chromedriver_win64/chromedriver.exe";47                        break;48                    case X86:49                        chromeBinaryPath = "/chromedriver_win32/chromedriver.exe";50                        break;51                    case X86_64:52                        chromeBinaryPath = "/chromedriver_win64/chromedriver.exe";53                        break;54                    default:55                        System.err.println("Could not determine architecture, defaulting to 32 bit driver.");56                        chromeBinaryPath = "/chromedriver_win32/chromedriver.exe";57                }58            } else if (OperatingSystem.isMacOperatingSystem()) {59                chromeBinaryPath = "/chromedriver_mac32/chromedriver";60                File chromedriver = new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath).getPath());61                // set application user permissions to 45562                chromedriver.setExecutable(true);63            } else if (OperatingSystem.isLinuxOperatingSystem()) {64                    switch (OperatingSystem.getSystemArchitecture()){65                        case X64:66                            chromeBinaryPath = "/chromedriver_linux64/chromedriver.exe";67                            break;68                        case X86:69                            chromeBinaryPath = "/chromedriver_linux32/chromedriver.exe";70                            break;71                        case X86_64:72                            chromeBinaryPath = "/chromedriver_linux64/chromedriver.exe";73                            break;74                        default:75                            System.err.println("Could not determine architecture, defaulting to 32 bit driver.");76                            chromeBinaryPath = "/chromedriver_linux32/chromedriver.exe";77                    }78                File chromedriver = new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath).getPath());79                // set application user permissions to 45580                chromedriver.setExecutable(true);81            }82            System.setProperty("webdriver.chrome.driver", new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath).getPath()).getPath());83            return new EventFiringWebDriver(new ChromeDriver(SeleniumConfig.getInstance().getDefinedCapabilities().getDesiredCapabilities()));84        }85    },86    IE {87        public WebDriver getDriverObject() {88            if(OperatingSystem.isLinuxOperatingSystem() || OperatingSystem.isMacOperatingSystem()){89                throw new RuntimeException("Unable to execute IE on linux or OSX");90            }91            File file = new File(ClassLoader.getSystemResource("IEDriver" + File.separator + "IEDriverServer.exe").getPath());92            System.setProperty("webdriver.ie.driver", file.getAbsolutePath());93            return new EventFiringWebDriver(new InternetExplorerDriver(SeleniumConfig.getInstance().getDefinedCapabilities().getDesiredCapabilities()));94        }95    },96    SAFARI {97        public WebDriver getDriverObject() {98            return new EventFiringWebDriver(new SafariDriver(SeleniumConfig.getInstance().getDefinedCapabilities().getDesiredCapabilities()));99        }100    },101    OPERA {102        public WebDriver getDriverObject() {103            return new OperaDriver(SeleniumConfig.getInstance().getDefinedCapabilities().getDesiredCapabilities());104        }105    },106    PHANTOMJS {107        public WebDriver getDriverObject() {108            return new PhantomJSDriver(SeleniumConfig.getInstance().getDefinedCapabilities().getDesiredCapabilities());109        }110    };111    protected DesiredCapabilities addProxySettings(DesiredCapabilities capabilities, Proxy proxySettings) {112        if (null != proxySettings) {113            capabilities.setCapability(PROXY, proxySettings);114        }115        return capabilities;116    }117    //More options at118    //http://phantomjs.org/api/command-line.html119    protected List<String> applyPhantomJSProxySettings(List<String> phantArgs, Proxy proxySettings) {120        if (null == proxySettings) {121            phantArgs.add("--proxy-type=none");122        } else {123            phantArgs.add("--proxy-type=http");124            phantArgs.add("--proxy=" + proxySettings.getHttpProxy());125        }126        return phantArgs;127    }128    protected void validateFireFoxEnvironment(){129        // Windows 8 requires to set webdriver.firefox.bin system variable130        // to path where executive file of FF is placed131        if (OperatingSystem.isWindowsOperatingSystem()) {132            System.setProperty("webdriver.firefox.bin", "c:" + File.separator + "Program Files (x86)" + File.separator + "Mozilla Firefox" + File.separator + "Firefox.exe");133        }134        // Check if user who is running tests has write access in ~/.mozilla135        // dir and home dir136        if (OperatingSystem.isLinuxOperatingSystem()) {137            File homePath = new File(System.getenv("HOME") + File.separator);138            File mozillaPath = new File(homePath + File.separator + ".mozilla");139            File tmpFile;140            if (mozillaPath.exists()) {141                try {142                    tmpFile = File.createTempFile("webdriver", null, mozillaPath);143                } catch (IOException ex) {144                    throw new RuntimeException("Can't create file in path: %s".replace("%s", mozillaPath.getAbsolutePath()));145                }146            } else {147                try {148                    tmpFile = File.createTempFile("webdriver", null, homePath);149                } catch (IOException ex) {150                    throw new RuntimeException("Can't create file in path: %s".replace("%s", homePath.getAbsolutePath()));151                }152            }153            tmpFile.delete();154        }155    }156}...Source:DriverFactory.java  
1package com.ta.driver;2import com.ta.utils.Log;3import com.ta.waits.WaitParams;4import io.github.bonigarcia.wdm.WebDriverManager;5import java.io.IOException;6import java.lang.management.ManagementFactory;7import java.net.URL;8import java.util.concurrent.TimeUnit;9import org.openqa.selenium.HasCapabilities;10import org.openqa.selenium.MutableCapabilities;11import org.openqa.selenium.WebDriver;12import org.openqa.selenium.chrome.ChromeDriver;13import org.openqa.selenium.chrome.ChromeDriverService;14import org.openqa.selenium.chrome.ChromeOptions;15import org.openqa.selenium.firefox.FirefoxDriver;16import org.openqa.selenium.firefox.FirefoxOptions;17import org.openqa.selenium.firefox.GeckoDriverService;18import org.openqa.selenium.remote.RemoteWebDriver;19import org.openqa.selenium.remote.service.DriverService;20import org.springframework.beans.factory.annotation.Autowired;21import org.springframework.stereotype.Component;22@Component23public class DriverFactory {24  @Autowired25  WaitParams waitParams;26  private String environmentInfo;27  private DriverFactory() {28  }29  public DriverService createAndStartDriverService(30      DriverParams driverParams) {31    Log.logger.info(Log.formatLogMessage(32        "Resolving and setting local WebDriver path according to browser and OS"));33    Drivers.valueOf(driverParams.browser.toUpperCase()).resolveLocalWebDriverPath();34    Log.logger.info(Log.formatLogMessage("Creating driver service instance according to browser"));35    DriverService driverService = Drivers.valueOf(driverParams.browser.toUpperCase()).newDriverService();36    try {37      Log.logger.info(Log.formatLogMessage("Starting driver service instance"));38      driverService.start();39    } catch (IOException e) {40      throw new RuntimeException(e);41    }42    return driverService;43  }44  public WebDriver createDriver(DriverService driverService, DriverParams driverParams) {45    WebDriver driver;46    Log.logger.info(Log.formatLogMessage(47        "Setting capabilities according to browser"));48    MutableCapabilities capabilities =49        Drivers.valueOf(driverParams.browser.toUpperCase()).newCapabilities(driverParams);50    URL url = (driverService == null) ? null : driverService.getUrl();51    if (url != null) {52      Log.logger.info(Log.formatLogMessage(53          "Creating RemoteWebDriver instance using capabilities and URL"));54      driver = new RemoteWebDriver(url, capabilities);55    } else {56      Log.logger.info(Log.formatLogMessage(57          "Creating local WebDriver instance using capabilities"));58      driver = Drivers.valueOf(driverParams.browser.toUpperCase()).newDriver(capabilities);59    }60    Log.logger.info(Log.formatLogMessage("Configuring browser", driver));61    driver.manage().timeouts().pageLoadTimeout(waitParams.pageLoadTimeoutSec, TimeUnit.SECONDS);62    driver.manage().timeouts().implicitlyWait(waitParams.implicitWaitTimeoutSec, TimeUnit.SECONDS);63    if (driverParams.maximize) {64      driver.manage().window().maximize();65    }66    setEnvInfo(driver, driverParams);67    Log.logger.info(Log.formatLogMessage(68        "Browser is started in thread '{}' with id  in JVM '{}'", driver),69        getThreadName(), getThreadId(), getProcessName());70    return driver;71  }72  public String getEnvironmentInfo() {73    return this.environmentInfo;74  }75  private void setEnvInfo(WebDriver webDriver, DriverParams driverParams) {76    environmentInfo = Log.formatLogMessage(""77        + "\nOS name: " + System.getProperty("os.name")78        + "\nOS architecture: " + System.getProperty("os.arch")79        + "\nOS version: " + System.getProperty("os.version")80        + "\nJava version: " + System.getProperty("java.version")81        + "\nEnvironment: " + System.getProperty("env")82        + "\nTarget: " + driverParams.target83        + "\nBrowser name: " + ((HasCapabilities) webDriver).getCapabilities().getBrowserName()84        + "\nBrowser version: " + ((HasCapabilities) webDriver).getCapabilities().getVersion()85        + "\nBrowser window size: " + webDriver.manage().window().getSize().width + "x" + webDriver.manage().window().getSize().height86        + "\nOS (Platform) name: " + ((HasCapabilities) webDriver).getCapabilities().getPlatform().toString()87        + "\nOS (Platform) version: " + ((HasCapabilities) webDriver).getCapabilities().getCapability("platformVersion")88        + "\nThreads Count: " + driverParams.threads89        + "\nAll Capabilities:\n" + ((HasCapabilities) webDriver).getCapabilities().asMap());90    Log.logger.debug(environmentInfo);91  }92  private String getProcessName() {93    return ManagementFactory.getRuntimeMXBean().getName();94  }95  private String getThreadName() {96    return Thread.currentThread().getName();97  }98  private long getThreadId() {99    return Thread.currentThread().getId();100  }101  private static ChromeOptions getChromeOptions(DriverParams driverParams) {102    ChromeOptions options = new ChromeOptions();103    if (driverParams.incognito) {104      options.addArguments("incognito");105    }106    options.setHeadless(driverParams.headless);107    return options;108  }109  private static FirefoxOptions getFirefoxOptions(DriverParams config) {110    FirefoxOptions options = new FirefoxOptions();111    if (config.incognito) {112      options.addArguments("-private");113    }114    options.setHeadless(config.headless);115    return options;116  }117  private enum Drivers {118    FIREFOX {119      @Override120      public void resolveLocalWebDriverPath() {121        WebDriverManager.firefoxdriver().setup();122      }123      @Override124      public MutableCapabilities newCapabilities(DriverParams config) {125        return getFirefoxOptions(config);126      }127      @Override128      public WebDriver newDriver(MutableCapabilities capabilities) {129        return new FirefoxDriver((FirefoxOptions) capabilities);130      }131      @Override132      public DriverService newDriverService() {133        return GeckoDriverService.createDefaultService();134      }135    }, CHROME {136      @Override137      public void resolveLocalWebDriverPath() {138        WebDriverManager.chromedriver().setup();139      }140      @Override141      public MutableCapabilities newCapabilities(DriverParams config) {142        return getChromeOptions(config);143      }144      @Override145      public WebDriver newDriver(MutableCapabilities capabilities) {146        return new ChromeDriver((ChromeOptions) capabilities);147      }148      @Override149      public DriverService newDriverService() {150        return ChromeDriverService.createDefaultService();151      }152    };153    public abstract void resolveLocalWebDriverPath();154    public abstract MutableCapabilities newCapabilities(DriverParams config);155    public abstract WebDriver newDriver(MutableCapabilities capabilities);156    public abstract DriverService newDriverService();157  }158}...Source:DriverType.java  
1package com.km.selenium.config;2import org.openqa.selenium.Platform;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.firefox.FirefoxDriver;6import org.openqa.selenium.ie.InternetExplorerDriver;7import org.openqa.selenium.phantomjs.PhantomJSDriver;8import org.openqa.selenium.phantomjs.PhantomJSDriverService;9import org.openqa.selenium.remote.CapabilityType;10import org.openqa.selenium.remote.DesiredCapabilities;11import org.openqa.selenium.remote.RemoteWebDriver;12import org.openqa.selenium.safari.SafariDriver;13import java.net.MalformedURLException;14import java.net.URL;15import java.util.Arrays;16import java.util.HashMap;17import static com.km.selenium.config.DriverBinaryMapper.configureBinary;18import static com.km.selenium.config.DriverBinaryMapper.getBinaryPath;19import static com.km.selenium.config.OperatingSystem.getOperatingSystem;20import static com.km.selenium.config.SystemArchitecture.getSystemArchitecture;21public enum DriverType implements DriverSetup {22    FIREFOX {23        public DesiredCapabilities getDesiredCapabilities() {24            return DesiredCapabilities.firefox();25        }26        public WebDriver getWebDriverObject(DesiredCapabilities capabilities) {27            return new FirefoxDriver(capabilities);28        }29    },30    CHROME {31        public DesiredCapabilities getDesiredCapabilities() {32            DesiredCapabilities capabilities = DesiredCapabilities.chrome();33            capabilities.setCapability("chrome.switches", Arrays.asList("--no-default-browser-check"));34            HashMap<String, String> chromePreferences = new HashMap<String, String>();35            chromePreferences.put("profile.password_manager_enabled", "false");36            capabilities.setCapability("chrome.prefs", chromePreferences);37            return capabilities;38        }39        public WebDriver getWebDriverObject(DesiredCapabilities capabilities) {40            return new ChromeDriver(capabilities);41        }42        @Override43        public String getWebDriverSystemPropertyKey() {44            return "webdriver.chrome.driver";45        }46    },47    IE {48        public DesiredCapabilities getDesiredCapabilities() {49            DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();50            capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);51            capabilities.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, true);52            capabilities.setCapability("requireWindowFocus", true);53            return capabilities;54        }55        public WebDriver getWebDriverObject(DesiredCapabilities capabilities) {56            return new InternetExplorerDriver(capabilities);57        }58        @Override59        public String getWebDriverSystemPropertyKey() {60            return "webdriver.ie.driver";61        }62    },63    SAFARI {64        public DesiredCapabilities getDesiredCapabilities() {65            DesiredCapabilities capabilities = DesiredCapabilities.safari();66            capabilities.setCapability("safari.cleanSession", true);67            return capabilities;68        }69        public WebDriver getWebDriverObject(DesiredCapabilities capabilities) {70            return new SafariDriver(capabilities);71        }72    },73    PHANTOMJS {74        public DesiredCapabilities getDesiredCapabilities() {75            DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();76            capabilities.setCapability("takesScreenshot", true);77            capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, getBinaryPath(PHANTOMJS, operatingSystem, systemArchitecture));78            return capabilities;79        }80        public WebDriver getWebDriverObject(DesiredCapabilities capabilities) {81            return new PhantomJSDriver(capabilities);82        }83    };84    public static final DriverType defaultDriverType = FIREFOX;85    public static final boolean useRemoteWebDriver = Boolean.valueOf(System.getProperty("remoteDriver"));86    private static final OperatingSystem operatingSystem = getOperatingSystem();87    private static final SystemArchitecture systemArchitecture = getSystemArchitecture();88    public String getWebDriverSystemPropertyKey() {89        return null;90    }91    public WebDriver instantiateWebDriver() throws MalformedURLException {92        DesiredCapabilities desiredCapabilities = getDesiredCapabilities();93        if (useRemoteWebDriver) {94            URL seleniumGridURL = new URL(System.getProperty("gridURL"));95            String desiredBrowserVersion = System.getProperty("desiredBrowserVersion");96            String desiredPlatform = System.getProperty("desiredPlatform");97            if (null != desiredPlatform && !desiredPlatform.isEmpty()) {98                desiredCapabilities.setPlatform(Platform.valueOf(desiredPlatform.toUpperCase()));99            }100            if (null != desiredBrowserVersion && !desiredBrowserVersion.isEmpty()) {101                desiredCapabilities.setVersion(desiredBrowserVersion);102            }103            return new RemoteWebDriver(seleniumGridURL, desiredCapabilities);104        }105        return getWebDriverObject(desiredCapabilities);106    }107    public static DriverType determineEffectiveDriverType(String browser) {108        DriverType driverType = defaultDriverType;109        try {110            driverType = valueOf(browser.toUpperCase());111        } catch (IllegalArgumentException ignored) {112            System.err.println("Unknown driver specified, defaulting to '" + driverType + "'...");113        } catch (NullPointerException ignored) {114            System.err.println("No driver specified, defaulting to '" + driverType + "'...");115        }116        return driverType;117    }118    public WebDriver configureDriverBinaryAndInstantiateWebDriver() {119        System.out.println("Current Operating System: " + operatingSystem.getOperatingSystemType());120        System.out.println("Current Architecture: " + systemArchitecture.getSystemArchitectureType());121        System.out.println("Current Browser Selection: " + this);122        configureBinary(this, operatingSystem, systemArchitecture);123        try {124            return instantiateWebDriver();125        } catch (MalformedURLException urlIsInvalid) {126            urlIsInvalid.printStackTrace();127            return null;128        }129    }130}...Source:Browser.java  
1package com.globant.automation.trainings.webdriver.browsers;2import com.globant.automation.trainings.logging.Logging;3import com.globant.automation.trainings.tests.TestContext;4import com.globant.automation.trainings.utils.Environment;5import io.github.bonigarcia.wdm.*;6import org.openqa.selenium.Capabilities;7import org.openqa.selenium.HasCapabilities;8import org.openqa.selenium.chrome.ChromeOptions;9import org.openqa.selenium.remote.DesiredCapabilities;10import java.util.Map;11import java.util.concurrent.ConcurrentHashMap;12import static com.globant.automation.trainings.webdriver.config.UISettings.UI;13import static io.github.bonigarcia.wdm.Architecture.x32;14import static io.github.bonigarcia.wdm.Architecture.x64;15import static java.lang.String.format;16import static java.util.Optional.ofNullable;17import static java.util.jar.Pack200.Packer.LATEST;18/**19 * Enumeration that defines the browsers supported by this framework20 *21 * @author Juan Krzemien22 */23public enum Browser implements Logging, HasCapabilities {24    FIREFOX {25        @Override26        public Capabilities getCapabilities() {27            initialize(this);28            return DesiredCapabilities.firefox();29        }30    },31    CHROME {32        @Override33        public Capabilities getCapabilities() {34            initialize(this);35            DesiredCapabilities capabilities = DesiredCapabilities.chrome();36            ChromeOptions options = new ChromeOptions();37            options.addArguments(UI.Driver(this).getArguments());38            capabilities.setCapability(ChromeOptions.CAPABILITY, options);39            return capabilities;40        }41    },42    IE {43        @Override44        public Capabilities getCapabilities() {45            initialize(this);46            return DesiredCapabilities.internetExplorer();47        }48    },49    EDGE {50        @Override51        public Capabilities getCapabilities() {52            initialize(this);53            return DesiredCapabilities.edge();54        }55    },56    SAFARI {57        @Override58        public Capabilities getCapabilities() {59            return DesiredCapabilities.safari();60        }61    },62    PHANTOMJS {63        @Override64        public Capabilities getCapabilities() {65            return DesiredCapabilities.htmlUnitWithJs();66        }67    },68    SAUCE_LABS {69        @Override70        public Capabilities getCapabilities() {71            return new DesiredCapabilities();72        }73    },74    ANDROID {75        @Override76        public Capabilities getCapabilities() {77            DesiredCapabilities capabilities = DesiredCapabilities.android();78            ofNullable(TestContext.get()).ifPresent(context -> {79                capabilities.setCapability("locale", context.getLanguage().toLocale().getCountry());80                capabilities.setCapability("language", context.getLanguage().toLocale().getLanguage());81            });82            return capabilities;83        }84    },85    IPHONE {86        @Override87        public Capabilities getCapabilities() {88            return DesiredCapabilities.iphone();89        }90    },91    IPAD {92        @Override93        public Capabilities getCapabilities() {94            return DesiredCapabilities.ipad();95        }96    };97    private static final Architecture architecture = Environment.is64Bits() ? x64 : x32;98    private static final Map<Browser, Boolean> alreadyInitialized = new ConcurrentHashMap<>();99    Browser() {100        getLogger().info(format("Initializing [%s] browser capabilities...", name()));101    }102    private static synchronized void initialize(Browser browser) {103        if (alreadyInitialized.computeIfAbsent(browser, b -> false) || UI.WebDriver().isSeleniumGrid()) {104            return;105        }106        switch (browser) {107            case FIREFOX:108                FirefoxDriverManager.getInstance().architecture(architecture).version(LATEST).setup();109                break;110            case CHROME:111                ChromeDriverManager.getInstance().architecture(architecture).version(LATEST).setup();112                break;113            case IE:114                // Override architecture for IE. 64 bits version is known to misbehave...115                InternetExplorerDriverManager.getInstance().arch32().version("3.3").setup();116                break;117            case EDGE:118                EdgeDriverManager.getInstance().architecture(architecture).version(LATEST).setup();119                break;120            case PHANTOMJS:121                PhantomJsDriverManager.getInstance().architecture(architecture).version(LATEST).setup();122                break;123            default:124                break;125        }126        alreadyInitialized.put(browser, true);127    }128}...Source:DriverSelector.java  
1package selenium.config;2import org.openqa.selenium.Platform;3import org.openqa.selenium.Proxy;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.remote.DesiredCapabilities;6import org.openqa.selenium.remote.RemoteWebDriver;7import java.net.MalformedURLException;8import java.net.URL;9import static org.openqa.selenium.Proxy.ProxyType.MANUAL;10import static selenium.config.DriverEnum.CHROME;11import static selenium.config.DriverEnum.valueOf;12public class DriverSelector {13    private WebDriver webdriver;14    private DriverEnum selectedDriverType;15    private final DriverEnum defaultDriverType = CHROME;16    private final String browser = System.getProperty("browser", defaultDriverType.toString()).toUpperCase();17    private final String operatingSystem = System.getProperty("os.name").toUpperCase();18    private final String systemArchitecture = System.getProperty("os.arch");19    private final boolean useRemoteWebDriver = Boolean.getBoolean("remoteDriver");20    private final boolean proxyEnabled = Boolean.getBoolean("proxyEnabled");21    private final String proxyHostname = System.getProperty("proxyHost");22    private final Integer proxyPort = Integer.getInteger("proxyPort");23    private final String proxyDetails = String.format("%s:%d", proxyHostname, proxyPort);24    public WebDriver getDriver() throws Exception {25        if (null == webdriver) {26            Proxy proxy = null;27            if (proxyEnabled) {28                proxy = new Proxy();29                proxy.setProxyType(MANUAL);30                proxy.setHttpProxy(proxyDetails);31                proxy.setSslProxy(proxyDetails);32            }33            determineEffectiveDriverType();34            DesiredCapabilities desiredCapabilities = selectedDriverType.getDesiredCapabilities(proxy);35            instantiateWebDriver(desiredCapabilities);36        }37        return webdriver;38    }39    public void quitDriver() {40        if (null != webdriver) {41            webdriver.quit();42        }43    }44    private void determineEffectiveDriverType() {45        DriverEnum driverType = defaultDriverType;46        try {47            driverType = valueOf(browser);48        } catch (IllegalArgumentException ignored) {49            System.err.println("Unknown driver specified, defaulting to '" + driverType + "'...");50        } catch (NullPointerException ignored) {51            System.err.println("No driver specified, defaulting to '" + driverType + "'...");52        }53        selectedDriverType = driverType;54    }55    private void instantiateWebDriver(DesiredCapabilities desiredCapabilities) throws MalformedURLException {56        System.out.println(" ");57        System.out.println("Current Operating System: " + operatingSystem);58        System.out.println("Current Architecture: " + systemArchitecture);59        System.out.println("Current Browser Selection: " + selectedDriverType);60        System.out.println(" ");61        if (useRemoteWebDriver) {62            URL seleniumGridURL = new URL(System.getProperty("gridURL"));63            String desiredBrowserVersion = System.getProperty("desiredBrowserVersion");64            String desiredPlatform = System.getProperty("desiredPlatform");65            if (null != desiredPlatform && !desiredPlatform.isEmpty()) {66                desiredCapabilities.setPlatform(Platform.valueOf(desiredPlatform.toUpperCase()));67            }68            if (null != desiredBrowserVersion && !desiredBrowserVersion.isEmpty()) {69                desiredCapabilities.setVersion(desiredBrowserVersion);70            }71            webdriver = new RemoteWebDriver(seleniumGridURL, desiredCapabilities);72        } else {73            webdriver = selectedDriverType.getWebDriverObject(desiredCapabilities);74        }75    }76}...Enum Architecture
Using AI Code Generation
1package com.selenium;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.chrome.ChromeDriverService;8import org.openqa.selenium.remote.DesiredCapabilities;9import org.openqa.selenium.remote.RemoteWebDriver;10import java.io.File;11import java.io.IOException;12import java.util.List;13import java.util.concurrent.TimeUnit;14import org.openqa.selenium.support.ui.Select;15import org.openqa.selenium.support.ui.WebDriverWait;16import org.openqa.selenium.support.ui.ExpectedConditions;17import org.openqa.selenium.JavascriptExecutor;18import org.openqa.selenium.interactions.Actions;19import org.openqa.selenium.Keys;20import org.openqa.selenium.Platform;21import org.openqa.selenium.Proxy;22import org.openqa.selenium.TakesScreenshot;23import org.openqa.selenium.OutputType;24import org.openqa.selenium.Dimension;25import org.openqa.selenium.Point;26import org.openqa.selenium.Alert;27import org.openqa.selenium.Cookie;28import org.openqa.selenium.NoSuchElementException;29import org.openqa.selenium.StaleElementReferenceException;30import org.openqa.selenium.WebDriverException;31import org.openqa.selenium.WebElement;32import org.openqa.selenium.remote.Augmenter;33import org.openqa.selenium.remote.Augmentable;34import org.openqa.selenium.remote.CapabilityType;35import org.openqa.selenium.remote.CommandExecutor;36import org.openqa.selenium.remote.DesiredCapabilities;37import org.openqa.selenium.remote.DriverCommand;38import org.openqa.selenium.remote.ErrorHandler;39import org.openqa.selenium.remote.FileDetector;40import org.openqa.selenium.remote.Response;41import org.openqa.selenium.remote.RemoteWebElement;42import org.openqa.selenium.remote.SessionId;43import org.openqa.selenium.remote.UnreachableBrowserException;44import org.openqa.selenium.remote.http.HttpMethod;45import org.openqa.selenium.remote.internal.WebElementToJsonConverter;46import org.openqa.selenium.remote.service.DriverService;47import org.openqa.selenium.remote.service.DriverCommandExecutor;48import org.openqa.selenium.support.ui.ExpectedCondition;49import org.openqa.selenium.support.ui.FluentWait;50import org.openqa.selenium.support.ui.Wait;51import org.openqa.selenium.support.ui.WebDriverWait;52import org.openqa.selenium.support.ui.ExpectedConditions;53import org.openqa.selenium.support.ui.Select;54import org.openqa.selenium.support.ui.Select;55import org.openqa.selenium.support.ui.Wait;56import org.openqa.selenium.support.ui.WebDriverWait;57import org.openqa.selenium.support.ui.ExpectedConditions;58import org.openqa.selenium.support.ui.Select;59import org.openqa.selenium.support.ui.Select;60import org.openqa.selenium.support.ui.Wait;61import org.openqa.selenium.support.ui.WebDriverWait;62import org.openqa.selenium.support.ui.ExpectedConditions;63import org.openqa.selenium.support.ui.Select;64importEnum Architecture
Using AI Code Generation
1import org.openqa.selenium.Architecture;2import org.openqa.selenium.Platform;3public class TestEnum {4    public static void main(String[] args) {5        System.out.println("Architecture: " + Architecture.X86);6        System.out.println("Platform: " + Platform.WIN10);7    }8}9import java.util.EnumSet;10import org.openqa.selenium.Architecture;11import org.openqa.selenium.Platform;12public class TestEnum {13    public static void main(String[] args) {14        System.out.println("EnumSet: " + EnumSet.of(Architecture.X86, Platform.WIN10));15    }16}17import java.util.EnumMap;18import org.openqa.selenium.Architecture;19import org.openqa.selenium.Platform;20public class TestEnum {21    public static void main(String[] args) {22        EnumMap<Architecture, Platform> enumMap = new EnumMap<Architecture, Platform>(Architecture.class);23        enumMap.put(Architecture.X86, Platform.WIN10);24        System.out.println("EnumMap: " + enumMap);25    }26}27EnumMap: {X86=WIN10}28You can also use EnumSet.allOf() method to get all the constants of the given enum type:29import java.util.EnumSet;30import org.openqa.selenium.Architecture;31public class TestEnum {32    public static void main(String[] args) {33        System.out.println("EnumSet.allOf(): " + EnumSet.allOf(Architecture.class));34    }35}36EnumSet.allOf(): [X86, X64, ARM64, UNKNOWN]37You can also use Enum.valueOf() method to get the constant of the given enum type with the specified name:38import org.openqa.selenium.Architecture;39public class TestEnum {40    public static void main(String[] args) {41        System.out.println("Enum.valueOf(): " + Enum.valueOf(Architecture.class, "X86"));42    }43}Enum Architecture
Using AI Code Generation
1public class TestEnum {2public static void main(String[] args) {3    WebDriver driver = new ChromeDriver();4    driver.manage().window().maximize();5    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);6    driver.findElement(By.name("q")).sendKeys("Selenium");7    driver.findElement(By.name("btnK")).submit();8    driver.close();9    driver.quit();10}11}12public class TestEnum {13public static void main(String[] args) {14    WebDriver driver = new ChromeDriver();15    driver.manage().window().maximize();16    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);17    driver.findElement(By.name("q")).sendKeys("Selenium");18    driver.findElement(By.name("btnK")).submit();19    driver.close();20    driver.quit();21}22}23public class TestEnum {24public static void main(String[] args) {25    WebDriver driver = new ChromeDriver();26    driver.manage().window().maximize();27    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);28    driver.findElement(By.name("q")).sendKeys("Selenium");29    driver.findElement(By.name("btnK")).submit();30    driver.close();31    driver.quit();32}33}34public class TestEnum {35public static void main(String[] args) {36    WebDriver driver = new ChromeDriver();37    driver.manage().window().maximize();38    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);39    driver.findElement(By.name("q")).sendKeys("Selenium");40    driver.findElement(By.name("btnK")).submit();41    driver.close();42    driver.quit();43}44}45public class TestEnum {46public static void main(String[] args) {47    WebDriver driver = new ChromeDriver();48    driver.manage().window().maximize();49    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);50    driver.findElement(By.name("q")).sendKeys("Selenium");51    driver.findElement(By.name("btnK")).submit();52    driver.close();Enum Architecture
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.chrome.ChromeDriver;3import org.openqa.selenium.remote.DesiredCapabilities;4import org.openqa.selenium.Platform;5import org.openqa.selenium.remote.Architecture;6import org.openqa.selenium.remote.BrowserType;7import org.openqa.selenium.remote.RemoteWebDriver;8import java.net.URL;9import java.net.MalformedURLException;10import java.util.concurrent.TimeUnit;11import org.openqa.selenium.By;12import org.openqa.selenium.WebElement;13import org.openqa.selenium.Keys;14import java.util.List;15import java.util.Iterator;16import org.openqa.selenium.NoSuchElementException;17import org.openqa.selenium.JavascriptExecutor;18import org.openqa.selenium.Alert;19import org.openqa.selenium.support.ui.ExpectedConditions;20import org.openqa.selenium.support.ui.WebDriverWait;21import org.openqa.selenium.interactions.Actions;22import org.openqa.selenium.By;23import org.openqa.selenium.WebElement;24import org.openqa.selenium.Keys;25import java.util.List;26import java.util.Iterator;27import org.openqa.selenium.NoSuchElementException;Enum Architecture
Using AI Code Generation
1import org.openqa.selenium.firefox.FirefoxDriver;2import org.openqa.selenium.firefox.FirefoxOptions;3import org.openqa.selenium.firefox.FirefoxProfile;4import org.openqa.selenium.remote.CapabilityType;5import org.openqa.selenium.remote.DesiredCapabilities;6public class GetBrowserArchitecture {7    public static void main(String[] args) {8        System.setProperty("webdriver.gecko.driver", "C:\\Users\\Vipul\\Downloads\\geckodriver-v0.26.0-win64\\geckodriver.exe");9        FirefoxOptions options = new FirefoxOptions();10        options.setCapability(CapabilityType.BROWSER_ARCHITECTURE, 64);11        System.out.println("Browser architecture is: " + options.getCapability(CapabilityType.BROWSER_ARCHITECTURE));12        FirefoxProfile profile = new FirefoxProfile();13        profile.setPreference("browser.download.folderList", 2);14        profile.setPreference("browser.download.dir", "C:\\Users\\Vipul\\Downloads");15        options.setProfile(profile);16        DesiredCapabilities capabilities = DesiredCapabilities.firefox();17        capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);18        FirefoxDriver driver = new FirefoxDriver(capabilities);19    }20}1System.setProperty("webdriver.chrome.driver", "/path/to/your/chrome/driver");2WebDriver driver = new ChromeDriver();31String chromeDriverPath = "/path/to/chromedriver.exe";2DesiredCapabilities capabilities = DesiredCapabilities.chrome();3ChromeDriverService Service = Builder4    .usingAnyFreePort()5    .withLogFile(new File("./chromdriver.log"))6    .usingDriverExecutable(new File(chromeDriverPath))7    .build();8CommandExecutor commandExecutor = new DriverCommandExecutor(Service);9RemoteWebDriver driver = new RemoteWebDriver(commandExecutor, capabilities);10WebDriverRunner.setWebDriver(driver); //Set driver that Selenide should use11LambdaTest’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.
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.
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.
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.
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.
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.
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.
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.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
