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.jitsi.meet.test.ConferenceFixture.java

License:Apache License

/**
 * Starts a <tt>WebDriver</tt> instance using default settings.
 * @param browser the browser type./*  ww  w  .ja  va2 s .c  o m*/
 * @param participant the participant we are creating a driver for.
 * @return the <tt>WebDriver</tt> instance.
 */
private static WebDriver startDriverInstance(BrowserType browser, Participant participant) {
    // by default we load chrome, but we can load safari or firefox
    if (browser == BrowserType.firefox) {
        String browserBinary = System.getProperty(BROWSER_FF_BINARY_NAME_PROP);
        if (browserBinary != null && browserBinary.trim().length() > 0) {
            File binaryFile = new File(browserBinary);
            if (binaryFile.exists())
                System.setProperty("webdriver.firefox.bin", browserBinary);
        }

        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("media.navigator.permission.disabled", true);
        // Enables tcp in firefox, disabled by default in 44
        profile.setPreference("media.peerconnection.ice.tcp", true);
        profile.setAcceptUntrustedCertificates(true);

        profile.setPreference("webdriver.log.file", FailureListener.createLogsFolder() + "/firefox-js-console-"
                + getParticipantName(participant) + ".log");

        System.setProperty("webdriver.firefox.logfile", FailureListener.createLogsFolder() + "/firefox-console-"
                + getParticipantName(participant) + ".log");

        return new FirefoxDriver(profile);
    } else if (browser == BrowserType.safari) {
        return new SafariDriver();
    } else if (browser == BrowserType.ie) {
        DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
        caps.setCapability("ignoreZoomSetting", true);
        System.setProperty("webdriver.ie.driver.silent", "true");

        return new InternetExplorerDriver(caps);
    } else {
        System.setProperty("webdriver.chrome.verboseLogging", "true");
        System.setProperty("webdriver.chrome.logfile", FailureListener.createLogsFolder() + "/chrome-console-"
                + getParticipantName(participant) + ".log");

        DesiredCapabilities caps = DesiredCapabilities.chrome();
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.ALL);
        caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

        final ChromeOptions ops = new ChromeOptions();
        ops.addArguments("use-fake-ui-for-media-stream");
        ops.addArguments("use-fake-device-for-media-stream");
        ops.addArguments("disable-extensions");
        ops.addArguments("disable-plugins");
        ops.addArguments("mute-audio");

        String disProp = System.getProperty(DISABLE_NOSANBOX_PARAM);
        if (disProp == null && !Boolean.parseBoolean(disProp)) {
            ops.addArguments("no-sandbox");
            ops.addArguments("disable-setuid-sandbox");
        }

        // starting version 46 we see crashes of chrome GPU process when
        // running in headless mode
        // which leaves the browser opened and selenium hang forever.
        // There are reports that in older version crashes like that will
        // fallback to software graphics, we try to disable gpu for now
        ops.addArguments("disable-gpu");

        String browserProp;
        if (participant == Participant.secondParticipantDriver)
            browserProp = BROWSER_CHROME_BINARY_SECOND_NAME_PROP;
        else
            browserProp = BROWSER_CHROME_BINARY_OWNER_NAME_PROP;

        String browserBinary = System.getProperty(browserProp);
        if (browserBinary != null && browserBinary.trim().length() > 0) {
            File binaryFile = new File(browserBinary);
            if (binaryFile.exists())
                ops.setBinary(binaryFile);
        }

        if (fakeStreamAudioFName != null) {
            ops.addArguments("use-file-for-fake-audio-capture=" + fakeStreamAudioFName);
        }

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

        //ops.addArguments("vmodule=\"*media/*=3,*turn*=3\"");
        ops.addArguments("enable-logging");
        ops.addArguments("vmodule=*=3");

        caps.setCapability(ChromeOptions.CAPABILITY, ops);

        try {
            final ExecutorService pool = Executors.newFixedThreadPool(1);
            // we will retry four times for 1 minute to obtain
            // the chrome driver, on headless environments chrome hangs
            // and we wait forever
            for (int i = 0; i < 2; i++) {
                Future<ChromeDriver> future = null;
                try {
                    future = pool.submit(new Callable<ChromeDriver>() {
                        @Override
                        public ChromeDriver call() throws Exception {
                            long start = System.currentTimeMillis();
                            ChromeDriver resDr = new ChromeDriver(ops);
                            System.err.println("ChromeDriver created for:"
                                    + (System.currentTimeMillis() - start) + " ms.");
                            return resDr;
                        }
                    });

                    ChromeDriver res = future.get(2, TimeUnit.MINUTES);
                    if (res != null)
                        return res;
                } catch (TimeoutException te) {
                    // cancel current task
                    if (future != null)
                        future.cancel(true);

                    System.err.println("Timeout waiting for "
                            + "chrome instance! We will retry now, this was our" + "attempt " + i);
                }

            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        // keep the old code
        System.err.println("Just create ChromeDriver, may hang!");
        return new ChromeDriver(ops);
    }
}

From source file:org.kurento.room.test.RoomTest.java

License:Open Source License

protected WebDriver newWebDriver() {
    ChromeOptions options = new ChromeOptions();

    // 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");

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

    ExecutorService webExec = Executors.newFixedThreadPool(1);
    BrowserInit initThread = new BrowserInit(capabilities);
    webExec.execute(initThread);//  w w  w .  j  ava2 s .c  o m
    webExec.shutdown();
    try {
        if (!webExec.awaitTermination(DRIVER_INIT_THREAD_TIMEOUT, TimeUnit.SECONDS)) {
            log.warn("Webdriver init thread timed-out after {}s, will be interrupted",
                    DRIVER_INIT_THREAD_TIMEOUT);
            initThread.interrupt();
            initThread.join(DRIVER_INIT_THREAD_JOIN);
        }
    } catch (InterruptedException e) {
        log.error("Interrupted exception", e);
        fail(e.getMessage());
    }

    return initThread.getBrowser();
}

From source file:org.kurento.test.browser.Browser.java

License:Apache License

private void createChromeBrowser(DesiredCapabilities capabilities) throws MalformedURLException {

    // 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());
                }/*from  w w w.j a  v a  2  s  .c  o m*/
            }
        }
    }

    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=fps=30");

        if (video != null && (isLocal() || isDocker())) {

            if (!Files.exists(Paths.get(video))) {
                throw new RuntimeException("Trying to create a browser using video file " + video
                        + ", but this file doesn't exist.");
            }

            log.debug("Using video {} in browser {}", video, id);
            options.addArguments("--use-file-for-fake-video-capture=" + video);
        }
    }

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

    createDriver(capabilities, options);
}

From source file:org.kurento.test.browser.Browser.java

License:Apache License

public void createRemoteDriver(final DesiredCapabilities capabilities) throws MalformedURLException {

    assertPublicIpNotNull();/*from   w  w w  .j  a  va 2  s.c o  m*/

    String remoteHubUrl = getProperty(SELENIUM_REMOTE_HUB_URL_PROPERTY);
    GridNode gridNode = null;

    if (remoteHubUrl == null) {

        log.debug("Creating remote webdriver for {}", id);
        if (!GridHandler.getInstance().containsSimilarBrowserKey(id)) {

            if (login != null) {
                System.setProperty(TEST_NODE_LOGIN_PROPERTY, login);
            }
            if (passwd != null) {
                System.setProperty(TEST_NODE_PASSWD_PROPERTY, passwd);
            }
            if (pem != null) {
                System.setProperty(TEST_NODE_PEM_PROPERTY, pem);
            }

            // Filtering valid nodes (just the first time will be effective)
            GridHandler.getInstance().filterValidNodes();

            if (!node.equals(host) && login != null && !login.isEmpty()
                    && (passwd != null && !passwd.isEmpty() || pem != null && !pem.isEmpty())) {
                gridNode = new GridNode(node, browserType, browserPerInstance, login, passwd, pem);
                GridHandler.getInstance().addNode(id, gridNode);
            } else {
                gridNode = GridHandler.getInstance().getRandomNodeFromList(id, browserType, browserPerInstance);
            }

            // Start Hub (just the first time will be effective)
            GridHandler.getInstance().startHub();

            // Start node
            GridHandler.getInstance().startNode(gridNode);

            // Copy video (if necessary)
            if (video != null && browserType == BrowserType.CHROME) {
                GridHandler.getInstance().copyRemoteVideo(gridNode, video);
            }

        } else {
            // Wait for node
            boolean started = false;
            do {
                gridNode = GridHandler.getInstance().getNode(id);
                if (gridNode != null) {
                    started = gridNode.isStarted();
                }
                if (!started) {
                    log.debug("Node {} is not started ... waiting 1 second", id);
                    waitSeconds(1);
                }
            } while (!started);
        }

        // At this moment we are able to use the argument for remote video
        if (video != null && browserType == BrowserType.CHROME) {
            ChromeOptions options = (ChromeOptions) capabilities.getCapability(ChromeOptions.CAPABILITY);
            options.addArguments("--use-file-for-fake-video-capture="
                    + GridHandler.getInstance().getFirstNode(id).getRemoteVideo(video));
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        }

        final int hubPort = GridHandler.getInstance().getHubPort();
        final String hubHost = GridHandler.getInstance().getHubHost();

        log.debug("Creating remote webdriver of {} ({})", id, gridNode.getHost());

        remoteHubUrl = "http://" + hubHost + ":" + hubPort + "/wd/hub";
    }

    final String remoteHub = remoteHubUrl;
    Thread t = new Thread() {
        @Override
        public void run() {
            boolean exception = false;
            do {
                try {
                    driver = new RemoteWebDriver(new URL(remoteHub), capabilities);
                    exception = false;
                } catch (MalformedURLException | WebDriverException e) {
                    log.error("Exception {} creating RemoteWebDriver ... retrying in 1 second", e.getClass());
                    waitSeconds(1);
                    exception = true;
                }
            } while (exception);
        }
    };
    t.start();

    int timeout = getProperty(SELENIUM_REMOTEWEBDRIVER_TIME_PROPERTY, SELENIUM_REMOTEWEBDRIVER_TIME_DEFAULT);
    String nodeMsg = gridNode != null ? " (" + gridNode.getHost() + ")" : "";

    for (int i = 0; i < timeout; i++) {
        if (t.isAlive()) {
            log.debug("Waiting for RemoteWebDriver {}{}", id, nodeMsg);
        } else {
            log.debug("Remote webdriver of {}{} created", id, nodeMsg);
            return;
        }
        waitSeconds(1);
    }

    String exceptionMessage = "Remote webdriver of " + id + nodeMsg + " not created in " + timeout + "seconds";
    log.error(">>>>>>>>>> " + exceptionMessage);
    throw new RuntimeException(exceptionMessage);
}

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

License:Open Source License

public void init() {

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

    try {/* www. j a  v a2 s.  c om*/
        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.test.client.BrowserClient.java

License:Open Source License

public void createRemoteDriver(DesiredCapabilities capabilities) throws MalformedURLException {
    assertPublicIpNotNull();/*w w  w.j  a  v a2  s . c o  m*/
    if (!GridHandler.getInstance().containsSimilarBrowserKey(id)) {
        GridNode gridNode = null;

        if (login != null) {
            System.setProperty(TEST_NODE_LOGIN_PROPERTY, login);
        }
        if (passwd != null) {
            System.setProperty(TEST_NODE_PASSWD_PROPERTY, passwd);
        }
        if (pem != null) {
            System.setProperty(TEST_NODE_PEM_PROPERTY, pem);
        }

        if (!node.equals(host) && login != null && !login.isEmpty()
                && (passwd != null && !passwd.isEmpty() || pem != null && !pem.isEmpty())) {
            gridNode = new GridNode(node, browserType, browserPerInstance, login, passwd, pem);
            GridHandler.getInstance().addNode(id, gridNode);
        } else {
            gridNode = GridHandler.getInstance().getRandomNodeFromList(id, browserType, browserPerInstance);
        }

        // Start Hub (just the first time will be effective)
        GridHandler.getInstance().startHub();

        // Start node
        GridHandler.getInstance().startNode(gridNode);

        // Copy video (if necessary)
        if (video != null && browserType == BrowserType.CHROME) {
            GridHandler.getInstance().copyRemoteVideo(gridNode, video);
        }

    }

    // At this moment we are able to use the argument for remote video
    if (video != null && browserType == BrowserType.CHROME) {
        ChromeOptions options = (ChromeOptions) capabilities.getCapability(ChromeOptions.CAPABILITY);
        options.addArguments("--use-file-for-fake-video-capture="
                + GridHandler.getInstance().getFirstNode(id).getRemoteVideo(video));
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    }

    int hubPort = GridHandler.getInstance().getHubPort();
    String hubHost = GridHandler.getInstance().getHubHost();

    driver = new RemoteWebDriver(new URL("http://" + hubHost + ":" + hubPort + "/wd/hub"), capabilities);
}

From source file:org.me.seleniumGridUI.SeleniumGridOperation.java

public static DesiredCapabilities CreateBrowserCapbility(String browser) {
    DesiredCapabilities caps = null;/*from  w  ww .ja  v a2s . c o  m*/
    if (browser.equalsIgnoreCase("firefox")) {
        caps = DesiredCapabilities.firefox();
    } else if (browser.equalsIgnoreCase("chrome")) {
        caps = DesiredCapabilities.chrome();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-popup-blocking");
        options.addArguments("disable-prompt-on-repost");
        options.addArguments("whitelist-ips");
        options.addArguments("no-first-run");
        options.addArguments("disk-cache-size=1");
        options.addArguments("media-cache-size=1");
        options.addArguments("test-type");
        caps.setCapability(ChromeOptions.CAPABILITY, options);
    } else if (browser.equalsIgnoreCase("ie")) {
        caps = DesiredCapabilities.internetExplorer();
        caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        caps.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, true);
        caps.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
        caps.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);
        caps.setCapability(InternetExplorerDriver.NATIVE_EVENTS, false);
        caps.setCapability(InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR, UnexpectedAlertBehaviour.DISMISS);
    } else if (browser.equalsIgnoreCase("phantomjs")) {
        caps = DesiredCapabilities.phantomjs();
    } else if (browser.equalsIgnoreCase("safari")) {
        caps = DesiredCapabilities.safari();
    } else if (browser.equalsIgnoreCase("iphone")) {
        caps = DesiredCapabilities.iphone();
    } else if (browser.equalsIgnoreCase("ipad")) {
        caps = DesiredCapabilities.ipad();
    } else {
        caps = DesiredCapabilities.htmlUnit();
    }
    return caps;
}

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 .jav a  2s .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));
            }
        }
    }
    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;
        }/*from  w  w  w .j  a v  a2s.  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.safs.selenium.webdriver.lib.SelectBrowser.java

License:Open Source License

/**
 * /*from  w  w w . j  ava 2s.  co  m*/
 * @param browserName String, the browser name, such as "explorer"
 * @param extraParameters Map<String,Object>, can be used to pass more browser parameters, such as proxy settings.
 * @return DesiredCapabilities
 */
public static DesiredCapabilities getDesiredCapabilities(String browserName,
        Map<String, Object> extraParameters) {
    String debugmsg = StringUtils.debugmsg(false);
    DesiredCapabilities caps = null;

    if (browserName.equals(BROWSER_NAME_IE)) {
        System.setProperty(SYSTEM_PROPERTY_WEBDRIVER_IE, "IEDriverServer.exe");
        caps = DesiredCapabilities.internetExplorer();
        caps.setCapability("nativeEvents", true);
        caps.setCapability("requireWindowFocus", true);
        //caps.setCapability("browserName", BROWSER_NAME_IE);
    } else if (browserName.equals(BROWSER_NAME_CHROME)) {
        System.setProperty(SYSTEM_PROPERTY_WEBDRIVER_CHROME, "chromedriver.exe");
        caps = DesiredCapabilities.chrome();

        // Disable extensions to avoid popping up 'Disable developer mode extensions' message by default.
        if (!extraParameters.containsKey(KEY_CHROME_DISABLE_EXTENSIONS)) {
            // Only execute if no user's setting
            extraParameters.put(KEY_CHROME_DISABLE_EXTENSIONS, "true");
        }

        //caps.setCapability("browserName", BROWSER_NAME_CHROME);
    } else if (browserName.equals(BROWSER_NAME_EDGE)) {
        System.setProperty(SYSTEM_PROPERTY_WEBDRIVER_EDGE, "MicrosoftWebDriver.exe");
        caps = DesiredCapabilities.edge();
        //caps.setCapability("browserName", BROWSER_NAME_EDGE);
    } else if (browserName.equals(BROWSER_NAME_ANDROID_CHROME)) {
        System.setProperty(SYSTEM_PROPERTY_WEBDRIVER_CHROME, "chromedriver.exe");
        caps = DesiredCapabilities.chrome();
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setExperimentalOption("androidPackage", "com.android.chrome");
        caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
        caps.setCapability(CapabilityType.BROWSER_NAME, BROWSER_NAME_CHROME);
    } else if (browserName.equals(BROWSER_NAME_IPAD_SIMULATOR_SAFARI)) {
        caps = new DesiredCapabilities();
        caps.setCapability("device", "ipad");
        caps.setCapability("simulator", "true");
        caps.setCapability(CapabilityType.BROWSER_NAME, "safari");
    } else { // default browser always
        caps = DesiredCapabilities.firefox();
        caps.setCapability(CapabilityType.BROWSER_NAME, BROWSER_NAME_FIREFOX);
    }

    String unexpectedAlertBehaviour = Processor.getUnexpectedAlertBehaviour();
    if (unexpectedAlertBehaviour == null)
        unexpectedAlertBehaviour = System
                .getProperty(DriverConstant.PROERTY_SAFS_TEST_UNEXPECTEDALERTBEHAVIOUR);
    if (unexpectedAlertBehaviour != null) {
        IndependantLog.debug(debugmsg + " Set '" + unexpectedAlertBehaviour + "' to '"
                + CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR + "'.");
        caps.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, unexpectedAlertBehaviour);
    }

    if (extraParameters != null && !extraParameters.isEmpty()) {
        //1. Add http proxy settings to Capabilities, if they exist 
        Object proxysetting = extraParameters.get(KEY_PROXY_SETTING);
        if (proxysetting != null && proxysetting instanceof String) {
            org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
            proxy.setHttpProxy(proxysetting.toString());

            Object bypass = extraParameters.get(KEY_PROXY_BYPASS_ADDRESS);
            if (bypass != null && bypass instanceof String) {
                proxy.setNoProxy(bypass.toString());
            }

            caps.setCapability(CapabilityType.PROXY, proxy);
        }

        //2 Add firefox profile setting to Capabilities.
        if (BROWSER_NAME_FIREFOX.equals(browserName)) {
            //2.1 Add firefox profile setting to Capabilities, if it exists
            FirefoxProfile firefoxProfile = null;
            Object firefoxProfileParam = extraParameters.get(KEY_FIREFOX_PROFILE);
            if (firefoxProfileParam != null && firefoxProfileParam instanceof String) {
                //Can be profile's name or profile's file name
                String profileNameOrPath = firefoxProfileParam.toString();
                IndependantLog.debug(
                        debugmsg + "Try to Set firefox profile '" + profileNameOrPath + "' to Capabilities.");

                firefoxProfile = getFirefoxProfile(profileNameOrPath);

                if (firefoxProfile != null) {
                    caps.setCapability(KEY_FIREFOX_PROFILE, profileNameOrPath);//used to store in session file
                } else {
                    IndependantLog.error(debugmsg + " Fail to set firefox profile to Capabilities.");
                }
            }
            //2.2 Add firefox profile preferences to Capabilities, if it exists
            Object prefsFileParam = extraParameters.get(KEY_FIREFOX_PROFILE_PREFERENCE);
            if (prefsFileParam != null && prefsFileParam instanceof String) {
                String preferenceFile = prefsFileParam.toString();
                IndependantLog.debug(debugmsg + "Try to Set firefox preference file '" + preferenceFile
                        + "' to Firefox Profile.");
                caps.setCapability(KEY_FIREFOX_PROFILE_PREFERENCE, preferenceFile);//used to store in session file

                Map<?, ?> firefoxPreference = Json.readJSONFileUTF8(preferenceFile);
                if (firefoxProfile == null)
                    firefoxProfile = new FirefoxProfile();
                addFireFoxPreference(firefoxProfile, firefoxPreference);
            }

            if (firefoxProfile != null) {
                caps.setCapability(FirefoxDriver.PROFILE, firefoxProfile);
            }
        }

        //3. Add chrome-options-settings to Capabilities.
        if (BROWSER_NAME_CHROME.equals(browserName) || BROWSER_NAME_ANDROID_CHROME.equals(browserName)) {
            setChromeCapabilities(caps, extraParameters);
        }

        //put extra grid-nodes information
        Object gridnodes = extraParameters.get(KEY_GRID_NODES_SETTING);
        if (gridnodes != null && gridnodes instanceof String) {
            caps.setCapability(KEY_GRID_NODES_SETTING, gridnodes);
        }
    }

    return caps;
}