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.powertools.web.WebDriverBrowser.java

License:Open Source License

private boolean startChrome(String logDirectory) {
    try {/*  w  w  w .ja  v  a  2  s.co m*/
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        ChromeDriverService service = new ChromeDriverService.Builder()
                .usingDriverExecutable(new File("chromedriver.exe")).usingAnyFreePort()
                .withLogFile(new File(logDirectory + CHROMEDRIVER_LOG_FILENAME)).build();
        service.start();
        mDriver = new ChromeDriver(service);
        mRunTime.reportLink(CHROMEDRIVER_LOG_FILENAME);
        return true;
    } catch (IOException ioe) {
        return false;
    }
}

From source file:org.qe4j.web.OpenWebDriver.java

License:Open Source License

/**
 * Builds a local WebDriver based on properties.
 *
 * @param browser//w  w w.  j a v  a  2 s  .c  om
 * @return local WebDriver
 * @throws IOException
 */
protected WebDriver initLocalWebDriver(Browser browser, String version, Platform platform,
        Properties properties) throws IOException {
    local = true;
    log.info("attempting to instantiate local web driver using {}", browser);
    WebDriver driver = null;

    // determine the browser binary path key by version
    String browserBinaryPath = getBrowserBinaryPath(platform, browser, version, properties);

    DesiredCapabilities capabilities = null;
    switch (browser) {
    case FIREFOX:
    default:
        FirefoxProfile profile = getFireFoxProfile();
        // TODO investigate adding JSErrorCollector data extraction
        // JavaScriptError.addExtension(profile);
        driver = OpenWebDriver.newLocalFirefoxDriver(browserBinaryPath, profile);
        break;
    case IEXPLORE:
        /*
         * TODO investigate possibility of dynamically running
         * non-default version of IE with IEDriverServer
         */

        // pass driver path to system properties
        System.setProperty(IEXPLORE_DRIVER_PROP_KEY, properties.getProperty(IEXPLORE_DRIVER_PROP_KEY));

        capabilities = DesiredCapabilities.internetExplorer();
        driver = new InternetExplorerDriver(capabilities);
        break;
    case HTMLUNIT:
        log.info("creating HtmlUnit driver emulating " + "FireFox17 with javascript enabled");
        driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_17);
        ((HtmlUnitDriver) driver).setJavascriptEnabled(true);
        break;
    case CHROME:
        initChromeDriver(properties);

        // enable testability of this without actually executing
        if (Boolean.parseBoolean(System.getProperty("os.name.overriden"))) {
            throw new IllegalStateException("os overriden so can't detect driver reliably");
        }

        capabilities = DesiredCapabilities.chrome();

        if (browserBinaryPath != null) {
            capabilities.setCapability("chrome.binary", browserBinaryPath);
        }

        initChromeProfile(capabilities);

        driver = new ChromeDriver(capabilities);
        break;
    }

    return driver;
}

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

License:Open Source License

/**
 * /* w  ww  .  jav  a2 s.  c o  m*/
 * @param browserName String, the browser name, such as "explorer".  If null, then the 
 * System.property {@link #SYSTEM_PROPERTY_BROWSER_NAME} is sought. If not set, then the 
 * default {@link #BROWSER_NAME_FIREFOX} is used.
 * 
 * @param extraParameters HashMap<String,Object>, can be used to pass more browser parameters, such as proxy settings.
 * @return WebDriver
 */
public static WebDriver getBrowserInstance(String browserName, HashMap<String, Object> extraParameters) {
    WebDriver instance = null;
    DesiredCapabilities caps = null;

    if (browserName == null || browserName.length() == 0) {
        browserName = System.getProperty(SYSTEM_PROPERTY_BROWSER_NAME);
        if (browserName == null || browserName.length() == 0) {
            browserName = BROWSER_NAME_FIREFOX;
            System.setProperty(SYSTEM_PROPERTY_BROWSER_NAME, browserName);
        }
    }

    String browserNameLC = browserName.toLowerCase();

    //Prepare the Capabilities
    if (extraParameters == null || extraParameters.isEmpty()) {
        //Get proxy settings from System properties
        String proxy = System.getProperty(SelectBrowser.SYSTEM_PROPERTY_PROXY_HOST);
        String port = System.getProperty(SelectBrowser.SYSTEM_PROPERTY_PROXY_PORT);
        if (proxy != null && !proxy.isEmpty()) {
            String proxysetting = proxy;
            if (port != null && !port.isEmpty())
                proxysetting += ":" + port;
            extraParameters.put(KEY_PROXY_SETTING, proxysetting);

            String bypass = System.getProperty(SelectBrowser.SYSTEM_PROPERTY_PROXY_BYPASS);
            if (proxy != null && !proxy.isEmpty()) {
                extraParameters.put(KEY_PROXY_BYPASS_ADDRESS, bypass);
            }
        }
    }
    if (extraParameters != null && !extraParameters.isEmpty()) {
        caps = getDesiredCapabilities(browserNameLC, extraParameters);
    }

    String installdir = System.getenv("SELENIUM_PLUS");

    //Create the Driver
    if (browserNameLC.contains(BROWSER_NAME_IE)) {
        System.setProperty(SYSTEM_PROPERTY_WEBDRIVER_IE, installdir + "/extra/IEDriverServer.exe");
        instance = (caps != null) ? new InternetExplorerDriver(caps) : new InternetExplorerDriver();
    } else if (browserNameLC.equals(BROWSER_NAME_CHROME)) {
        System.setProperty(SYSTEM_PROPERTY_WEBDRIVER_CHROME, installdir + "/extra/chromedriver.exe");
        instance = (caps != null) ? new ChromeDriver(caps) : new ChromeDriver();
    } else if (browserNameLC.equals(BROWSER_NAME_EDGE)) {
        System.setProperty(SYSTEM_PROPERTY_WEBDRIVER_EDGE, installdir + "/extra/MicrosoftWebDriver.exe");
        instance = (caps != null) ? new EdgeDriver(caps) : new EdgeDriver();
    } else if (browserNameLC.equals(BROWSER_NAME_ANDROID_CHROME)) {
        System.setProperty(SYSTEM_PROPERTY_WEBDRIVER_CHROME, installdir + "/extra/chromedriver.exe");
        instance = (caps != null) ? new ChromeDriver(caps) : new ChromeDriver();
    } else { // default browser always
        instance = (caps != null) ? new FirefoxDriver(caps) : new FirefoxDriver();
    }
    return instance;
}

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

License:Open Source License

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

}

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

License:Open Source License

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

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

License:Open Source License

public void testParallelLogin() {

    createAdminUser();//from w  w w.  ja v a 2s. co m

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

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

    final String menuEntry = "Pages";

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

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

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

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

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

            WebDriver localDriver = new ChromeDriver(chromeOptions);

            try {
                long t0 = System.currentTimeMillis();

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

                long t1 = System.currentTimeMillis();

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

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

            localDriver = null;

            return null;
        });

        results.add(result);
    }

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

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

        try {

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

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

            assertNull(res);

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

    long t3 = System.currentTimeMillis();

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

    service.shutdown();

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

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

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

License:Open Source License

@Before
public void startDriver() {

    switch (activeBrowser) {

    case FIREFOX:

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

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

        driver = new FirefoxDriver(firefoxOptions);

        break;//from   w w w  .j a  v  a  2 s.  c om

    case CHROME:

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

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

        driver = new ChromeDriver(chromeOptions);

        break;

    case NONE:

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

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

License:Apache License

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

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

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

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

License:Open Source License

/**
 * launches Google Chrome with the ChromeDriverManager, this will be downloaded
 * automatically and will be saved in the directory
 * /~USER_HOME/m2/repository/webdriver/ in every according OS.
 * /*w w  w . java 2s.c  o  m*/
 * @throws FixtureException
 */
private void launchChrome() throws FixtureException {
    logger.debug("Starting Google Chrome ...");
    setupDrivermanager(ChromeDriverManager.getInstance(DriverManagerType.CHROME));
    logger.trace("WebDriverManager setup executed!");
    ChromeOptions options = populateBrowserSettingsForChrome();
    ChromeDriver chromeDriver = new ChromeDriver(options);
    driver = chromeDriver;
    logger.trace("Google Chrome setup executed!");
    logBrowserVersion(options, chromeDriver);
    registerShutdownHook(driver);
}

From source file:org.wso2.is.portal.user.test.ui.SelectDriver.java

License:Open Source License

public static WebDriver selectDriver(String driverType) {

    try {/*from w w  w .ja  v  a 2 s .com*/
        if (driverType.equalsIgnoreCase("chrome")) {
            System.setProperty("webdriver.chrome.driver", System.getProperty("pathToChromeDriver"));
            DesiredCapabilities capability = DesiredCapabilities.chrome();
            capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
            driver = new ChromeDriver(capability);
            driver.manage().window().maximize();
        } else {
            driver = new HtmlUnitDriver();
        }
    } catch (WebDriverException wb) {
        LOGGER.info("The relavent driver is not found. Please read the README.txt in the uer-portal tests");
    } catch (Exception e) {
        LOGGER.info(e.toString());
    }
    return driver;
}