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

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

Introduction

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

Prototype

String CAPABILITY

To view the source code for org.openqa.selenium.chrome ChromeOptions CAPABILITY.

Click Source Link

Document

Key used to store a set of ChromeOptions in a Capabilities object.

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)                                           
 *///ww  w  . j  a  v  a 2s . 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 ava2  s .c o  m
        return new ChromeDriver();

}

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

License:Apache License

/**
 * ?/*from   www  . j av a 2 s.  co 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.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  ava 2 s . co  m*/

    // 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 {//from w  ww  .j a  va2  s.co  m
        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);
    }
}

From source file:PokemonGoMapValidator.Config.java

public void configInstance(String driverFile, String profileFile, String mapFile) {
    WebDriver webDriver = null;/*from  w w  w  .  j  a  va2 s .c  o  m*/

    try {
        System.setProperty("webdriver.chrome.driver", driverFile);

        String currentDirectory = Paths.get(".").toAbsolutePath().normalize().toString();

        ZipFile zipFile = new ZipFile(profileFile);
        zipFile.extractAll(currentDirectory + "/" + "profile" + "/");

        File f = new File(currentDirectory + "/prints/");
        if (!f.isDirectory()) {
            new File(currentDirectory + "/prints/").mkdir();
        }

        HashMap<String, Object> chromePrefs = new HashMap<>();
        chromePrefs.put("profile.default_content_settings.popups", 0);
        chromePrefs.put("download.default_directory", currentDirectory);

        ChromeOptions options = new ChromeOptions();

        //se na user-data-dir nao existir profile do chrome,  gerado um na hora
        options.addArguments("user-data-dir=" + currentDirectory + "/" + "profile");
        options.addArguments("--start-maximized");
        //adicionei esta linha, j que dns e portos andam sempre em mudanas
        options.addArguments("--dns-prefetch-disable");
        //options.addExtensions(new File(extensionFile));
        options.setExperimentalOption("prefs", chromePrefs);

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        webDriver = new ChromeDriver(capabilities);

        //pokemongos grow in sextagon shape, so I will force a square resolution
        webDriver.manage().window().setPosition(new Point(XCOORD, YCOORD));
        if (MAPDIMENSION > 0) {
            webDriver.manage().window().setSize(new Dimension(MAPDIMENSION, MAPDIMENSION));
        } else {
            webDriver.manage().window().maximize();
        }

        //in the code below, I tried to create a square, but the width's and height's
        //seem to change, and I didn't figured out why and how
        //TODO in the future
        /*
        webDriver.get("http://www.google.com");
        Thread.sleep(1000);
        Dimension win_size = webDriver.manage().window().getSize();
                
        WebElement html = webDriver.findElement(By.tagName("html"));
        int inner_width = Integer.parseInt(html.getAttribute("clientWidth"));
        int outer_width = win_size.width - inner_width;
        int inner_height = Integer.parseInt(html.getAttribute("clientHeight"));
        int outer_height = win_size.height - inner_height;
                
        //pokemongos grow in sextagon shape, so I will force a square resolution
        webDriver.manage().window().setPosition(new Point(0, -1080));
        webDriver.manage().window().setSize(new Dimension(800 + outer_width, 600 + outer_height));
                
        if (VALIDATEBROWSER) {
        new Graphics().browserDimension(webDriver);
        }
                
        */

        RunComparison comparison = new RunComparison();
        comparison.comparison(currentDirectory, webDriver, mapFile);

    } catch (ZipException | IOException | InterruptedException ex) {
        System.err.println("Config error: " + ex.getMessage());
    } finally {
        try {
            if (webDriver != null) {
                Exit sair = new Exit();
                sair.exit(webDriver);
                System.out.println("ChromeDriver and Chrome unloaded");
            }
        } catch (InterruptedException ex) {
            System.err.println("Exit error: " + ex.getMessage());
        }
    }
}

From source file:sfp.gov.py.core.CHDriver.java

License:Open Source License

private static void loadCapabilities() {
    System.setProperty("webdriver.chrome.driver", properties.getProperty("app.chromeDriver"));
    capability = DesiredCapabilities.chrome();

    HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
    chromePrefs.put("profile.default_content_settings.popups", 0);
    chromePrefs.put("download.default_directory", properties.getProperty("app.download-path"));
    chromePrefs.put("download.prompt_for_download", "false");
    chromePrefs.put("plugins.plugins_disabled", new String[] { "Adobe Flash Player", "Chrome PDF Viewer" });
    ChromeOptions options = new ChromeOptions();
    HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
    options.setExperimentalOption("prefs", chromePrefs);
    options.addArguments("--test-type");

    capability.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
    capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    capability.setCapability(ChromeOptions.CAPABILITY, options);
}