Example usage for org.openqa.selenium.support.ui FluentWait FluentWait

List of usage examples for org.openqa.selenium.support.ui FluentWait FluentWait

Introduction

In this page you can find the example usage for org.openqa.selenium.support.ui FluentWait FluentWait.

Prototype

public FluentWait(T input) 

Source Link

Usage

From source file:com.pentaho.ctools.utils.ElementHelper.java

License:Apache License

/**
 * This method shall wait for an alert shows-up.
 * //  w ww. j  a  v  a2s. co  m
 * @param driver
 * @param timeout
 * @param pollingTime
 * @return
 */
public Alert WaitForAlert(final WebDriver driver, final long timeout, final long pollingTime) {
    this.log.debug("WaitForAlert::Enter");
    ExecutorService executor = null;

    Alert alert = null;

    try {
        class CheckForAlert implements Callable<Alert> {

            @Override
            public Alert call() {
                Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(timeout, TimeUnit.SECONDS)
                        .pollingEvery(pollingTime, TimeUnit.MILLISECONDS);

                return wait.until(new Function<WebDriver, Alert>() {

                    @Override
                    public Alert apply(WebDriver driver) {
                        try {
                            return driver.switchTo().alert();
                        } catch (NoAlertPresentException e) {
                            return null;
                        }
                    }
                });
            }
        }

        CheckForAlert call = new CheckForAlert();
        executor = Executors.newSingleThreadExecutor();
        alert = executor.submit(call).get(timeout + 2, TimeUnit.SECONDS);

    } catch (InterruptedException ie) {
        this.log.warn("Interrupted Exception");
        this.log.warn(ie.toString());
    } catch (ExecutionException ee) {
        if (ee.getCause().getClass().getCanonicalName()
                .equalsIgnoreCase(TimeoutException.class.getCanonicalName())) {
            this.log.warn("WebDriver timeout exceeded!");
        } else {
            this.log.warn("Execution Exception");
            this.log.warn(ee.toString());
        }
    } catch (java.util.concurrent.TimeoutException cte) {
        this.log.warn("Thread timeout exceeded!");
        this.log.warn(cte.toString());
    } catch (Exception e) {
        this.log.error("Exception");
        this.log.catching(e);
    }

    if (executor != null) {
        executor.shutdown();
    }
    this.log.debug("WaitForAlert::Exit");
    return alert;
}

From source file:com.pentaho.selenium.BaseTest.java

License:Apache License

@BeforeSuite
public void setUpClass() {
    this.log.info("Master setup");

    // Initialize BASEURL
    baseUrl = "http://localhost:8080/pentaho/";
    downloadDir = System.getProperty("user.home") + "\\SeleniumDonwloadDir";
    pentahoReleaseVersion = System.getProperty("pentaho.release.version");
    pentahoBaServerServiceName = System.getProperty("pentaho.bi.server.service.name");
    pentahoBaServerUrl = System.getProperty("pentaho.bi.server.url");
    pentahoBaServerHostname = System.getProperty("pentaho.bi.server.hostname");
    pentahoBaServerPort = System.getProperty("pentaho.bi.server.port");

    this.log.info("pentaho.release.version::" + pentahoReleaseVersion);

    new File(downloadDir).mkdir();

    System.setProperty("webdriver.log.file", "/dev/stdout");
    //System.setProperty( "webdriver.firefox.logfile", "/dev/stdout" );

    // Setting log preferences
    LoggingPreferences logs = new LoggingPreferences();
    logs.enable(LogType.BROWSER, Level.WARNING);
    /*logs.enable( LogType.SERVER, Level.WARNING );
    logs.enable( LogType.DRIVER, Level.WARNING );
    logs.enable( LogType.PROFILER, Level.WARNING );
    logs.enable( LogType.CLIENT, Level.WARNING );
    logs.enable( LogType.PERFORMANCE, Level.WARNING );*/

    /*//from   ww w.j a  v a2  s  . com
     * INTERNET EXPLORER DRIVER
     */
    // Initialize DRIVER
    FirefoxProfile ffProfile = new FirefoxProfile();
    //ffProfile.setEnableNativeEvents( true );
    ffProfile.setPreference("general.useragent.locale", "en-US");
    ffProfile.setPreference("intl.accept_languages", "en-US, en");
    ffProfile.setPreference("browser.download.folderList", 2); // 0 - Desktop, 1- Download dir, 2 - specify dir
    ffProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
    ffProfile.setPreference("browser.download.manager.showWhenStarting", false);
    ffProfile.setPreference("browser.download.dir", downloadDir);
    ffProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
            "table/excel;application/vnd.ms-excel;application/msexcel;application/x-msexcel;application/x-ms-excel;application/x-excel;application/x-dos_ms_excel;application/xls;application/x-xls;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;text/csv;application/rtf");

    // Setting properties for webdriver
    DesiredCapabilities capabilities = DesiredCapabilities.firefox();
    capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
    capabilities.setCapability(FirefoxDriver.PROFILE, ffProfile);

    BaseTest.driver = new FirefoxDriver(capabilities);

    /*
     * INTERNET EXPLORER DRIVER
     */
    /*
     * System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer_Win32_2.44.0\\IEDriverServer.exe");
     * System.setProperty("webdriver.ie.driver.host", "10.120.42.25");
     * System.setProperty("webdriver.ie.driver.loglevel", "FATAL"); System.setProperty("webdriver.ie.driver.loglevel",
     * downloadDir + "\\seleniumlogs.txt");
     *
     * // We could use any driver for our tests... DesiredCapabilities capabilities = new DesiredCapabilities();
     * capabilities.setBrowserName("internet explorer"); capabilities.setVersion("8");
     * capabilities.setPlatform(Platform.WINDOWS); capabilities.setCapability("platform", "WINDOWS");
     * capabilities.setJavascriptEnabled(true); //capabilities.setCapability(InternetExplorerDriver.HOST,
     * "10.120.40.243");
     *
     * capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
     * capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);
     *
     * // Get a handle to the driver. This will throw an exception // if a matching driver cannot be located driver =
     * new RemoteWebDriver(new URL("http://10.120.42.25:4444/wd/hub"), capabilities); //driver = new
     * InternetExplorerDriver();
     */

    BaseTest.driver.manage().window().setPosition(new Point(0, 0));
    BaseTest.driver.manage().window().setSize(new Dimension(1360, 764));
    BaseTest.driver.manage().timeouts().pageLoadTimeout(180, TimeUnit.SECONDS);
    BaseTest.driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    BaseTest.driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);

    // Initialize WAIT
    wait = new FluentWait<WebDriver>(BaseTest.driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5,
            TimeUnit.SECONDS);
}

From source file:com.robin.utilities.Utilities.java

License:Open Source License

/**
 * A utility that waits for a gmail mailbox to receive a new message with
 * according to a given SearchTerm. Only "Not seen" messages are searched,
 * and all match is set as SEEN, but just the first occurrence of the
 * matching message is returned./*  ww  w. j  a v  a  2s.c om*/
 * @param username the mailbox owner's user name (no @gmail.com required).
 * @param pass the user password protecting this mailbox
 * @param st the SearchTerm built to filter messages
 * @param timeoutMessage the message to show when no such mail found within
 *            timeout
 * @param timeout The maximum amount of time to wait in milliseconds.
 * @return a last from the new messages thats match the st conditions
 */
public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st,
        final String timeoutMessage, final long timeout) {
    String host = "imap.gmail.com";
    final long retryTime = 1000;

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.trust", "*");
    EMail email = null;
    Session session = Session.getDefaultInstance(props, null);
    try {
        Store store = session.getStore("imaps");
        store.connect(host, username, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox)
                .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS)
                .withMessage(timeoutMessage);
        email = waitForMail.until(new Function<Folder, EMail>() {
            @Override
            public EMail apply(final Folder inbox) {
                EMail email = null;
                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
                SearchTerm sst = new AndTerm(ft, st);
                try {
                    inbox.getMessageCount();
                    Message[] messages = inbox.search(sst);
                    for (Message message : messages) {
                        message.setFlag(Flag.SEEN, true);
                    }
                    if (messages.length > 0) {
                        return new EMail(messages[0]);
                    }
                } catch (MessagingException e) {
                    Assert.fail(e.getMessage());
                }
                return email;
            }
        });
        inbox.close(false);
        store.close();
    } catch (MessagingException e) {
        Assert.fail(e.getMessage());
    }
    return email;
}

From source file:com.synapticpath.naica.selenium.SeleniumUtils.java

License:Open Source License

/**
 * Call this method to find a WebElement. Several parameters are supported.
 * /*from w  w  w  . j  ava2 s  . c om*/
 * @param elementSelector
 *            Will be used as primary criteria to find an element.
 * @param visible
 *            When not null, will be evaluated for visibility on page. That is, the desired element must
 *            also be visible when true, or invisible when false.
 * @param withText
 *            if specified, the element.getText must match also.
 * @param timeout
 *            positive number of seconds to wait
 * @return the {@link WebElement} when found, null if not found in timeout reached first.
 */
public static WebElement findElementWithTimeout(final SeleniumSelector elementSelector, final Boolean visible,
        final String withText, int timeout) {

    final WebDriver driver = SeleniumTestContext.getInstance().getDriver();

    FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(timeout > -1 ? timeout : MAX_WAIT, TimeUnit.SECONDS)
            .pollingEvery(POLL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class)
            .ignoring(TimeoutException.class);

    try {
        return wait.until((WebDriver d) -> {
            WebElement e = d.findElement(elementSelector.toBySelector());
            if (e != null && (withText == null || e.getText().contains(withText))
                    && (visible == null || visible && e.isDisplayed() || !visible && !e.isDisplayed())) {
                return e;
            }
            return null;
        });
    } catch (TimeoutException te) {
        logger.severe(format("Element selected by %s, visible:%s, withText:%s was not found in time.",
                elementSelector, visible, withText));
    }

    return null;

}

From source file:com.synapticpath.naica.selenium.SeleniumUtils.java

License:Open Source License

/**
 * Polls through Selenium driver until an element matched by given {@link SeleniumSelector} can no longer be found.
 * //w w w.  ja v a2s.  c om
 * @param elementSelector
 * @param timeout
 *            number of seconds to wait if positive number, otherwise
 *            default will be applied.
 * @return true when element disappears, false otherwise
 */

public static boolean waitUntilElementGoneWithTimeout(final SeleniumSelector elementSelector,
        final int timeout) {

    final WebDriver driver = SeleniumTestContext.getInstance().getDriver();

    FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(timeout > -1 ? timeout : MAX_WAIT, TimeUnit.SECONDS)
            .pollingEvery(POLL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);

    try {
        return wait.until((WebDriver d) -> d.findElements(elementSelector.toBySelector()).size() == 0);

    } catch (TimeoutException te) {
        logger.severe(
                format("Element selected by %s did not go away in time.", elementSelector.toBySelector()));
    }

    return false;
}

From source file:com.synapticpath.naica.selenium.SeleniumUtils.java

License:Open Source License

/**
 * Polls through Selenium driver until:/*from  w w  w .  j a  va  2 s.c  o m*/
 * a) browser URL contains desired String
 * b) timeout is reached
 * 
 * @param text
 * @param timeout
 * @return true when url contains the text, false if timeout reached.
 */
public static boolean waitUntilUrlContains(final String text, int timeout) {

    final WebDriver driver = SeleniumTestContext.getInstance().getDriver();

    FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(timeout > -1 ? timeout : MAX_WAIT, TimeUnit.SECONDS)
            .pollingEvery(POLL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);

    try {
        return wait.until(ExpectedConditions.urlContains(text));
    } catch (TimeoutException te) {
        logger.severe(format("Url did not contain text %s in time.", text));
    }

    return false;
}

From source file:com.tractionsoftware.reshoot.teampage.ProteusPage.java

License:Apache License

public void waitForClassName(int timeoutSeconds, final String className) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(timeoutSeconds, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);
    wait.until(new Function<WebDriver, WebElement>() {
        @Override/*w w  w.  j  a  v  a2s .c  o m*/
        public WebElement apply(WebDriver driver) {
            return driver.findElement(By.className(className));
        }
    });
}

From source file:com.tractionsoftware.reshoot.teampage.ProteusPage.java

License:Apache License

public void waitForClassName(int timeoutSeconds, final String className, WebElement scope) {
    Wait<WebElement> wait = new FluentWait<WebElement>(scope).withTimeout(timeoutSeconds, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);
    wait.until(new Function<WebElement, WebElement>() {
        @Override//from  w w w  .j  a va2s  .co  m
        public WebElement apply(WebElement scope) {
            return scope.findElement(By.className(className));
        }
    });
}

From source file:com.tractionsoftware.reshoot.util.TractionWebdriverUtils.java

License:Apache License

public static WebElement waitForElement(WebDriver driver, final By by, int seconds) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(seconds, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);
    WebElement elm = wait.until(new Function<WebDriver, WebElement>() {
        @Override/*from   w ww .  ja v a  2 s.c o m*/
        public WebElement apply(WebDriver driver) {
            return driver.findElement(by);
        }
    });
    return elm;
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * internal method which actually checks whether the given element is
 * exists./*from  ww  w  .  ja  v  a2s  .  c  o  m*/
 * 
 * @param searchPath
 *            the search path
 * @return the web element
 * @throws Exception
 *             the exception
 */
private WebElement checkElementPresence(final String searchPath) throws Exception {
    WebDriver driver = getDriver();
    WebElement webElement = null;
    String locator = searchPath;
    final Logger log = getLog();
    int count = getRetryCount();
    setCommandStartTime(getCurrentTime());
    final By searchBy = getLocatorType(locator);
    final Long retryMillis = 1000L;

    try {

        Function<WebDriver, WebElement> findElementFunction = new FindElementFunction<WebDriver, WebElement>(
                searchBy);

        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout((count * retryMillis), TimeUnit.MILLISECONDS)
                .pollingEvery(retryInterval, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class)
                .ignoring(WebDriverException.class);

        webElement = wait.until(findElementFunction);

    } catch (Exception e) {
        log.error("Element [ " + searchPath + " ] Not Found", e);
    }

    if (webElement != null) {
        try {
            log.info("Element [ " + searchBy.toString() + " ] Found");
            JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
            jsExecutor.executeScript("arguments[0].scrollIntoView(false);", webElement);
        } catch (Exception ex) {
            log.error("Exception occured while scrolling to the element.", ex);
        }
    } else {
        throw new Exception("Element " + searchPath);
    }

    return webElement;
}