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

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

Introduction

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

Prototype

public ChromeDriver(ChromeOptions options) 

Source Link

Document

Creates a new ChromeDriver instance with the specified options.

Usage

From source file:org.kurento.test.client.BrowserClient.java

License:Open Source License

public void init() {

    Class<? extends WebDriver> driverClass = browserType.getDriverClass();

    try {/*  w  w  w . j a  v a  2 s . c  o  m*/
        DesiredCapabilities capabilities = new DesiredCapabilities();

        if (driverClass.equals(FirefoxDriver.class)) {
            FirefoxProfile profile = new FirefoxProfile();
            // This flag avoids granting the access to the camera
            profile.setPreference("media.navigator.permission.disabled", true);

            capabilities.setCapability(FirefoxDriver.PROFILE, profile);
            capabilities.setBrowserName(DesiredCapabilities.firefox().getBrowserName());

            // Firefox extensions
            if (extensions != null && !extensions.isEmpty()) {
                for (Map<String, String> extension : extensions) {
                    InputStream is = getExtensionAsInputStream(extension.values().iterator().next());
                    if (is != null) {
                        try {
                            File xpi = File.createTempFile(extension.keySet().iterator().next(), ".xpi");
                            FileUtils.copyInputStreamToFile(is, xpi);
                            profile.addExtension(xpi);
                        } catch (Throwable t) {
                            log.error("Error loading Firefox extension {} ({} : {})", extension, t.getClass(),
                                    t.getMessage());
                        }
                    }
                }
            }

            if (scope == BrowserScope.SAUCELABS) {
                createSaucelabsDriver(capabilities);
            } else if (scope == BrowserScope.REMOTE) {
                createRemoteDriver(capabilities);
            } else {
                driver = new FirefoxDriver(profile);
            }

        } else if (driverClass.equals(ChromeDriver.class)) {
            // Chrome driver
            ChromeDriverManager.getInstance().setup();

            // Chrome options
            ChromeOptions options = new ChromeOptions();

            // Chrome extensions
            if (extensions != null && !extensions.isEmpty()) {
                for (Map<String, String> extension : extensions) {
                    InputStream is = getExtensionAsInputStream(extension.values().iterator().next());
                    if (is != null) {
                        try {
                            File crx = File.createTempFile(extension.keySet().iterator().next(), ".crx");
                            FileUtils.copyInputStreamToFile(is, crx);
                            options.addExtensions(crx);
                        } catch (Throwable t) {
                            log.error("Error loading Chrome extension {} ({} : {})", extension, t.getClass(),
                                    t.getMessage());
                        }
                    }
                }
            }

            if (enableScreenCapture) {
                // This flag enables the screen sharing
                options.addArguments("--enable-usermedia-screen-capturing");

                String windowTitle = TEST_SCREEN_SHARE_TITLE_DEFAULT;
                if (platform != null && (platform == Platform.WINDOWS || platform == Platform.XP
                        || platform == Platform.VISTA || platform == Platform.WIN8
                        || platform == Platform.WIN8_1)) {

                    windowTitle = TEST_SCREEN_SHARE_TITLE_DEFAULT_WIN;
                }
                options.addArguments("--auto-select-desktop-capture-source="
                        + getProperty(TEST_SCREEN_SHARE_TITLE_PROPERTY, windowTitle));

            } else {
                // This flag avoids grant the camera
                options.addArguments("--use-fake-ui-for-media-stream");
            }

            // This flag avoids warning in Chrome. See:
            // https://code.google.com/p/chromedriver/issues/detail?id=799
            options.addArguments("--test-type");

            if (protocol == Protocol.FILE) {
                // This flag allows reading local files in video tags
                options.addArguments("--allow-file-access-from-files");
            }

            if (!usePhysicalCam) {
                // This flag makes using a synthetic video (green with
                // spinner) in WebRTC. Or it is needed to combine with
                // use-file-for-fake-video-capture to use a file faking the
                // cam
                options.addArguments("--use-fake-device-for-media-stream");

                if (video != null && isLocal()) {
                    options.addArguments("--use-file-for-fake-video-capture=" + video);
                }
            }

            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            capabilities.setBrowserName(DesiredCapabilities.chrome().getBrowserName());

            if (scope == BrowserScope.SAUCELABS) {
                createSaucelabsDriver(capabilities);
            } else if (scope == BrowserScope.REMOTE) {
                createRemoteDriver(capabilities);
            } else {
                driver = new ChromeDriver(options);
            }
        } else if (driverClass.equals(InternetExplorerDriver.class)) {

            if (scope == BrowserScope.SAUCELABS) {
                capabilities.setBrowserName(DesiredCapabilities.internetExplorer().getBrowserName());
                capabilities.setCapability("ignoreProtectedModeSettings", true);
                createSaucelabsDriver(capabilities);
            }

        } else if (driverClass.equals(SafariDriver.class)) {

            if (scope == BrowserScope.SAUCELABS) {
                capabilities.setBrowserName(DesiredCapabilities.safari().getBrowserName());
                createSaucelabsDriver(capabilities);
            }

        }

        // Timeouts
        changeTimeout(timeout);

        if (protocol == Protocol.FILE) {
            String clientPage = client.toString();
            File clientPageFile = new File(
                    this.getClass().getClassLoader().getResource("static" + clientPage).getFile());
            url = protocol.toString() + clientPageFile.getAbsolutePath();
        } else {
            String hostName = host != null ? host : node;
            url = protocol.toString() + hostName + ":" + serverPort + client.toString();
        }
        log.info("*** Browsing URL with WebDriver: {}", url);
        driver.get(url);

    } catch (MalformedURLException e) {
        log.error("MalformedURLException in BrowserClient.initDriver", e);
    }

    // startPing();
}

From source file:org.kurento.tutorial.magicmirror.test.MagicMirrorIT.java

License:Open Source License

@Before
public void setup() {
    ChromeOptions options = new ChromeOptions();
    // This flag avoids a warning in Chrome. See:
    // https://code.google.com/p/chromedriver/issues/detail?id=799
    options.addArguments("--test-type");
    // This flag avoids granting camera/microphone
    options.addArguments("--use-fake-ui-for-media-stream");
    // This flag makes using a synthetic video (green with spinner) in
    // WebRTC instead of real media from camera/microphone
    options.addArguments("--use-fake-device-for-media-stream");

    driver = new ChromeDriver(options);
}

From source file:org.mozilla.zest.core.v1.ZestClientLaunch.java

License:Mozilla Public License

@Override
public String invoke(ZestRuntime runtime) throws ZestClientFailException {

    try {/*from   w  w w. java 2s .  c o m*/
        WebDriver driver = null;
        DesiredCapabilities cap = new DesiredCapabilities();

        String httpProxy = runtime.getProxy();
        if (httpProxy.length() > 0) {
            Proxy proxy = new Proxy();
            proxy.setHttpProxy(httpProxy);
            proxy.setSslProxy(httpProxy);
            cap.setCapability(CapabilityType.PROXY, proxy);
        }
        if (capabilities != null) {
            for (String capability : capabilities.split("\n")) {
                if (capability != null && capability.trim().length() > 0) {
                    String[] typeValue = capability.split("=");
                    if (typeValue.length != 2) {
                        throw new ZestClientFailException(this,
                                "Invalid capability, expected type=value : " + capability);
                    }
                    cap.setCapability(typeValue[0], typeValue[1]);
                }
            }
        }

        if ("Firefox".equalsIgnoreCase(this.browserType)) {
            driver = new FirefoxDriver(cap);
        } else if ("Chrome".equalsIgnoreCase(this.browserType)) {
            driver = new ChromeDriver(cap);
        } else if ("HtmlUnit".equalsIgnoreCase(this.browserType)) {
            driver = new HtmlUnitDriver(DesiredCapabilities.htmlUnit().merge(cap));
        } else if ("InternetExplorer".equalsIgnoreCase(this.browserType)) {
            driver = new InternetExplorerDriver(cap);
        } else if ("Opera".equalsIgnoreCase(this.browserType)) {
            driver = new OperaDriver(cap);
        } else if ("PhantomJS".equalsIgnoreCase(this.browserType)) {
            driver = new PhantomJSDriver(cap);
        } else if ("Safari".equalsIgnoreCase(this.browserType)) {
            driver = new SafariDriver(cap);
        } else {
            // See if its a class name
            try {
                Class<?> browserClass = this.getClass().getClassLoader().loadClass(this.browserType);
                Constructor<?> cons = browserClass.getConstructor(Capabilities.class);
                if (cons != null) {
                    driver = (WebDriver) cons.newInstance(cap);
                } else {
                    throw new ZestClientFailException(this,
                            "Unsupported browser type: " + this.getBrowserType());
                }
            } catch (ClassNotFoundException e) {
                throw new ZestClientFailException(this, "Unsupported browser type: " + this.getBrowserType());
            }
        }

        runtime.addWebDriver(getWindowHandle(), driver);

        if (this.url != null) {
            driver.get(runtime.replaceVariablesInString(this.url, true));
        }

        return getWindowHandle();

    } catch (Exception e) {
        throw new ZestClientFailException(this, e);
    }
}

From source file:org.musetest.selenium.providers.ChromeDriverProvider.java

License:Open Source License

@Override
public WebDriver getDriver(SeleniumBrowserCapabilities capabilities, MuseExecutionContext context) {
    if (getOs() != null && !(OperatingSystem.get().equals(getOs())))
        return null; // this provider is not for the current OS

    if (!capabilities.getName().equals(BrowserType.CHROME))
        return null;

    File path = getDriverLocation(context);
    if (path == null) {
        context.raiseEvent(MessageEventType.create(
                "ChromeDriverProvider would try to satisfy request for Chrome browser, but it was not configured with a path to the driver"));
        return null;
    }/*from ww w. ja  v a  2s .  c o m*/

    if (!(path.exists())) {
        context.raiseEvent(MessageEventType.create(
                "ChromeDriverProvider would try to satisfy request for Chrome browser, but the configured path does not exist: "
                        + path.getAbsolutePath()));
        return null;
    }

    synchronized (ChromeDriverProvider.class) {
        ChromeOptions options = new ChromeOptions();
        if (getArguments() != null)
            options.addArguments(getArguments());

        DesiredCapabilities desired = DesiredCapabilities.chrome();
        if (capabilities.getVersion() != null && capabilities.getVersion().length() > 0)
            desired.setVersion(capabilities.getVersion());
        if (capabilities.getPlatform() != null && capabilities.getPlatform().length() > 0)
            desired.setPlatform(Platform.fromString(capabilities.getPlatform()));
        options.merge(desired);

        System.setProperty("webdriver.chrome.driver", path.getAbsolutePath());
        return new ChromeDriver(options);
    }
}

From source file:org.nuxeo.functionaltests.AbstractTest.java

License:Open Source License

@SuppressWarnings("deprecation")
protected static void initChromeDriver() throws Exception {
    if (System.getProperty(SYSPROP_CHROME_DRIVER_PATH) == null) {
        String chromeDriverDefaultPath = null;
        String chromeDriverExecutableName = CHROME_DRIVER_DEFAULT_EXECUTABLE_NAME;
        if (SystemUtils.IS_OS_LINUX) {
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_LINUX;
        } else if (SystemUtils.IS_OS_MAC) {
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_MAC;
        } else if (SystemUtils.IS_OS_WINDOWS_XP) {
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_WINXP;
            chromeDriverExecutableName = CHROME_DRIVER_WINDOWS_EXECUTABLE_NAME;
        } else if (SystemUtils.IS_OS_WINDOWS_VISTA) {
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_WINVISTA;
            chromeDriverExecutableName = CHROME_DRIVER_WINDOWS_EXECUTABLE_NAME;
        } else if (SystemUtils.IS_OS_WINDOWS) {
            // Unknown default path on other Windows OS. To be completed.
            chromeDriverExecutableName = CHROME_DRIVER_WINDOWS_EXECUTABLE_NAME;
        }//from  w w  w  .  ja va  2  s  .co m

        if (chromeDriverDefaultPath != null && new File(chromeDriverDefaultPath).exists()) {
            log.warn(String.format("Missing property %s but found %s. Using it...", SYSPROP_CHROME_DRIVER_PATH,
                    chromeDriverDefaultPath));
            System.setProperty(SYSPROP_CHROME_DRIVER_PATH, chromeDriverDefaultPath);
        } else {
            // Can't find chromedriver in default location, check system
            // path
            File chromeDriverExecutable = findExecutableOnPath(chromeDriverExecutableName);
            if ((chromeDriverExecutable != null) && (chromeDriverExecutable.exists())) {
                log.warn(String.format("Missing property %s but found %s. Using it...",
                        SYSPROP_CHROME_DRIVER_PATH, chromeDriverExecutable.getCanonicalPath()));
                System.setProperty(SYSPROP_CHROME_DRIVER_PATH, chromeDriverExecutable.getCanonicalPath());
            } else {
                log.error(String.format(
                        "Could not find the Chrome driver looking at %s or system path."
                                + " Download it from %s and set its path with " + "the System property %s.",
                        chromeDriverDefaultPath, "http://code.google.com/p/chromedriver/downloads/list",
                        SYSPROP_CHROME_DRIVER_PATH));
            }
        }
    }
    DesiredCapabilities dc = DesiredCapabilities.chrome();
    ChromeOptions options = new ChromeOptions();
    options.addArguments(Arrays.asList("--ignore-certificate-errors"));
    Proxy proxy = startProxy();
    if (proxy != null) {
        proxy.setNoProxy("");
        dc.setCapability(CapabilityType.PROXY, proxy);
    }
    dc.setCapability(ChromeOptions.CAPABILITY, options);
    driver = new ChromeDriver(dc);
}

From source file:org.nuxeo.functionaltests.drivers.ChromeDriverProvider.java

License:Open Source License

@Override
public RemoteWebDriver init(DesiredCapabilities dc) throws Exception {
    if (System.getProperty(SYSPROP_CHROME_DRIVER_PATH) == null) {
        String chromeDriverDefaultPath = null;
        String chromeDriverExecutableName = CHROME_DRIVER_DEFAULT_EXECUTABLE_NAME;
        if (SystemUtils.IS_OS_LINUX) {
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_LINUX;
        } else if (SystemUtils.IS_OS_MAC) {
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_MAC;
        } else if (SystemUtils.IS_OS_WINDOWS_XP) {
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_WINXP;
            chromeDriverExecutableName = CHROME_DRIVER_WINDOWS_EXECUTABLE_NAME;
        } else if (SystemUtils.IS_OS_WINDOWS_VISTA) {
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_WINVISTA;
            chromeDriverExecutableName = CHROME_DRIVER_WINDOWS_EXECUTABLE_NAME;
        } else if (SystemUtils.IS_OS_WINDOWS) {
            // Unknown default path on other Windows OS. To be completed.
            chromeDriverDefaultPath = CHROME_DRIVER_DEFAULT_PATH_WINVISTA;
            chromeDriverExecutableName = CHROME_DRIVER_WINDOWS_EXECUTABLE_NAME;
        }// w  ww  . ja v a2 s. c o m

        if (chromeDriverDefaultPath != null && new File(chromeDriverDefaultPath).exists()) {
            log.warn(String.format("Missing property %s but found %s. Using it...", SYSPROP_CHROME_DRIVER_PATH,
                    chromeDriverDefaultPath));
            System.setProperty(SYSPROP_CHROME_DRIVER_PATH, chromeDriverDefaultPath);
        } else {
            // Can't find chromedriver in default location, check system
            // path
            File chromeDriverExecutable = findExecutableOnPath(chromeDriverExecutableName);
            if ((chromeDriverExecutable != null) && (chromeDriverExecutable.exists())) {
                log.warn(String.format("Missing property %s but found %s. Using it...",
                        SYSPROP_CHROME_DRIVER_PATH, chromeDriverExecutable.getCanonicalPath()));
                System.setProperty(SYSPROP_CHROME_DRIVER_PATH, chromeDriverExecutable.getCanonicalPath());
            } else {
                log.error(String.format(
                        "Could not find the Chrome driver looking at %s or system path."
                                + " Download it from %s and set its path with " + "the System property %s.",
                        chromeDriverDefaultPath, "http://code.google.com/p/chromedriver/downloads/list",
                        SYSPROP_CHROME_DRIVER_PATH));
            }
        }
    }
    ChromeOptions options = new ChromeOptions();
    options.addArguments(Arrays.asList("--ignore-certificate-errors"));
    dc.setCapability(ChromeOptions.CAPABILITY, options);
    driver = new ChromeDriver(dc);
    return driver;
}

From source file:org.nvonop.selenium.framework.Browser.java

License:Open Source License

/**
 * This method initialises the ThreadLocal WebDriver object according to the
 * supplied parameters to enable tests to run on a users local machine.
 */// www  .  j a va2  s  .com
private void setLocalWebdriver() {

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setJavascriptEnabled(true);
    capabilities.setCapability("handlesAlerts", true);
    switch (getBrowserId(browser)) {
    case 0:
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
                Boolean.valueOf(System.getProperty("IGNORE_SECURITY_DOMAINS", "false")));
        driver.set(new InternetExplorerDriver(capabilities));
        break;
    case 1:
        driver.set(new FirefoxDriver(capabilities));
        break;
    case 2:
        driver.set(new SafariDriver(capabilities));
        break;
    case 3:
        driver.set(new ChromeDriver(capabilities));
        break;
    default:
        throw new WebDriverException("Browser not found: " + browser);
    }
}

From source file:org.nvonop.selenium.framework.utilities.BaseTest.java

License:Open Source License

/**
 * This method initialises the ThreadLocal WebDriver object according to the
 * supplied parameters to enable tests to run on a users local machine.
 *
 * @param browser  This can be set to "chrome", "internet explorer" or "firefox"
 * @param version  This should be set to reflect the browser required. It is only
 *                 used when matching capabilities for a RemoteWebDriver object
 *                 however./*from  w  w w. j  av a 2  s. c  o m*/
 * @param platform This should be set to whatever platform the test is required
 *                 to run on e.g. "WINDOWS", "MAC", "LINUX". It is only used when
 *                 matching capabilities for a RemoteWebDriver object however.
 */
public void setLocalWebdriver(String browser, String version, String platform) {

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setJavascriptEnabled(true);
    capabilities.setCapability("handlesAlerts", true);
    switch (getBrowserId(browser)) {
    case 0:
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
                Boolean.valueOf(System.getProperty("IGNORE_SECURITY_DOMAINS", "false")));
        driver.set(new InternetExplorerDriver(capabilities));
        break;
    case 1:
        driver.set(new FirefoxDriver(capabilities));
        break;
    case 2:
        driver.set(new SafariDriver(capabilities));
        break;
    case 3:
        driver.set(new ChromeDriver(capabilities));
        break;
    default:
        throw new WebDriverException("Browser not found: " + browser);
    }
}

From source file:org.openlmis.UiUtils.DriverFactory.java

License:Open Source License

private WebDriver createChromeDriver() {
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();

    Map<String, String> prefs = new Hashtable<>();
    prefs.put("download.prompt_for_download", "false");
    prefs.put("download.default_directory", "C:\\Users\\openlmis\\Downloads");

    String[] switches = { "--start-maximized", "--ignore-certificate-errors" };
    capabilities.setJavascriptEnabled(true);
    capabilities.setCapability("chrome.prefs", prefs);
    capabilities.setCapability("chrome.switches", Arrays.asList(switches));

    return new ChromeDriver(capabilities);
}

From source file:org.paxml.selenium.webdriver.NewSessionTag.java

License:Open Source License

private WebDriver createWebDriver(Context context) {
    Proxy proxy = new Proxy();
    if (StringUtils.isNotBlank(proxyHttp)) {
        proxy.setHttpProxy(proxyHttp);//from w w  w .java2s .  c  om
    }
    if (StringUtils.isNotBlank(proxyFtp)) {
        proxy.setFtpProxy(proxyFtp);
    }
    if (StringUtils.isNotBlank(proxySsl)) {
        proxy.setSslProxy(proxySsl);
    }
    if (StringUtils.isNotBlank(proxyAutoConfigUrl)) {
        proxy.setProxyAutoconfigUrl(proxyAutoConfigUrl);
    }
    if (proxyAutoDetect != null) {
        proxy.setAutodetect(proxyAutoDetect);
    }

    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability(CapabilityType.PROXY, proxy);
    cap.setJavascriptEnabled(true);

    if (StringUtils.isNotBlank(hub)) {
        final URL url;
        try {
            url = new URL(hub);
        } catch (MalformedURLException e) {
            throw new RuntimeException("hub url is invalid: " + hub, e);
        }
        if ("firefox".equalsIgnoreCase(browser)) {
            cap = cap.firefox();
        } else if ("iexplore".equalsIgnoreCase(browser)) {
            cap = cap.internetExplorer();
        } else if ("chrome".equalsIgnoreCase(browser)) {
            cap = cap.chrome();
        }
        return new RemoteWebDriver(url, cap);
    }

    if ("firefox".equalsIgnoreCase(browser)) {
        return new FirefoxDriver(cap);
    }
    if ("iexplore".equalsIgnoreCase(browser)) {
        return new InternetExplorerDriver(cap);
    }
    if ("chrome".equalsIgnoreCase(browser)) {
        return new ChromeDriver(cap);
    }

    throw new RuntimeException("unknown browser type: " + browser);

}