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.apache.portals.pluto.test.utilities.SimpleTestDriver.java

License:Apache License

/**
 * @throws java.lang.Exception/*  w w w . j a  v  a2s  . c  o m*/
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    if (driver == null) {
        loginUrl = System.getProperty("test.server.login.url");
        host = System.getProperty("test.server.host");
        port = System.getProperty("test.server.port");
        username = System.getProperty("test.server.username");
        usernameId = System.getProperty("test.server.username.id");
        password = System.getProperty("test.server.password");
        passwordId = System.getProperty("test.server.password.id");
        browser = System.getProperty("test.browser");
        testContextBase = System.getProperty("test.context.base");
        StringBuilder sb = new StringBuilder();
        sb.append("http://");
        sb.append(host);
        if (port != null && !port.isEmpty()) {
            sb.append(":");
            sb.append(port);
        }
        sb.append("/");
        sb.append(testContextBase);
        baseUrl = sb.toString();
        String str = System.getProperty("test.url.strategy");
        useGeneratedUrl = str.equalsIgnoreCase("generateURLs");
        str = System.getProperty("test.debug");
        debug = str.equalsIgnoreCase("true");
        str = System.getProperty("test.timeout");
        dryrun = Boolean.valueOf(System.getProperty("test.dryrun"));
        timeout = ((str != null) && str.matches("\\d+")) ? Integer.parseInt(str) : 3;
        String wd = System.getProperty("test.browser.webDriver");
        String binary = System.getProperty("test.browser.binary");
        String headlessProperty = System.getProperty("test.browser.headless");
        boolean headless = (((headlessProperty == null) || (headlessProperty.length() == 0)
                || Boolean.valueOf(headlessProperty)));
        String maximizedProperty = System.getProperty("test.browser.maximized");
        boolean maximized = Boolean.valueOf(maximizedProperty);

        System.out.println("before class.");
        System.out.println("   Debug        =" + debug);
        System.out.println("   Dryrun       =" + dryrun);
        System.out.println("   Timeout      =" + timeout);
        System.out.println("   Login URL    =" + loginUrl);
        System.out.println("   Host         =" + host);
        System.out.println("   Port         =" + port);
        System.out.println("   Context      =" + testContextBase);
        System.out.println("   Generate URL =" + useGeneratedUrl);
        System.out.println("   Username     =" + username);
        System.out.println("   UsernameId   =" + usernameId);
        System.out.println("   Password     =" + password);
        System.out.println("   PasswordId   =" + passwordId);
        System.out.println("   Browser      =" + browser);
        System.out.println("   Driver       =" + wd);
        System.out.println("   binary       =" + binary);
        System.out.println("   headless     =" + headless);
        System.out.println("   maximized    =" + maximized);

        if (browser.equalsIgnoreCase("firefox")) {

            System.setProperty("webdriver.gecko.driver", wd);
            FirefoxOptions options = new FirefoxOptions();
            options.setLegacy(true);
            options.setAcceptInsecureCerts(true);

            if ((binary != null) && (binary.length() != 0)) {
                options.setBinary(binary);
            }

            if (headless) {
                options.setHeadless(true);
            }

            driver = new FirefoxDriver(options);

        } else if (browser.equalsIgnoreCase("internetExplorer")) {
            System.setProperty("webdriver.ie.driver", wd);
            driver = new InternetExplorerDriver();
        } else if (browser.equalsIgnoreCase("chrome")) {

            System.setProperty("webdriver.chrome.driver", wd);
            ChromeOptions options = new ChromeOptions();

            if ((binary != null) && (binary.length() > 0)) {
                options.setBinary(binary);
            }

            if (headless) {
                options.addArguments("--headless");
            }

            options.addArguments("--disable-infobars");
            options.setAcceptInsecureCerts(true);

            if (maximized) {
                // The webDriver.manage().window().maximize() feature does not work correctly in headless mode, so set the
                // window size to 1920x1200 (resolution of a 15.4 inch screen).
                options.addArguments("--window-size=1920,1200");
            }

            driver = new ChromeDriver(options);

        } else if (browser.equalsIgnoreCase("phantomjs")) {
            DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
            capabilities.setJavascriptEnabled(true);
            capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, binary);
            driver = new PhantomJSDriver(capabilities);
        } else if (browser.equalsIgnoreCase("htmlUnit")) {
            LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log",
                    "org.apache.commons.logging.impl.NoOpLog");
            Logger.getLogger("com.gargoylesoftware").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.SEVERE);
            driver = new HtmlUnitDriver() {
                @Override
                protected WebClient getWebClient() {
                    WebClient webClient = super.getWebClient();
                    WebClientOptions options = webClient.getOptions();
                    options.setThrowExceptionOnFailingStatusCode(false);
                    options.setThrowExceptionOnScriptError(false);
                    options.setPrintContentOnFailingStatusCode(false);
                    webClient.setCssErrorHandler(new SilentCssErrorHandler());
                    return webClient;
                }
            };
        } else if (browser.equalsIgnoreCase("safari")) {
            driver = new SafariDriver();
        } else {
            throw new Exception("Unsupported browser: " + browser);
        }

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                driver.quit();
            }
        }));

        if (maximized) {
            driver.manage().window().maximize();
        }

        if (!dryrun) {
            login();
        }
    }
}

From source file:org.codehaus.mojo.screenshot.ScreenshotMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    System.setProperty("webdriver.chrome.driver", chromeDriverPath);
    webDriverMap = new HashMap<String, WebDriver>();
    final DesiredCapabilities firefoxCapabilities = DesiredCapabilities.firefox();
    firefoxCapabilities.setJavascriptEnabled(true);
    WebDriver firefoxDriver = new FirefoxDriver(firefoxCapabilities);
    firefoxDriver.manage().window().maximize();
    webDriverMap.put("firefox", firefoxDriver);
    final DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
    ieCapabilities.setJavascriptEnabled(true);
    WebDriver ieDriver = new InternetExplorerDriver(ieCapabilities);
    ieDriver.manage().window().maximize();
    webDriverMap.put("ie", ieDriver);
    final ChromeOptions chromeOptions = new ChromeOptions();
    WebDriver chromeDriver = new ChromeDriver(chromeOptions);
    chromeDriver.manage().window().maximize();
    webDriverMap.put("chrome", chromeDriver);
    WebDriver smallChromeDriver = new ChromeDriver(chromeOptions);
    smallChromeDriver.manage().window().setSize(new Dimension(400, 800));
    webDriverMap.put("chrome-small", smallChromeDriver);
    if (this.inDirectory.exists() && this.inDirectory.isDirectory()) {
        final List<String> includes = new ArrayList<String>();
        includes.add("**/*.html");

        final List<String> excludes = new ArrayList<String>();
        excludes.add("**/archive/**");

        final DirectoryWalker dw = new DirectoryWalker();
        dw.setBaseDir(this.inDirectory);
        dw.setIncludes(includes);/*ww w  .j a  va 2 s .c  om*/
        dw.setExcludes(excludes);

        dw.addDirectoryWalkListener(new ScreenshotDirectoryWalker());
        dw.scan();
    } else {
        getLog().debug("No wireframes in that folder");
    }
}

From source file:org.core.ChromeBenchmark.java

License:Open Source License

@Override
protected WebDriver getWebDriver(TestCase test) {
    ChromeOptions options = new ChromeOptions();

    options.addArguments(/*from  w ww .  j  a  v a  2 s  .co  m*/
            "user-agent=Mozilla/5.0 (Linux; U; Android 2.1-update1; de-de; HTC Desire 1.19.161.5 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");

    if (test.getProxy() != null && !test.getProxy().equals("")) {
        if (test.getProxy().endsWith(".pac") || test.getProxy().endsWith(".js"))
            options.addArguments("proxy-pac-url=" + test.getProxy());
        else
            options.addArguments("proxy-server=" + test.getProxy());
    }

    return new ChromeDriver(options);
}

From source file:org.evilco.bot.powersweeper.platform.DriverManager.java

License:Apache License

/**
 * Initializes the web driver.// w w  w . j  a v a 2  s  .co  m
 */
public void initializeDriver() {
    getLogger().entry();

    // prepare capabilities
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setJavascriptEnabled(true);

    // prepare driver
    switch (this.configuration.getDriver()) {
    case CHROME:
        // set driver path
        System.setProperty("webdriver.chrome.driver", this.getDriverNativeFile().getAbsolutePath());

        // start driver
        this.driver = new ChromeDriver(capabilities);
        break;
    case FIREFOX:
        this.driver = new FirefoxDriver(capabilities);
        break;
    }

    // log
    getLogger().info("Loaded driver of type " + this.driver.getClass().getName() + ".");
    getLogger().info("Setting window properties ...");

    // set window dimension
    this.driver.manage().window().setSize(WINDOW_DIMENSIONS);

    // log
    getLogger().info("Browser is ready for operations.");

    // trace
    getLogger().exit();
}

From source file:org.finra.jtaf.ewd.impl.DefaultSessionFactory.java

License:Apache License

@Override
public WebDriver createInnerDriver(Map<String, String> options, DesiredCapabilities capabilities)
        throws Exception {
    ClientProperties properties = new ClientProperties(options.get("client"));

    WebDriver wd = null;/*w  w w . j ava2  s. c  o m*/
    DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities);
    String browser = properties.getBrowser();

    if (properties.isUseGrid()) {
        RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(properties.getGridUrl()), capabilities);
        remoteWebDriver.setFileDetector(new LocalFileDetector());
        wd = remoteWebDriver;
    } else {
        if (browser == null || browser.equals("")) {
            throw new RuntimeException(
                    "Browser cannot be null. Please set 'browser' in client properties. Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit.");
        } else if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore")
                || browser.equalsIgnoreCase("*iexplore")) {
            String webdriverIEDriver = properties.getWebDriverIEDriver();

            if (webdriverIEDriver != null) {
                System.setProperty("webdriver.ie.driver", webdriverIEDriver);
            }

            String browserVersion = properties.getBrowserVersion();

            if (browserVersion == null || browserVersion.equals("")) {
                throw new RuntimeException(
                        "When using IE as the browser, please set 'browser.version' in client properties");
            } else {
                if (browserVersion.startsWith("9")) {
                    desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
                    desiredCapabilities.setCapability(
                            InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
                    wd = new InternetExplorerDriver(desiredCapabilities);
                } else {
                    wd = new InternetExplorerDriver(desiredCapabilities);
                }
            }
        } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) {
            final String ffProfileFolder = properties.getFirefoxProfileFolder();
            final String ffProfileFile = properties.getFirefoxProfileFile();
            final String path = properties.getBinaryPath();

            if (path != null) {
                FirefoxBinary fireFox = getFFBinary(path);
                FirefoxProfile ffp = null;

                if (ffProfileFolder != null) {
                    ffp = new FirefoxProfile(new File(ffProfileFolder));
                } else {
                    ffp = new FirefoxProfile();
                }

                if (ffProfileFile != null) {
                    addPreferences(ffp, ffProfileFile);
                }

                addPreferences(ffp);

                List<String> ffExtensions = properties.getFirefoxExtensions();
                if (ffExtensions != null && ffExtensions.size() > 0) {
                    addExtensionsToFirefoxProfile(ffp, ffExtensions);
                }

                wd = new FirefoxDriver(fireFox, ffp, desiredCapabilities);
            } else {
                wd = new FirefoxDriver(desiredCapabilities);
            }
        } else if (browser.equalsIgnoreCase("chrome")) {

            String webdriverChromeDriver = properties.getWebDriverChromeDriver();

            if (webdriverChromeDriver != null) {
                System.setProperty("webdriver.chrome.driver", webdriverChromeDriver);
            }

            wd = new ChromeDriver(desiredCapabilities);
        } else if (browser.equalsIgnoreCase("safari")) {
            wd = new SafariDriver(desiredCapabilities);
        } else if (browser.equalsIgnoreCase("htmlunit")) {
            wd = new HtmlUnitDriver(desiredCapabilities);
            ((HtmlUnitDriver) wd).setJavascriptEnabled(true);
        } else {
            throw new Exception("Unsupported browser type: " + browser
                    + ". Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit.");
        }

        // move browser windows to specific position. It's useful for
        // debugging...
        final int browserInitPositionX = properties.getBrowserInitPositionX();
        final int browserInitPositionY = properties.getBrowserInitPositionY();
        if (browserInitPositionX != 0 || browserInitPositionY != 0) {
            wd.manage().window().setSize(new Dimension(1280, 1024));
            wd.manage().window().setPosition(new Point(browserInitPositionX, browserInitPositionY));
        }
    }

    return wd;
}

From source file:org.glassfish.tyrus.tests.qa.SeleniumToolkit.java

License:Open Source License

public void setUpChrome() {
    ChromeDriverService service;// w  ww  .  j a v  a  2  s .co  m

    try {
        System.setProperty("webdriver.chrome.driver", getEnv("CHROME_DRIVER"));
        service = new ChromeDriverService.Builder().usingAnyFreePort()
                .usingDriverExecutable(new File(getEnv("CHROME_DRIVER"))).build();
        service.start();
        logger.log(Level.INFO, "ChromeDriverService.URL: {0}", service.getUrl());
        driver = new ChromeDriver(service);
        commonBrowserSetup();
        logger.log(Level.INFO, "Chrome Setup PASSED");
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Chrome Setup FAILED: {0}", ex.getLocalizedMessage());
        ex.printStackTrace();
    } finally {
        assert driver != null : "Driver is null";
    }
}

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 . java  2 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.jitsi.meet.test.web.WebParticipantFactory.java

License:Apache License

/**
 * Starts a <tt>WebDriver</tt> instance using default settings.
 * @param options the options to use when creating the driver.
 * @return the <tt>WebDriver</tt> instance.
 */// www. j a v a 2s .c o  m
private WebDriver startWebDriver(WebParticipantOptions options) {
    ParticipantType participantType = options.getParticipantType();
    String version = options.getVersion();
    File browserBinaryAPath = getFile(options, options.getBinary());

    boolean isRemote = options.isRemote();

    // by default we load chrome, but we can load safari or firefox
    if (participantType.isFirefox()) {
        FirefoxDriverManager.getInstance().setup();

        if (browserBinaryAPath != null && (browserBinaryAPath.exists() || isRemote)) {
            System.setProperty("webdriver.firefox.bin", browserBinaryAPath.getAbsolutePath());
        }

        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.setPreference("media.navigator.streams.fake", true);
        profile.setAcceptUntrustedCertificates(true);

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

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

        if (isRemote) {
            FirefoxOptions ffOptions = new FirefoxOptions();
            ffOptions.setProfile(profile);

            if (version != null && version.length() > 0) {
                ffOptions.setCapability(CapabilityType.VERSION, version);
            }

            return new RemoteWebDriver(options.getRemoteDriverAddress(), ffOptions);
        }

        return new FirefoxDriver(new FirefoxOptions().setProfile(profile));
    } else if (participantType == ParticipantType.safari) {
        // You must enable the 'Allow Remote Automation' option in
        // Safari's Develop menu to control Safari via WebDriver.
        // In Safari->Preferences->Websites, select Camera,
        // and select Allow for "When visiting other websites"
        if (isRemote) {
            return new RemoteWebDriver(options.getRemoteDriverAddress(), new SafariOptions());
        }
        return new SafariDriver();
    } else if (participantType == ParticipantType.edge) {
        InternetExplorerDriverManager.getInstance().setup();

        InternetExplorerOptions ieOptions = new InternetExplorerOptions();
        ieOptions.ignoreZoomSettings();

        System.setProperty("webdriver.ie.driver.silent", "true");

        return new InternetExplorerDriver(ieOptions);
    } else {
        ChromeDriverManager.getInstance().setup();

        System.setProperty("webdriver.chrome.verboseLogging", "true");
        System.setProperty("webdriver.chrome.logfile",
                FailureListener.createLogsFolder() + "/chrome-console-" + options.getName() + ".log");

        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.ALL);

        final ChromeOptions ops = new ChromeOptions();
        ops.addArguments("use-fake-ui-for-media-stream");
        ops.addArguments("use-fake-device-for-media-stream");
        ops.addArguments("disable-plugins");
        ops.addArguments("mute-audio");
        ops.addArguments("disable-infobars");
        // Since chrome v66 there are new autoplay policies, which broke
        // shared video tests, disable no-user-gesture to make it work
        ops.addArguments("autoplay-policy=no-user-gesture-required");

        if (options.getChromeExtensionId() != null) {
            try {
                ops.addExtensions(downloadExtension(options.getChromeExtensionId()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        ops.addArguments("auto-select-desktop-capture-source=Entire screen");

        ops.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

        if (options.isChromeSandboxDisabled()) {
            ops.addArguments("no-sandbox");
            ops.addArguments("disable-setuid-sandbox");
        }

        if (options.isHeadless()) {
            ops.addArguments("headless");
            ops.addArguments("window-size=1200x600");
        }

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

        if (browserBinaryAPath != null && (browserBinaryAPath.exists() || isRemote)) {
            ops.setBinary(browserBinaryAPath.getAbsolutePath());
        }

        File uplinkFile = getFile(options, options.getUplink());
        if (uplinkFile != null) {
            ops.addArguments("uplink=" + uplinkFile.getAbsolutePath());
        }

        File downlinkFile = getFile(options, options.getDownlink());
        if (downlinkFile != null) {
            ops.addArguments("downlink=" + downlinkFile.getAbsolutePath());
        }

        String profileDirectory = options.getProfileDirectory();
        if (profileDirectory != null && profileDirectory != "") {
            ops.addArguments("user-data-dir=" + profileDirectory);
        }

        File fakeStreamAudioFile = getFile(options, options.getFakeStreamAudioFile());
        if (fakeStreamAudioFile != null) {
            ops.addArguments("use-file-for-fake-audio-capture=" + fakeStreamAudioFile.getAbsolutePath());
        }

        File fakeStreamVideoFile = getFile(options, options.getFakeStreamVideoFile());
        if (fakeStreamVideoFile != null) {
            ops.addArguments("use-file-for-fake-video-capture=" + fakeStreamVideoFile.getAbsolutePath());
        }

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

        if (isRemote) {
            if (version != null && version.length() > 0) {
                ops.setCapability(CapabilityType.VERSION, version);
            }

            return new RemoteWebDriver(options.getRemoteDriverAddress(), 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(() -> {
                        long start = System.currentTimeMillis();
                        ChromeDriver resDr = new ChromeDriver(ops);
                        TestUtils.print(
                                "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
                    future.cancel(true);

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

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

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

From source file:org.kuali.rice.testtools.selenium.WebDriverUtils.java

License:Educational Community License

/**
 * <p>/*from  ww w  . j  a  va2 s .  c  o m*/
 * remote.public.driver set to chrome or firefox (null assumes firefox).
 * </p><p>
 * if remote.public.hub is set a RemoteWebDriver is created (Selenium Grid)
 * if proxy.host is set, the web driver is setup to use a proxy
 * </p>
 *
 * @return WebDriver or null if unable to create
 */
public static WebDriver getWebDriver() {
    String driverParam = System.getProperty(HUB_DRIVER_PROPERTY);
    String hubParam = System.getProperty(HUB_PROPERTY);
    String proxyParam = System.getProperty(PROXY_HOST_PROPERTY);

    // setup proxy if specified as VM Arg
    DesiredCapabilities capabilities = new DesiredCapabilities();
    WebDriver webDriver = null;
    if (StringUtils.isNotEmpty(proxyParam)) {
        capabilities.setCapability(CapabilityType.PROXY, new Proxy().setHttpProxy(proxyParam));
    }

    if (hubParam == null) {
        if (driverParam == null || "firefox".equalsIgnoreCase(driverParam)) {
            FirefoxProfile profile = new FirefoxProfile();
            profile.setEnableNativeEvents(false);
            capabilities.setCapability(FirefoxDriver.PROFILE, profile);
            return new FirefoxDriver(capabilities);
        } else if ("chrome".equalsIgnoreCase(driverParam)) {
            return new ChromeDriver(capabilities);
        } else if ("safari".equals(driverParam)) {
            System.out.println("SafariDriver probably won't work, if it does please contact Erik M.");
            return new SafariDriver(capabilities);
        }
    } else {
        try {
            if (driverParam == null || "firefox".equalsIgnoreCase(driverParam)) {
                return new RemoteWebDriver(new URL(getHubUrlString()), DesiredCapabilities.firefox());
            } else if ("chrome".equalsIgnoreCase(driverParam)) {
                return new RemoteWebDriver(new URL(getHubUrlString()), DesiredCapabilities.chrome());
            }
        } catch (MalformedURLException mue) {
            System.out.println(getHubUrlString() + " " + mue.getMessage());
            mue.printStackTrace();
        }
    }
    return null;
}

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

License:Apache License

public static WebDriver newWebDriver(Object options) {

    WebDriver driver = null;//from w ww .j  a va2s  .  c  o  m

    int numDriverTries = 0;
    final int maxDriverError = getProperty(SELENIUM_MAX_DRIVER_ERROR_PROPERTY,
            SELENIUM_MAX_DRIVER_ERROR_DEFAULT);
    final String errMessage = "Exception creating webdriver for chrome";
    do {
        try {

            if (options instanceof ChromeOptions) {
                driver = new ChromeDriver((ChromeOptions) options);
            } else if (options instanceof FirefoxProfile) {
                driver = new FirefoxDriver((FirefoxProfile) options);
            }

        } catch (Throwable t) {
            driver = null;
            log.warn(errMessage + " #" + numDriverTries, t);
        } finally {
            numDriverTries++;
            if (numDriverTries > maxDriverError) {
                throw new KurentoException(errMessage + " (" + maxDriverError + " times)");
            }
        }
    } while (driver == null);

    return driver;
}