Example usage for org.openqa.selenium WebDriver manage

List of usage examples for org.openqa.selenium WebDriver manage

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver manage.

Prototype

Options manage();

Source Link

Document

Gets the Option interface

Usage

From source file:net.codestory.simplelenium.SeleniumTest.java

License:Apache License

protected void configureWebDriver(WebDriver driver) {
    driver.manage().window().setSize(new Dimension(2048, 768));
}

From source file:net.continuumsecurity.web.drivers.DriverFactory.java

License:Open Source License

private static WebDriver getDriver(String type, boolean isProxyDriver) {
    WebDriver retVal = instance().findOrCreate(type, isProxyDriver);
    try {/*w w w  . j  a  v  a2 s.co  m*/
        if (!retVal.getCurrentUrl().equals("about:blank")) {
            retVal.manage().deleteAllCookies();
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return retVal;
}

From source file:omelet.driver.DriverUtility.java

License:Apache License

/***
 * Generic waitFor Function which waits for condition to be successful else
 * return null//from  w  w w  . jav a  2 s  .c  om
 * 
 * @param expectedCondition
 *            :ExpectedCondition<T>
 * @param driver
 *            :WebDriver
 * @param timeout
 *            in seconds
 * @return <T> or null
 */
public static <T> T waitFor(ExpectedCondition<T> expectedCondition, WebDriver driver, int timeOutInSeconds) {
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    try {
        T returnValue = new WebDriverWait(driver, timeOutInSeconds).pollingEvery(500, TimeUnit.MILLISECONDS)
                .until(expectedCondition);
        return returnValue;
    } catch (TimeoutException e) {
        LOGGER.error(e);
        return null;
    } finally {
        driver.manage().timeouts().implicitlyWait(Driver.getBrowserConf().getDriverTimeOut(), TimeUnit.SECONDS);
        stopwatch.stop();
        LOGGER.debug("Time Taken for waitFor method for Expected Condition is:"
                + stopwatch.elapsedTime(TimeUnit.SECONDS));
    }
}

From source file:org.alfresco.po.share.ShareUtil.java

License:Open Source License

public HtmlPage loginWithPost(WebDriver driver, String shareUrl, String userName, String password) {
    HttpClient client = new HttpClient();

    //login/*from   w  w w .  ja va2 s  .  co  m*/
    PostMethod post = new PostMethod((new StringBuilder()).append(shareUrl).append("/page/dologin").toString());
    NameValuePair[] formParams = (new NameValuePair[] {
            new org.apache.commons.httpclient.NameValuePair("username", userName),
            new org.apache.commons.httpclient.NameValuePair("password", password),
            new org.apache.commons.httpclient.NameValuePair("success", "/share/page/site-index"),
            new org.apache.commons.httpclient.NameValuePair("failure", "/share/page/type/login?error=true") });
    post.setRequestBody(formParams);
    post.addRequestHeader("Accept-Language", "en-us,en;q=0.5");
    try {
        client.executeMethod(post);
        HttpState state = client.getState();
        //Navigate to login page to obtain a session cookie.
        driver.navigate().to(shareUrl);
        //add authenticated token to cookie and navigate to user dashboard
        String url = shareUrl + "/page/user/" + userName + "/dashboard";
        driver.manage()
                .addCookie(new Cookie(state.getCookies()[0].getName(), state.getCookies()[0].getValue()));
        driver.navigate().to(url);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("Login error ", e);
    } finally {
        post.releaseConnection();
    }

    return factoryPage.getPage(driver);

}

From source file:org.alfresco.selenium.FetchHttpClient.java

License:Open Source License

/**
 * Prepare the client cookie based on the authenticated {@link WebDriver} 
 * cookie. //  w w  w.j  ava2s .c o  m
 * @param driver {@link WebDriver}
 * @return BasicClientCookie with correct credentials.
 */
public static BasicClientCookie generateSessionCookie(WebDriver driver) {
    Cookie originalCookie = driver.manage().getCookieNamed("JSESSIONID");
    if (originalCookie == null) {
        return null;
    }
    // just build new apache-like cookie based on webDriver's one
    String cookieName = originalCookie.getName();
    String cookieValue = originalCookie.getValue();
    BasicClientCookie resultCookie = new BasicClientCookie(cookieName, cookieValue);
    resultCookie.setDomain(originalCookie.getDomain());
    resultCookie.setExpiryDate(originalCookie.getExpiry());
    resultCookie.setPath(originalCookie.getPath());
    return resultCookie;
}

From source file:org.apache.nutch.protocol.htmlunit.HtmlUnitWebDriver.java

License:Apache License

public static WebDriver getDriverForPage(String url, Configuration conf) {
    long pageLoadTimout = conf.getLong("page.load.delay", 3);
    enableJavascript = conf.getBoolean("htmlunit.enable.javascript", true);
    enableCss = conf.getBoolean("htmlunit.enable.css", false);
    javascriptTimeout = conf.getLong("htmlunit.javascript.timeout", 3500);
    int redirects = Integer.parseInt(conf.get("http.redirect.max", "0"));
    enableRedirect = redirects <= 0 ? false : true;
    maxRedirects = redirects;/*from  www .j av a2  s. c o m*/

    WebDriver driver = null;

    try {
        driver = new HtmlUnitWebDriver();
        driver.manage().timeouts().pageLoadTimeout(pageLoadTimout, TimeUnit.SECONDS);
        driver.get(url);
    } catch (Exception e) {
        if (e instanceof TimeoutException) {
            LOG.debug("HtmlUnit WebDriver: Timeout Exception: Capturing whatever loaded so far...");
            return driver;
        }
        cleanUpDriver(driver);
        throw new RuntimeException(e);
    }

    return driver;
}

From source file:org.apache.nutch.protocol.interactiveselenium.handlers.SearchHandler.java

License:Apache License

private String genericSearchHandler(WebDriver webDriver, String htmlpage, String searchWindowPath,
        String searchInputPath, String searchButtonPath, String searchRadioButtonPath, String searchKey) {
    webDriver.manage().window().maximize();
    try {/* ww w .  ja va  2  s. c  o  m*/
        WebElement findSearchWindow = webDriver.findElement(By.xpath(searchWindowPath));
        if (findSearchWindow.isDisplayed())
            findSearchWindow.click();
        WebElement classifiedRadioBtn = webDriver.findElement(By.xpath(searchRadioButtonPath));
        if (classifiedRadioBtn.isSelected())
            classifiedRadioBtn.click();
        WebElement username = webDriver.findElement(By.xpath(searchInputPath));
        if (username.isDisplayed())
            username.sendKeys(searchKey);
        WebElement loginBtn = webDriver.findElement(By.xpath(searchButtonPath));
        if (loginBtn.isDisplayed())
            loginBtn.click();
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        htmlpage += webDriver.findElement(By.tagName("body")).getAttribute("innerHTML");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return htmlpage;
}

From source file:org.apache.nutch.protocol.selenium.HttpWebClient.java

License:Apache License

public static WebDriver getDriverForPage(String url, Configuration conf) {
    WebDriver driver = null;
    long pageLoadWait = conf.getLong("page.load.delay", 3);

    try {//from   w ww  . j  a  va  2s  .  co  m
        String driverType = conf.get("selenium.driver", "firefox");
        boolean enableHeadlessMode = conf.getBoolean("selenium.enable.headless", false);

        switch (driverType) {
        case "firefox":
            String geckoDriverPath = conf.get("selenium.grid.binary", "/root/geckodriver");
            driver = createFirefoxWebDriver(geckoDriverPath, enableHeadlessMode);
            break;
        case "chrome":
            String chromeDriverPath = conf.get("selenium.grid.binary", "/root/chromedriver");
            driver = createChromeWebDriver(chromeDriverPath, enableHeadlessMode);
            break;
        // case "opera":
        // // This class is provided as a convenience for easily testing the
        // Chrome browser.
        // String operaDriverPath = conf.get("selenium.grid.binary",
        // "/root/operadriver");
        // driver = createOperaWebDriver(operaDriverPath, enableHeadlessMode);
        // break;
        case "remote":
            String seleniumHubHost = conf.get("selenium.hub.host", "localhost");
            int seleniumHubPort = Integer.parseInt(conf.get("selenium.hub.port", "4444"));
            String seleniumHubPath = conf.get("selenium.hub.path", "/wd/hub");
            String seleniumHubProtocol = conf.get("selenium.hub.protocol", "http");
            URL seleniumHubUrl = new URL(seleniumHubProtocol, seleniumHubHost, seleniumHubPort,
                    seleniumHubPath);

            String seleniumGridDriver = conf.get("selenium.grid.driver", "firefox");

            switch (seleniumGridDriver) {
            case "firefox":
                driver = createFirefoxRemoteWebDriver(seleniumHubUrl, enableHeadlessMode);
                break;
            case "chrome":
                driver = createChromeRemoteWebDriver(seleniumHubUrl, enableHeadlessMode);
                break;
            case "random":
                driver = createRandomRemoteWebDriver(seleniumHubUrl, enableHeadlessMode);
                break;
            default:
                LOG.error(
                        "The Selenium Grid WebDriver choice {} is not available... defaulting to FirefoxDriver().",
                        driverType);
                driver = createDefaultRemoteWebDriver(seleniumHubUrl, enableHeadlessMode);
                break;
            }
            break;
        default:
            LOG.error("The Selenium WebDriver choice {} is not available... defaulting to FirefoxDriver().",
                    driverType);
            FirefoxOptions options = new FirefoxOptions();
            driver = new FirefoxDriver(options);
            break;
        }
        LOG.debug("Selenium {} WebDriver selected.", driverType);

        driver.manage().timeouts().pageLoadTimeout(pageLoadWait, TimeUnit.SECONDS);
        driver.get(url);
    } catch (Exception e) {
        if (e instanceof TimeoutException) {
            LOG.error("Selenium WebDriver: Timeout Exception: Capturing whatever loaded so far...");
            return driver;
        } else {
            LOG.error(e.toString());
        }
        cleanUpDriver(driver);
        throw new RuntimeException(e);
    }

    return driver;
}

From source file:org.apache.zeppelin.WebDriverManager.java

License:Apache License

public static WebDriver getWebDriver() {
    WebDriver driver = null;

    if (driver == null) {
        try {/*  w  ww . ja  va 2  s. c om*/
            FirefoxBinary ffox = new FirefoxBinary();
            if ("true".equals(System.getenv("TRAVIS"))) {
                ffox.setEnvironmentProperty("DISPLAY", ":99"); // xvfb is supposed to
                // run with DISPLAY 99
            }
            int firefoxVersion = WebDriverManager.getFirefoxVersion();
            LOG.info("Firefox version " + firefoxVersion + " detected");

            downLoadsDir = FileUtils.getTempDirectory().toString();

            String tempPath = downLoadsDir + "/firefox/";

            downloadGeekoDriver(firefoxVersion, tempPath);

            FirefoxProfile profile = new FirefoxProfile();
            profile.setPreference("browser.download.folderList", 2);
            profile.setPreference("browser.download.dir", downLoadsDir);
            profile.setPreference("browser.helperApps.alwaysAsk.force", false);
            profile.setPreference("browser.download.manager.showWhenStarting", false);
            profile.setPreference("browser.download.manager.showAlertOnComplete", false);
            profile.setPreference("browser.download.manager.closeWhenDone", true);
            profile.setPreference("app.update.auto", false);
            profile.setPreference("app.update.enabled", false);
            profile.setPreference("dom.max_script_run_time", 0);
            profile.setPreference("dom.max_chrome_script_run_time", 0);
            profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                    "application/x-ustar,application/octet-stream,application/zip,text/csv,text/plain");
            profile.setPreference("network.proxy.type", 0);

            System.setProperty(GeckoDriverService.GECKO_DRIVER_EXE_PROPERTY, tempPath + "geckodriver");
            System.setProperty(SystemProperty.DRIVER_USE_MARIONETTE, "false");

            FirefoxOptions firefoxOptions = new FirefoxOptions();
            firefoxOptions.setBinary(ffox);
            firefoxOptions.setProfile(profile);
            driver = new FirefoxDriver(firefoxOptions);
        } catch (Exception e) {
            LOG.error("Exception in WebDriverManager while FireFox Driver ", e);
        }
    }

    if (driver == null) {
        try {
            driver = new ChromeDriver();
        } catch (Exception e) {
            LOG.error("Exception in WebDriverManager while ChromeDriver ", e);
        }
    }

    if (driver == null) {
        try {
            driver = new SafariDriver();
        } catch (Exception e) {
            LOG.error("Exception in WebDriverManager while SafariDriver ", e);
        }
    }

    String url;
    if (System.getenv("url") != null) {
        url = System.getenv("url");
    } else {
        url = "http://localhost:8080";
    }

    long start = System.currentTimeMillis();
    boolean loaded = false;
    driver.manage().timeouts().implicitlyWait(AbstractZeppelinIT.MAX_IMPLICIT_WAIT, TimeUnit.SECONDS);
    driver.get(url);

    while (System.currentTimeMillis() - start < 60 * 1000) {
        // wait for page load
        try {
            (new WebDriverWait(driver, 30)).until(new ExpectedCondition<Boolean>() {
                @Override
                public Boolean apply(WebDriver d) {
                    return d.findElement(By.xpath("//i[@uib-tooltip='WebSocket Connected']")).isDisplayed();
                }
            });
            loaded = true;
            break;
        } catch (TimeoutException e) {
            LOG.info("Exception in WebDriverManager while WebDriverWait ", e);
            driver.navigate().to(url);
        }
    }

    if (loaded == false) {
        fail();
    }

    driver.manage().window().maximize();
    return driver;
}

From source file:org.apache.zeppelin.ZeppelinITUtils.java

License:Apache License

public static void turnOffImplicitWaits(WebDriver driver) {
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
}