Example usage for org.openqa.selenium.chrome ChromeOptions ChromeOptions

List of usage examples for org.openqa.selenium.chrome ChromeOptions ChromeOptions

Introduction

In this page you can find the example usage for org.openqa.selenium.chrome ChromeOptions ChromeOptions.

Prototype

public ChromeOptions() 

Source Link

Usage

From source file:org.safs.selenium.webdriver.lib.SelectBrowser.java

License:Open Source License

/**
 * Add chrome-options-settings to Capabilities for chrome browser.<br>
 * How to set the capabilities, refer to following 2 links:<br>
 * https://sites.google.com/a/chromium.org/chromedriver/capabilities<br>
 * http://peter.sh/experiments/chromium-command-line-switches/<br>
 * @param caps DesiredCapabilities, a chrome DesiredCapabilities.
 * @param extraParameters Map<String,Object>, contains chrome specific parameters pair (key, value), 
 *                                            such as "user-data-dir", "profile-directory" and "excludeSwitches" etc.
 * @see #getDesiredCapabilities(String, Map)                                           
 *//*from  w w w  . j a  va2 s . c o m*/
private static void setChromeCapabilities(DesiredCapabilities caps, Map<String, Object> extraParameters) {
    String debugmsg = StringUtils.debugmsg(false);
    ChromeOptions options = null;
    if (caps == null || extraParameters == null || extraParameters.isEmpty()) {
        IndependantLog.debug(debugmsg + " caps is null or there are no browser specific parametes to set.");
        return;
    }

    try {
        //Get the general data setting directory, it is for all users
        String chromeUserDataDir = StringUtilities.getString(extraParameters, KEY_CHROME_USER_DATA_DIR);
        IndependantLog.debug(debugmsg + "Try to Set chrome user data directory '" + chromeUserDataDir
                + "' to ChromeOptions.");
        options = new ChromeOptions();
        if (!chromeUserDataDir.isEmpty()) {
            caps.setCapability(KEY_CHROME_USER_DATA_DIR, chromeUserDataDir);//used to store in session file
            options.addArguments(KEY_CHROME_USER_DATA_DIR + "=" + chromeUserDataDir);
        }
    } catch (Exception e) {
        IndependantLog.warn(debugmsg + "Fail to Set chrome user data directory to ChromeOptions.");
    }
    try {
        //Get user-specific settings directory, it is for one user
        String profiledir = StringUtilities.getString(extraParameters, KEY_CHROME_PROFILE_DIR);
        IndependantLog
                .debug(debugmsg + "Try to Set chrome profile directory '" + profiledir + "' to ChromeOptions.");
        if (options == null)
            options = new ChromeOptions();
        if (!profiledir.isEmpty()) {
            caps.setCapability(KEY_CHROME_PROFILE_DIR, profiledir);//used to store in session file
            options.addArguments(KEY_CHROME_PROFILE_DIR + "=" + profiledir);
        }
    } catch (Exception e) {
        IndependantLog.warn(debugmsg + "Fail to Set chrome profile directory to ChromeOptions.");
    }

    try {
        // Parse '--disable-extensions' parameters to add into ChromeOptions
        String disableExtensionsOptions = StringUtilities.getString(extraParameters,
                KEY_CHROME_DISABLE_EXTENSIONS);
        IndependantLog
                .debug(debugmsg + "Try to disable Chrome extensions: '" + disableExtensionsOptions + "'.");
        if (options == null)
            options = new ChromeOptions();
        if (!disableExtensionsOptions.isEmpty() && disableExtensionsOptions.toLowerCase().equals("true")) {
            options.addArguments(KEY_CHROME_DISABLE_EXTENSIONS);
        }
    } catch (Exception e) {
        IndependantLog.warn(debugmsg + "Fail to set disable Chrome extensions for ChromeOptions.");
    }

    try {
        //Get user command-line-options/preferences file (it contains command-line-options and/or preferences), and set them to ChromeOptions
        String commandLineOptions_preferenceFile = StringUtilities.getString(extraParameters,
                KEY_CHROME_PREFERENCE);
        IndependantLog.debug(debugmsg + "Try to Set chrome command-line-options/preferences file '"
                + commandLineOptions_preferenceFile + "' to ChromeOptions.");
        Map<?, ?> commandLineOptions = Json.readJSONFileUTF8(commandLineOptions_preferenceFile);
        if (options == null)
            options = new ChromeOptions();
        caps.setCapability(KEY_CHROME_PREFERENCE, commandLineOptions_preferenceFile);//used to store in session file

        //Set Chrome Preferences
        if (commandLineOptions.containsKey(KEY_CHROME_PREFERENCE_JSON_KEY)) {
            Map<?, ?> preferences = null;
            try {
                preferences = (Map<?, ?>) commandLineOptions.get(KEY_CHROME_PREFERENCE_JSON_KEY);
                IndependantLog.debug(debugmsg + "Setting preferences " + preferences + " to ChromeOptions.");
                options.setExperimentalOption(KEY_CHROME_PREFS, preferences);
            } catch (Exception e) {
                IndependantLog.warn(debugmsg + "Failed to Set chrome preferences to ChromeOptions, due to "
                        + StringUtils.debugmsg(e));
            }
            //remove the preferences from the Map object chromeCommandLineOptions, then the map will only contain "command line options".
            commandLineOptions.remove(KEY_CHROME_PREFERENCE_JSON_KEY);
        }

        //Set Chrome Command Line Options
        IndependantLog
                .debug(debugmsg + "Setting command line options " + commandLineOptions + " to ChromeOptions.");
        addChromeCommandLineOptions(options, commandLineOptions);

    } catch (Exception e) {
        IndependantLog.warn(debugmsg + "Fail to Set chrome preference file to ChromeOptions.");
    }

    try {
        //Get user-specific exclude options
        String excludeOptions = StringUtilities.getString(extraParameters, KEY_CHROME_EXCLUDE_OPTIONS);
        IndependantLog.debug(
                debugmsg + "Try to Set chrome excludeSwitches '" + excludeOptions + "' to ChromeOptions.");
        if (options == null)
            options = new ChromeOptions();
        if (!excludeOptions.isEmpty()) {
            caps.setCapability(KEY_CHROME_EXCLUDE_OPTIONS, excludeOptions);//used to store in session file
            List<String> excludeOptionsList = null;
            if (excludeOptions.contains(StringUtils.COMMA)) {
                excludeOptionsList = StringUtils.getTrimmedTokenList(excludeOptions, StringUtils.COMMA);
            } else {
                excludeOptionsList = StringUtils.getTrimmedTokenList(excludeOptions, StringUtils.SEMI_COLON);
            }

            options.setExperimentalOption(KEY_CHROME_EXCLUDE_OPTIONS, excludeOptionsList);
        }
    } catch (Exception e) {
        IndependantLog.warn(debugmsg + "Fail to Set chrome excludeSwitches to ChromeOptions.");
    }
    if (options != null)
        caps.setCapability(ChromeOptions.CAPABILITY, options);
}

From source file:org.securitytests.cisecurity.drivers.DriverFactory.java

License:Open Source License

public WebDriver createChromeDriver(DesiredCapabilities capabilities) {
    System.setProperty("webdriver.chrome.driver", Config.getDefaultDriverPath());
    if (capabilities != null) {
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--test-type");
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        return new ChromeDriver(capabilities);
    } else/*from  w w  w  .  j a  v  a 2s  .  co  m*/
        return new ChromeDriver();

}

From source file:org.specrunner.webdriver.impl.WebDriverFactoryChrome.java

License:Open Source License

@Override
public WebDriver create(String name, IContext context) throws PluginException {
    if (UtilLog.LOG.isInfoEnabled()) {
        UtilLog.LOG.info("Factory:" + getClass());
    }//ww w  .j  a  v  a  2  s .c om
    File fChrome = new File(chrome);
    if (!fChrome.exists()) {
        throw new PluginException("Missing Chrome application at:" + fChrome
                + ". Download Chrome and/or set 'FEATURE_CHROME' feature to the application executable.");
    }
    File fDriver = new File(driver);
    if (!fDriver.exists()) {
        throw new PluginException("Missing Chrome driver at Chrome path:" + fDriver
                + ". Download 'chromedriver.exe' at http://chromium.googlecode.com/ and set 'FEATURE_DRIVER' to the executable.");
    }
    System.setProperty("webdriver.chrome.driver", fDriver.getAbsolutePath());
    ChromeOptions options = new ChromeOptions();
    options.setBinary(fChrome);
    if (switches != null) {
        options.addArguments(switches);
    }
    return new ChromeDriver(options);
}

From source file:org.structr.web.frontend.selenium.ParallelLoginTest.java

License:Open Source License

public void testParallelLogin() {

    createAdminUser();/*from   ww  w.  ja v a2 s  .c  om*/

    final int numberOfRequests = 10000;
    final int numberOfParallelThreads = 8;
    final int waitForSec = 30;

    final ExecutorService service = Executors.newFixedThreadPool(numberOfParallelThreads);
    final List<Future<Exception>> results = new ArrayList<>();

    final String menuEntry = "Pages";

    System.setProperty("webdriver.chrome.driver",
            SeleniumTest.getBrowserDriverLocation(SupportedBrowsers.CHROME));

    final ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.setHeadless(true);

    for (int i = 0; i < numberOfRequests; i++) {

        Future<Exception> result = service.submit(() -> {

            //System.out.println(SimpleDateFormat.getDateInstance().format(new Date()) + " Login attempt from thread " + Thread.currentThread().toString());
            logger.info("Login attempt from thread " + Thread.currentThread().toString());

            WebDriver localDriver = new ChromeDriver(chromeOptions);

            try {
                long t0 = System.currentTimeMillis();

                // Wait for successful login
                SeleniumTest.loginAsAdmin(menuEntry, localDriver, waitForSec);

                long t1 = System.currentTimeMillis();

                logger.info("Successful login after " + (t1 - t0) + " ms  with thread "
                        + Thread.currentThread().toString());

            } catch (Exception ex) {
                logger.error("Error in nested test in thread " + Thread.currentThread().toString(), ex);
                return ex;
            } finally {
                localDriver.quit();
            }

            localDriver = null;

            return null;
        });

        results.add(result);
    }

    int r = 0;
    long t0 = System.currentTimeMillis();

    for (final Future<Exception> result : results) {

        try {

            long t1 = System.currentTimeMillis();
            Exception res = result.get();
            long t2 = System.currentTimeMillis();
            r++;

            logger.info(r + ": Got result from future after " + (t2 - t1) + " ms");

            assertNull(res);

        } catch (final InterruptedException | ExecutionException ex) {
            logger.error("Error while checking result of nested test", ex);
        }
    }

    long t3 = System.currentTimeMillis();

    logger.info("Got all results within " + (t3 - t0) / 1000 + " s");

    service.shutdown();

    logger.info("Waiting " + waitForSec + " s to allow login processes to finish before stopping the instance");

    try {
        Thread.sleep(waitForSec * 1000);
    } catch (InterruptedException ex) {
    }
}

From source file:org.structr.web.frontend.selenium.SeleniumTest.java

License:Open Source License

@Before
public void startDriver() {

    switch (activeBrowser) {

    case FIREFOX:

        System.setProperty("webdriver.gecko.driver", getBrowserDriverLocation(activeBrowser));

        final FirefoxOptions firefoxOptions = new FirefoxOptions();
        firefoxOptions.setHeadless(true);

        driver = new FirefoxDriver(firefoxOptions);

        break;/*from  w  w  w .jav a2 s. com*/

    case CHROME:

        System.setProperty("webdriver.chrome.driver", getBrowserDriverLocation(activeBrowser));
        System.setProperty("webdriver.chrome.logfile", "/tmp/chromedriver.log");
        System.setProperty("webdriver.chrome.verboseLogging", "true");

        final ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setHeadless(true);

        driver = new ChromeDriver(chromeOptions);

        break;

    case NONE:

        // Don't create a driver in main thread, useful for parallel testing
        break;
    }
}

From source file:org.suren.autotest.web.framework.selenium.CapabilityConfig.java

License:Apache License

/**
 * ?/*from w w w  .ja v  a  2s .c  o  m*/
 * chrome://version/
 */
private void chrome() {
    DesiredCapabilities capability = DesiredCapabilities.chrome();

    ChromeOptions options = new ChromeOptions();
    Iterator<Object> chromeKeys = enginePro.keySet().iterator();
    Proxy proxy = new Proxy();
    while (chromeKeys.hasNext()) {
        String key = chromeKeys.next().toString();
        if (!key.startsWith("chrome")) {
            continue;
        }

        if (key.startsWith("chrome.args")) {
            String arg = key.replace("chrome.args.", "") + "=" + enginePro.getProperty(key);
            if (arg.endsWith("=")) {
                arg = arg.substring(0, arg.length() - 1);
            }
            options.addArguments(arg);
            logger.info(String.format("chrome arguments : [%s]", arg));
        } else if (key.startsWith("chrome.cap.proxy.http")) {
            String val = enginePro.getProperty(key);

            proxy.setHttpProxy(val);
        } else if (key.startsWith("chrome.cap.proxy.ftp")) {
            String val = enginePro.getProperty(key);

            proxy.setFtpProxy(val);
        } else if (key.startsWith("chrome.cap.proxy.socks")) {
            String val = enginePro.getProperty(key);

            proxy.setSocksProxy(val);
        } else if (key.startsWith("chrome.cap.proxy.socks.username")) {
            String val = enginePro.getProperty(key);

            proxy.setSocksUsername(val);
        } else if (key.startsWith("chrome.cap.proxy.socks.password")) {
            String val = enginePro.getProperty(key);

            proxy.setSocksPassword(val);
        } else if (key.startsWith("chrome.binary")) {
            options.setBinary(enginePro.getProperty(key));
        }
    }

    if ("true".equals(enginePro.getProperty("chrome.cap.proxy.enable"))) {
        capability.setCapability("proxy", proxy);
    }
    capability.setCapability(ChromeOptions.CAPABILITY, options);

    engineCapMap.put(DRIVER_CHROME, capability);
}

From source file:org.terasoluna.gfw.tutorial.selenium.WebDriverCreator.java

License:Apache License

/**
 * Create a WebDriver with any locale enabled.
 * <p>//from  w  w w  .  j av a2  s .  c o  m
 * Supports FireFox and Chrome only<br>
 * If you specify "en" as an argument, it starts in the English locale.<br>
 * If "" is specified as an argument, it starts without a locale.
 * </p>
 * @param localeStr
 * @return WebDriver Operation target browser
 */
public WebDriver createLocaleSpecifiedDriver(String localeStr) {

    for (String activeProfile : getApplicationContext().getEnvironment().getActiveProfiles()) {
        if ("chrome".equals(activeProfile)) {
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--lang=" + localeStr);
            return new ChromeDriver(options);
        } else if ("firefox".equals(activeProfile)) {
            break;
        } else if ("ie".equals(activeProfile)) {
            throw new UnsupportedOperationException(
                    "It is not possible to start locale specified browser using InternetExplorer.");
        } else if ("phantomJs".equals(activeProfile)) {
            throw new UnsupportedOperationException(
                    "It is not possible to launch locale specified browser using PhantomJS.");
        }
    }

    // The default browser is Firefox
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("intl.accept_languages", localeStr);
    profile.setPreference("brouser.startup.homepage_override.mstone", "ignore");
    profile.setPreference("network.proxy.type", 0);
    return new FirefoxDriver(profile);
}

From source file:org.testeditor.fixture.web.WebDriverFixture.java

License:Open Source License

private ChromeOptions populateBrowserSettingsForChrome() throws FixtureException {
    List<BrowserSetting> options = new ArrayList<>();
    // specifying capabilities and options with the aid of the browser type.
    populateWithBrowserSpecificSettings(BrowserType.CHROME, options);
    ChromeOptions chromeOptions = new ChromeOptions();
    // Specific method because a ChromeOption is just a String like
    // "allow-outdated-plugins" or "load-extension=/path/to/unpacked_extension"
    populateChromeOption(options, chromeOptions);
    return chromeOptions;
}

From source file:org.zanata.page.WebDriverFactory.java

License:Open Source License

private EventFiringWebDriver configureChromeDriver() {
    System.setProperty(ChromeDriverService.CHROME_DRIVER_LOG_PROPERTY,
            PropertiesHolder.getProperty("webdriver.log"));
    driverService = ChromeDriverService.createDefaultService();
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability("chrome.binary",
            PropertiesHolder.properties.getProperty("webdriver.chrome.bin"));

    ChromeOptions options = new ChromeOptions();
    URL url = Thread.currentThread().getContextClassLoader()
            .getResource("zanata-testing-extension/chrome/manifest.json");
    assert url != null : "can't find extension (check testResource config in pom.xml)";
    File file = new File(url.getPath()).getParentFile();
    options.addArguments("load-extension=" + file.getAbsolutePath());
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);

    enableLogging(capabilities);/*from w  w  w .j  a  va 2  s.c om*/

    // start the proxy
    BrowserMobProxy proxy = new BrowserMobProxyServer();
    proxy.start(0);

    proxy.addFirstHttpFilterFactory(
            new ResponseFilterAdapter.FilterSource((response, contents, messageInfo) -> {
                // TODO fail test if response >= 500?
                if (response.getStatus().code() >= 400) {
                    log.warn("Response {} for URI {}", response.getStatus(),
                            messageInfo.getOriginalRequest().getUri());
                } else {
                    log.info("Response {} for URI {}", response.getStatus(),
                            messageInfo.getOriginalRequest().getUri());
                }
            }, 0));
    Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
    capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
    try {
        driverService.start();
    } catch (IOException e) {
        throw new RuntimeException("fail to start chrome driver service");
    }
    return new EventFiringWebDriver(
            new Augmenter().augment(new RemoteWebDriver(driverService.getUrl(), capabilities)));
}

From source file:org.zaproxy.zap.extension.jxbrowserlinux64.selenium.JxBrowserProvider.java

License:Apache License

private RemoteWebDriver getRemoteWebDriverImpl(final int requesterId, String proxyAddress, int proxyPort) {
    try {/* ww  w .  ja va2s.  c om*/
        ZapBrowserFrame zbf = this.getZapBrowserFrame(requesterId);

        File dataDir = Files.createTempDirectory("zap-jxbrowser").toFile();
        dataDir.deleteOnExit();
        BrowserContextParams contextParams = new BrowserContextParams(dataDir.getAbsolutePath());

        if (proxyAddress != null && !proxyAddress.isEmpty()) {
            String hostPort = proxyAddress + ":" + proxyPort;
            String proxyRules = "http=" + hostPort + ";https=" + hostPort;
            contextParams.setProxyConfig(new CustomProxyConfig(proxyRules));
        }

        BrowserPreferences.setChromiumSwitches("--remote-debugging-port=" + chromePort);
        Browser browser = new Browser(new BrowserContext(contextParams));
        final BrowserPanel browserPanel = zbf.addNewBrowserPanel(isNotAutomated(requesterId), browser);

        if (!ensureExecutable(webdriver)) {
            throw new IllegalStateException("Failed to ensure WebDriver is executable.");
        }
        final ChromeDriverService service = new ChromeDriverService.Builder()
                .usingDriverExecutable(webdriver.toFile()).usingAnyFreePort().build();
        service.start();

        DesiredCapabilities capabilities = new DesiredCapabilities();
        ChromeOptions options = new ChromeOptions();

        options.setExperimentalOption("debuggerAddress", "localhost:" + chromePort);
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);

        return new RemoteWebDriver(service.getUrl(), capabilities) {

            @Override
            public void close() {
                super.close();

                cleanUpBrowser(requesterId, browserPanel);
                // XXX should stop here too?
                // service.stop();
            }

            @Override
            public void quit() {
                super.quit();

                cleanUpBrowser(requesterId, browserPanel);

                boolean interrupted = Thread.interrupted();
                service.stop();
                if (interrupted) {
                    Thread.currentThread().interrupt();
                }
            }
        };
    } catch (Exception e) {
        throw new WebDriverException(e);
    }
}