Example usage for org.openqa.selenium WebDriver findElements

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

Introduction

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

Prototype

@Override
List<WebElement> findElements(By by);

Source Link

Document

Find all elements within the current page using the given mechanism.

Usage

From source file:com.novartis.opensource.yada.test.YADAAdminTest.java

License:Apache License

/**
 * Asserts that menu bar has either 3 disabled buttons, when app has 0 queries, or 0 disabled buttons when
 * it has at least 1 query// ww w. j  a  va  2 s  .c o  m
 * @throws InterruptedException if any thread has interrupted the current thread 
 */
private void validateMenues() throws InterruptedException {
    WebDriver d = getDriver();
    //    new WebDriverWait(d,20).until(ExpectedConditions.presenceOfElementLocated(By.id("app-qname-"+this.app)));

    List<WebElement> emptyWarning = d.findElements(By.className("dataTables_empty"));
    Thread.sleep(3000);
    String xpath = "//nav[contains(@class,\"main-menu\")]//li[contains(@class,\"disabled\")]/a[not(@href)]";
    List<WebElement> menuButtons = d.findElements(By.xpath(xpath));
    Thread.sleep(3000); //sometimes the next step takes time to appear, but WebDriverWait will throw an exception in the default case
    if (emptyWarning.size() > 0)
        Assert.assertEquals(menuButtons.size(), 3);
    else
        Assert.assertEquals(menuButtons.size(), 0);
}

From source file:com.novartis.opensource.yada.test.YADAAdminTest.java

License:Apache License

/**
 * Makes assertions about default state of query editor modal
 *//* w w w.j av a 2 s  . com*/
private void validateQueryEditor() {
    WebDriver d = getDriver();
    WebElement e = d.findElement(By.id("query-editor-container"));
    Assert.assertTrue(e.isDisplayed());
    List<WebElement> list = d.findElements(By.xpath("//div[contains(@class,\"panel \")]"));
    Assert.assertEquals(list.size(), 3);
    list = d.findElements(By.xpath("//div[contains(@class,\"panel \") and @style=\"display: none;\"]"));
    Assert.assertEquals(list.size(), 2);
    new WebDriverWait(d, 20).until(ExpectedConditions.presenceOfElementLocated(By.id("collapseOne")));
    Assert.assertTrue(d.findElement(By.id("collapseOne")).isDisplayed()); // comments
    Assert.assertFalse(d.findElement(By.id("collapseTwo")).isDisplayed()); // security
    Assert.assertFalse(d.findElement(By.id("collapseThree")).isDisplayed()); // params

    // validate buttons in footer
    list = d.findElements(
            By.xpath("//div[@id=\"query-editor-container\"]//div[contains(@class,\"modal-footer\")]/button"));
    Assert.assertEquals(list.size(), 5);
    list = d.findElements(By.xpath(
            "//div[@id=\"query-editor-container\"]//div[contains(@class,\"modal-footer\")]/button[@style=\"display: none;\"]"));
    Assert.assertEquals(list.size(), 3);
    Assert.assertTrue(d.findElement(By.id("button-save")).isDisplayed());
    Assert.assertTrue(d.findElement(By.id("button-cancel")).isDisplayed());
    Assert.assertFalse(d.findElement(By.id("button-rename")).isDisplayed());
    Assert.assertFalse(d.findElement(By.id("button-copy")).isDisplayed());
    Assert.assertFalse(d.findElement(By.id("button-delete")).isDisplayed());
}

From source file:com.novartis.opensource.yada.test.YADAAdminTest.java

License:Apache License

/**
 * <ol>/* w  ww. j  a va  2s .  c  o m*/
 * <li>Opens the query editor</li>
 * <li>Validates all the buttons are present</li>
 * <li>Opens the security panel</li>
 * <li>Sets URL validation policy</li>
 * <li>Sets TokenValidation policy</li>
 * <li>Sets ExecutionPolicy</li>
 * <li>Sets ContentPolicy</li>
 * </ol>
 * @throws InterruptedException if any thread has interrupted the current thread
 * @throws IOException when the test URL can't be accessed 
 */
@Test(dependsOnMethods = { "testNewQueryForNewAppSave" })
public void testSecurityConfigForQuery() throws InterruptedException, IOException {
    WebDriver d = getDriver();
    String protector = this.app + " Test Protector";
    this.createQueryForNewApp(" Test Protector", "SELECT 1 AS COL1", "save");
    WebElement save = d.findElement(By.id("button-save"));

    // validate ui
    WebElement e = new WebDriverWait(d, 20)
            .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".alert-success")));
    String expected = "Hooray! Query " + protector + " was saved successfully.";
    Assert.assertEquals(e.getText(), expected);
    Assert.assertFalse(save.isDisplayed());

    // close dialog
    d.findElement(By.id("button-cancel")).click();
    Thread.sleep(3000);

    // restore app-mgr
    d.findElement(By.id("app")).click();
    new WebDriverWait(d, 20).until(ExpectedConditions.presenceOfElementLocated(By.id("app-mgr")));
    Thread.sleep(3000);

    // nav to queries
    d.findElement(By.id("app-qname-" + this.app)).click();
    Thread.sleep(3000);

    // open query for edit
    String qname = this.app + " Test Save";
    d.findElement(By.xpath("//*[text()[contains(.,\"" + qname + "\")]]")).click();
    this.switchToActiveElement(d, 3000);
    new WebDriverWait(d, 20)
            .until(ExpectedConditions.presenceOfElementLocated(By.id("query-editor-container")));

    // validate buttons
    List<WebElement> list = d.findElements(By.cssSelector("#query-editor-container .modal-footer button"));
    Assert.assertEquals(list.size(), 5);
    for (WebElement b : list) {
        Assert.assertTrue(b.isDisplayed() && b.isEnabled());
    }

    // open security panel
    d.findElement(By.id("headingTwo")).click();
    Thread.sleep(3000);

    // Confirm query result
    String result = getUrl(qname);
    l.debug("EXPECT NORMAL RESULT:\n" + result);
    Assert.assertTrue(result.contains(qname) && result.toUpperCase().contains("\"ROWS\":[{\"COL1\":\"1\"}]"));

    // "Mark this query as secure" and confirm "unauth"
    d.findElement(By.id("secure-query-ckbx")).click();
    d.findElement(By.id("button-save")).click();
    Thread.sleep(3000);
    result = getUrl(qname);
    l.debug("EXPECT UNAUTHORIZED RESULT:\n" + result);
    //   should be rejected at this point due to checkbox + lack of plugin
    Assert.assertFalse(result.contains(qname) && result.toUpperCase().contains("\"ROWS\":[{\"COL1\":\"1\"}]"));
    Assert.assertTrue(result.contains("Server returned HTTP response code: 403"));
    d.findElement(By.id("button-cancel")).click(); // back to app-mgr
    Thread.sleep(3000);

    // open query for edit
    e = new WebDriverWait(d, 20).until(ExpectedConditions
            .presenceOfElementLocated(By.xpath("//*[text()[contains(.,\"" + qname + "\")]]")));
    e.click();
    this.switchToActiveElement(d, 3000);
    new WebDriverWait(d, 20)
            .until(ExpectedConditions.presenceOfElementLocated(By.id("query-editor-container")));

    if (!d.findElement(By.id("secure-query-ckbx")).isDisplayed()) {
        d.findElement(By.id("headingTwo")).click();
        Thread.sleep(3000);
    }

    // confirm "Mark this query as not secure"
    d.findElement(By.id("secure-query-ckbx")).click();
    d.findElement(By.id("button-save")).click();
    Thread.sleep(3000);
    result = getUrl(qname);
    l.debug("EXPECT NORMAL RESULT:\n" + result);
    //   should be accepted, as box is unchecked
    Assert.assertTrue(result.contains(qname) && result.toUpperCase().contains("\"ROWS\":[{\"COL1\":\"1\"}]"));
    d.findElement(By.id("button-cancel")).click();
    Thread.sleep(3000);

    // open query for edit
    e = new WebDriverWait(d, 20).until(ExpectedConditions
            .presenceOfElementLocated(By.xpath("//*[text()[contains(.,\"" + qname + "\")]]")));
    e.click();
    this.switchToActiveElement(d, 3000);
    new WebDriverWait(d, 20)
            .until(ExpectedConditions.presenceOfElementLocated(By.id("query-editor-container")));

    if (!d.findElement(By.id("secure-query-ckbx")).isDisplayed()) {
        d.findElement(By.id("headingTwo")).click();
    }
    //    l.debug("Sleeping for 2 minutes to enable manual investigation");
    Thread.sleep(3000);
    // validate all components
    //   what is there before any data entry?

    WebElement plugin = d.findElement(By.className("policy-plugin"));
    WebElement policyArg = d.findElement(By.className("policy-arg"));
    WebElement argString = d.findElement(By.className("arg-string"));

    Assert.assertTrue(d.findElement(By.className("policy-group")).isDisplayed());
    Assert.assertTrue(plugin.isDisplayed());
    Assert.assertTrue(d.findElement(By.className("policy-action")).isDisplayed());
    Assert.assertTrue(argString.isDisplayed());
    Assert.assertTrue(d.findElement(By.className("policy-type")).isDisplayed());
    Assert.assertTrue(policyArg.isDisplayed());
    Assert.assertTrue(d.findElement(By.className("remove-policy")).isDisplayed());

    // enter policies

    //   what is there after each policy entry  
    plugin.sendKeys("Gatekeeper");
    Select policyType = new Select(d.findElement(By.className("policy-type")));
    policyType.selectByVisibleText("URL Pattern Matching");
    policyArg.clear();
    policyArg.sendKeys("auth.path.rx=^(https?://)?localhost:8080/.+$");
    Assert.assertEquals(argString.getText(), "auth.path.rx=^(https?://)?localhost:8080/.+$");

    Select policyAction = new Select(d.findElement(By.className("policy-action")));
    policyAction.selectByValue("save");
    Thread.sleep(2000);
    policyAction.selectByValue("add-same");
    //Thread.sleep(3000);

    String xpath = "//div[contains(@class,\"security-options\")][2]";
    e = new WebDriverWait(d, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));

    List<WebElement> policies = d.findElements(By.className("security-options"));
    List<WebElement> policyTypes = d.findElements(By.className("policy-type"));
    List<WebElement> policyArgs = d.findElements(By.className("policy-arg"));

    policyType = new Select(policyTypes.get(1));
    policyType.selectByVisibleText("Execution Policy (Indices)");
    policyArgs.get(1).clear();
    policyArgs.get(1).sendKeys("execution.policy.indices=0:getToken()");
    Assert.assertTrue(d.findElement(By.className("policy-protector")).isDisplayed());
    d.findElement(By.className("policy-protector")).sendKeys(protector);

    policyAction.selectByValue("save");
    Thread.sleep(3000);
    policyAction.selectByValue("add-same");
    //Thread.sleep(3000);

    xpath = "//div[contains(@class,\"security-options\")][3]";
    e = new WebDriverWait(d, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));

    policies = d.findElements(By.className("security-options"));
    policyTypes = d.findElements(By.className("policy-type"));
    policyArgs = d.findElements(By.className("policy-arg"));
    List<WebElement> policyProtectors = d.findElements(By.className("policy-protector"));

    policyType = new Select(policyTypes.get(2));
    policyType.selectByVisibleText("Execution Policy (Columns)");
    policyArgs.get(2).clear();
    policyArgs.get(2).sendKeys("execution.policy.columns=0:getToken()");

    Assert.assertEquals(policyProtectors.size(), 2);
    policyProtectors.get(1).sendKeys(protector);

    policyAction.selectByValue("save");
    Thread.sleep(2000);
    policyAction.selectByValue("add-same");

    xpath = "(//input[contains(@class,\"security-options\")])[3]";
    e = new WebDriverWait(d, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));

    policies = d.findElements(By.className("security-options"));
    policyTypes = d.findElements(By.className("policy-type"));
    policyArgs = d.findElements(By.className("policy-arg"));
    policyProtectors = d.findElements(By.className("policy-protector"));

    policyType = new Select(policyTypes.get(3));
    policyType.selectByVisibleText("Content Policy");
    policyArgs.get(3).clear();
    policyArgs.get(3).sendKeys("content.policy.predicate=x=y");

    expected = "auth.path.rx=^(https?://)?localhost:8080.+$,execution.policy.indices=0:getToken(),execution.policy.columns=token:getToken(),content.policy.predicate=x=y";
    Assert.assertEquals(argString.getText(), expected);

    // save 
    //   multiple ways to save? (not yet)
    policyAction.selectByValue("save");

    // TODO validate data is in db
    // TODO validate security works? or is this just for a standard integration test?
    // TODO alert user when security setting is invalid or unsavable for any reason
    // TODO alert user to save security settings (this may enable safety net after all)
    // TODO parse security param into UI when appropriate (it currently doesn't) 

    d.findElement(By.id("button-save")).click();
    Thread.sleep(3000);

    d.findElement(By.id("app")).click();
    new WebDriverWait(d, 20).until(ExpectedConditions.presenceOfElementLocated(By.id("app-mgr")));
    Thread.sleep(3000);

    // nav to queries
    d.findElement(By.id("app-qname-" + this.app)).click();
    Thread.sleep(3000);

    // open query for edit
    d.findElement(By.xpath("//*[text()[contains(.,\"" + qname + "\")]]")).click();
    this.switchToActiveElement(d, 3000);
    new WebDriverWait(d, 20)
            .until(ExpectedConditions.presenceOfElementLocated(By.id("query-editor-container")));

    d.findElement(By.id("headingThree")).click();
    Thread.sleep(3000);
    String actual = d.findElement(By.cssSelector("$('#default-params tbody tr:eq(0) td input:eq(1)')"))
            .getAttribute("value");
    Assert.assertEquals(actual, expected);

}

From source file:com.numenta.htmit.mobile.test.behavior.TestUtilities.java

License:Open Source License

public static void checkBoxes(WebDriver driver, String deviceName) throws InterruptedException {
    List<WebElement> checkbox = driver.findElements(By.className("android.widget.CheckBox"));
    checkbox.get(1).click();/*from www.  j a va 2 s  .  co m*/
    checkbox.get(0).click();
    checkbox.get(1).click();
}

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

License:Apache License

/**
 * This method pretends to check if the element is present, if it doesn't
 * then don't wait, if element is present, wait for its invisibility.
 * true - element  invisible/*from  w  ww. j  a v a 2  s  .  c o m*/
 * false - element visible
 * @param driver
 * @param locator
 * @param timeout
 */
public boolean WaitForElementInvisibility(final WebDriver driver, final By locator, final Integer timeout) {
    this.log.debug("WaitForElementInvisibility::Enter");
    this.log.debug("Locator: " + locator.toString());
    boolean isElemVisible = false;
    ExecutorService executor = null;

    try {

        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

        try {
            class RunnableObject implements Runnable {

                private boolean isVisible;

                public boolean getVisibility() {
                    return this.isVisible;
                }

                public void run() {
                    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                            .withTimeout(timeout, TimeUnit.SECONDS).pollingEvery(50, TimeUnit.MILLISECONDS);

                    // Wait for element invisible
                    this.isVisible = wait.until(new Function<WebDriver, Boolean>() {

                        @Override
                        public Boolean apply(WebDriver d) {
                            try {
                                List<WebElement> listElements = d.findElements(locator);
                                if (listElements.size() > 0) {
                                    WebElement elem = listElements.get(0);
                                    return (!elem.isDisplayed()) ? true : false;
                                }
                                // The element does not exit, i.e., is not visible and even present
                                return true;
                            } catch (StaleElementReferenceException sere) {
                                return false;
                            }
                        }
                    });
                }
            }

            RunnableObject r = new RunnableObject();
            executor = Executors.newSingleThreadExecutor();
            executor.submit(r).get(timeout + 2, TimeUnit.SECONDS);
            isElemVisible = r.getVisibility();
        } 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! Looking for: " + locator.toString());
                this.log.warn(ee.toString());
            } else {
                this.log.warn("Execution Exception");
                this.log.warn(ee.toString());
            }
        } catch (java.util.concurrent.TimeoutException cte) {
            this.log.warn("Thread timeout exceeded! Looking for: " + locator.toString());
            this.log.warn(cte.toString());
        } catch (Exception e) {
            this.log.error("Exception");
            this.log.catching(e);
        }

        if (executor != null) {
            executor.shutdown();
        }

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    } catch (Exception ge) {
        this.log.error("Exception");
        this.log.catching(ge);
    }
    this.log.debug("WaitForElementInvisibility::Exit");

    return isElemVisible;
}

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

License:Apache License

/**
 * This method pretends to check if the element is present, if it doesn't
 * we wait for presence for a specific timeout (input), after this, we will
 * wait for element visible. And, if the element is present then we have to
 * check if is visible if not wait for visibility.
 *
 * @param driver//from w w w .j  a  va2s  .c o m
 * @param locator
 * @param timeout
 */
public WebElement WaitForElementPresenceAndVisible(final WebDriver driver, final By locator,
        final Integer timeout) {
    this.log.debug("WaitForElementPresenceAndVisible::Enter");
    this.log.debug("Locator: " + locator.toString());
    WebElement element = null;
    ExecutorService executor = null;
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

    try {

        class RunnableObject implements Runnable {

            private WebElement theElement;

            public RunnableObject(WebElement theElement) {
                this.theElement = theElement;
            }

            public WebElement getValue() {
                return this.theElement;
            }

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

                // Wait for element visible
                this.theElement = wait.until(new Function<WebDriver, WebElement>() {

                    @Override
                    public WebElement apply(WebDriver d) {
                        try {
                            List<WebElement> listElem = d.findElements(locator);
                            if (listElem.size() > 0) {
                                WebElement elem = listElem.get(0);
                                if (elem != null
                                        && ((elem.isEnabled() == true) && (elem.isDisplayed() == true))) {
                                    return elem;
                                }
                                return null;
                            }
                            return null;
                        } catch (StaleElementReferenceException sere) {
                            return null;
                        }
                    }
                });
            }
        }

        RunnableObject r = new RunnableObject(element);
        executor = Executors.newSingleThreadExecutor();
        executor.submit(r).get(timeout + 2, TimeUnit.SECONDS);
        element = r.getValue();
    } 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! Looking for: " + locator.toString());
        } else {
            this.log.warn("Execution Exception");
            this.log.warn(ee.toString());
        }
    } catch (java.util.concurrent.TimeoutException cte) {
        this.log.warn("Thread timeout exceeded! Looking for: " + locator.toString());
        this.log.warn(cte.toString());
    } catch (Exception e) {
        this.log.error("Exception");
        this.log.catching(e);
    }

    if (executor != null) {
        executor.shutdown();
    }

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    this.log.debug("WaitForElementPresenceAndVisible::Exit");
    return element;
}

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

License:Apache License

/**
 * This method pretends to check if the element is present, if it doesn't
 * we wait for presence for a specific timeout (input).
 *
 * @param driver/*from   w  ww . j  a va2 s  . c  o  m*/
 * @param locator
 */
public WebElement WaitForElementPresence(final WebDriver driver, final By locator, final Integer timeout,
        final Integer pollingtime) {
    this.log.debug("WaitForElementPresence::Enter");
    this.log.debug("Locator: " + locator.toString());
    WebElement element = null;
    ExecutorService executor = null;
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

    try {

        class RunnableObject implements Runnable {

            private WebElement theElement = null;

            public RunnableObject() {
            }

            public WebElement getValue() {
                return this.theElement;
            }

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

                // Wait for element visible
                this.theElement = wait.until(new Function<WebDriver, WebElement>() {

                    @Override
                    public WebElement apply(WebDriver d) {
                        try {
                            List<WebElement> listElem = d.findElements(locator);
                            if (listElem.size() > 0) {
                                WebElement elem = listElem.get(0);
                                if (elem.isEnabled()) {
                                    return elem;
                                }
                                return null;
                            }
                            return null;
                        } catch (StaleElementReferenceException sere) {
                            return null;
                        }
                    }
                });
            }
        }

        RunnableObject r = new RunnableObject();
        executor = Executors.newSingleThreadExecutor();
        executor.submit(r).get(timeout + 2, TimeUnit.SECONDS);
        element = r.getValue();
    } 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! Looking for: " + locator.toString());
        } else {
            this.log.warn("Execution Exception");
            this.log.warn(ee.toString());
        }
    } catch (java.util.concurrent.TimeoutException cte) {
        this.log.warn("Thread timeout exceeded! Looking for: " + locator.toString());
        this.log.warn(cte.toString());
    } catch (Exception e) {
        this.log.error("Exception");
        this.log.catching(e);
    }

    if (executor != null) {
        executor.shutdown();
    }

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    this.log.debug("WaitForElementPresence::Exit");
    return element;
}

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

License:Apache License

/**
 * This method pretends to check if the element is present, if it doesn't
 * then don't wait, if element is present, wait for its invisibility.
 *
 * @param driver/*from www. j  a v  a  2  s  .  c  o m*/
 * @param locator
 */
public WebElement WaitForElementVisibility(WebDriver driver, By locator) {
    this.log.debug("WaitForElementVisibility::Enter");
    this.log.debug("Locator: " + locator.toString());

    WebElement element = null;
    List<WebElement> elements = null;
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS)
            .pollingEvery(50, TimeUnit.MILLISECONDS).ignoring(StaleElementReferenceException.class);

    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

    try {
        elements = driver.findElements(locator);
        if (elements.size() > 0) {
            // wait for element to appear
            element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
            this.log.debug("Get element visible.");
        } else {
            this.log.warn("No elements found!");
        }
    } catch (Exception e) {
        this.log.warn("Something went wrong searching for vi: " + locator.toString());
        this.log.catching(e);
    }

    // ------------ ALWAYS REQUIRE TO SET THE DEFAULT VALUE --------------------
    // when set a new implicitlyWait timeout, we have to set the default
    // in order to not destroy other invocations of findElement ('WebDriver').
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    this.log.debug("WaitForElementVisibility::Exit");
    return element;
}

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

License:Apache License

/**
 * The method will wait for the frame to be available to usage. To ensure that
 * we check if an element exist inside (example a new element that refresh the
 * frame).//www  .j  av a 2 s  .  c o m
 *
 * @param driver
 * @param locator
 */
public void WaitForFrameReady(WebDriver driver, final By locator) {
    this.log.debug("WaitForFrameReady::Enter");
    this.log.debug("Locator: " + locator.toString());

    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(100,
            TimeUnit.MILLISECONDS);

    wait.until(new ExpectedCondition<Boolean>() {

        @Override
        public Boolean apply(WebDriver d) {
            Boolean elementExist = false;
            List<WebElement> listElements = d.findElements(locator);

            if (listElements.size() > 0) {
                elementExist = true;
            }
            return elementExist;
        }
    });

    this.log.debug("WaitForFrameReady::Exit");
}

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

License:Apache License

/**
 * This method pretends to assert the element is not present and return a
 * boolean = true if it isn't. This method also allow user to set a specify timeout.
 *
 * @param driver/* ww  w .  j av  a 2  s.  c o  m*/
 * @param locator
 * @param timeout
 */
public Boolean WaitForElementNotPresent(final WebDriver driver, final By locator, final Integer timeout) {
    this.log.debug("WaitForElementNotPresent::Enter");
    Boolean notPresent = false;
    ExecutorService executor = null;
    this.log.debug("Locator: " + locator.toString());
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

    try {

        class RunnableObject implements Runnable {

            private Boolean NotPresent;

            public RunnableObject(Boolean NotPresent) {
                this.NotPresent = NotPresent;
            }

            public Boolean getValue() {
                return this.NotPresent;
            }

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

                // Wait for element visible
                this.NotPresent = wait.until(new Function<WebDriver, Boolean>() {

                    @Override
                    public Boolean apply(WebDriver d) {
                        try {
                            List<WebElement> listElem = d.findElements(locator);
                            if (listElem.size() == 0) {
                                return true;
                            }
                            return false;
                        } catch (StaleElementReferenceException sere) {
                            return true;
                        }
                    }
                });
            }
        }

        RunnableObject r = new RunnableObject(notPresent);
        executor = Executors.newSingleThreadExecutor();
        executor.submit(r).get(timeout + 2, TimeUnit.SECONDS);
        notPresent = r.getValue();
    } 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! Looking for: " + locator.toString());
        } else {
            this.log.warn("Execution Exception");
            this.log.warn(ee.toString());
        }
    } catch (java.util.concurrent.TimeoutException cte) {
        this.log.warn("Thread timeout exceeded! Looking for: " + locator.toString());
        this.log.warn(cte.toString());
    } catch (Exception e) {
        this.log.error("Exception");
        this.log.catching(e);
    }

    if (executor != null) {
        executor.shutdown();
    }

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    this.log.debug("WaitForElementNotPresent::Exit");
    return notPresent;
}