Example usage for org.openqa.selenium.support.ui ExpectedConditions presenceOfElementLocated

List of usage examples for org.openqa.selenium.support.ui ExpectedConditions presenceOfElementLocated

Introduction

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

Prototype

public static ExpectedCondition<WebElement> presenceOfElementLocated(final By locator) 

Source Link

Document

An expectation for checking that an element is present on the DOM of a page.

Usage

From source file:org.wso2.carbon.greg.publisher.utils.ESWebDriver.java

License:Open Source License

/**
 * This method will wait until a given element is present in the page for a given amount of time
 *
 * @param by          Element to be present in the current page
 * @param waitTimeSec Time to wait in seconds
 *//* w  w w  .j  a  va2s. c  o  m*/
private void waitTillElementPresent(By by, int waitTimeSec) {
    WebDriverWait wait = new WebDriverWait(driver, waitTimeSec);
    wait.until(ExpectedConditions.presenceOfElementLocated(by));
}

From source file:org.wso2.das.ui.integration.test.ActivityDashboardUITestCase.java

License:Open Source License

@Test(groups = "wso2.das", description = "Verifying XSS Vulnerability in Activity Dashboard")
public void testXSSVulnerability() throws Exception {
    boolean isVulnerable = false;
    // Add stream with persistence
    StreamDefinitionBean streamDefinition = getStreamDefinition();
    AnalyticsTable analyticsTableDefinition = getAnalyticsTableDefinition();
    Utils.addStreamAndPersistence(this.webServiceClient, this.persistenceClient, streamDefinition,
            analyticsTableDefinition);/*from   w  w  w. j  ava 2s . c o m*/

    // Add event receiver
    boolean status = this.eventReceiverClient.addOrUpdateEventReceiver("activity_receiver", getResourceContent(
            ActivityDashboardUITestCase.class, "eventreceivers" + File.separator + "activity_receiver.xml"));
    Thread.sleep(10000);

    // Send an Event (to generate an activity)
    Event event = new Event(null, System.currentTimeMillis(), new Object[0], new Object[] { "activity_1" },
            new Object[] { "<script>document.getElementById('workArea').id='vulnerable';</script>" });
    this.dataPublisherClient.publish(STREAM_NAME, STREAM_VERSION, event);
    Utils.checkAndWaitForTableSize(webServiceClient, TABLE_NAME, 1);

    // Login to Management Console
    driver.get(getLoginURL());
    driver.findElement(By.id("txtUserName")).clear();
    driver.findElement(By.id("txtUserName"))
            .sendKeys(dasServer.getContextTenant().getContextUser().getUserName());
    driver.findElement(By.id("txtPassword")).clear();
    driver.findElement(By.id("txtPassword"))
            .sendKeys(dasServer.getContextTenant().getContextUser().getPassword());
    driver.findElement(By.cssSelector("input.button")).click();
    driver.findElement(By.id("menu-panel-button4")).click();

    // Goto Activity Dashboard page
    String pageUrl = backendURL.split("/services/")[0] + "/carbon/activitydashboard/index.jsp?";
    List<NameValuePair> pageParams = new ArrayList<>();
    pageParams.add(new BasicNameValuePair("region", "region1"));
    pageParams.add(new BasicNameValuePair("item", "activity_dashboard"));
    pageUrl += URLEncodedUtils.format(pageParams, "UTF-8");
    driver.get(pageUrl);
    WebDriverWait webDriverWait = new WebDriverWait(driver, 5);
    try {
        driver.findElement(By.cssSelector("#workArea > div.sectionSub > div.buttonRow > input:nth-child(1)"))
                .click();
        Thread.sleep(1000 * 3);

        driver.findElement(By.cssSelector("#workArea > div.sectionSeperator > a")).click();
        Thread.sleep(1000 * 3);

        driver.findElement(By.cssSelector("#records_activity_1 > table > tbody > tr > td > i > a")).click();
        Thread.sleep(1000 * 5);

        webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("vulnerable")));
        // If not vulnerable, element with #vulnerable would not get injected
        // Therefore it'll throw an exception mentioning that.
        isVulnerable = true;
    } catch (Exception ignored) {
    }
    Assert.assertFalse(isVulnerable);
    driver.close();
}

From source file:org.wso2.developerstudio.codenvy.ui.integration.test.utils.DevSWebDriver.java

License:Open Source License

/**
 * This method will wait untill a given element is present in the page for a given amount of time
 *
 * @param by          Element to be present in the current page
 * @param waitTimeSec Time to wait in seconds
 *//* w  w w.j a va2  s .c o  m*/
private void waitTillElementPresent(By by, int waitTimeSec) {
    WebDriverWait wait;
    wait = new WebDriverWait(driver, waitTimeSec);
    wait.until(ExpectedConditions.presenceOfElementLocated(by));
}

From source file:org.wso2.ds.ui.integration.test.dashboard.GadgetLoadOrderingTest.java

License:Open Source License

/**
 * Adds a new block and check whether the block presents in the view mode.
 *
 * @throws MalformedURLException/*from  ww  w  .j a  v a  2 s.c om*/
 * @throws XPathExpressionException
 */
@Test(groups = "wso2.ds.dashboard", description = "test the gadget load ordering")
public void testGadgetLoadOrder() throws MalformedURLException, XPathExpressionException {
    redirectToLocation("portal", "dashboards");
    getDriver().findElement(By.cssSelector("#" + DASHBOARD_TITLE + " a.ues-edit")).click();
    String[][] gadgetMappings = { { "textbox-TestGadgetLowPriority", "a" },
            { "textbox-TestGadgetMediumPriority", "b" }, { "textbox-TestGadgetHighPriority", "c" } };
    String script = generateAddGadgetScript(gadgetMappings);
    selectPane("gadgets");
    getDriver().executeScript(script);
    clickViewButton();
    for (String winHandle : getDriver().getWindowHandles()) {
        getDriver().switchTo().window(winHandle);
    }
    boolean correctLoadOrder = false;
    Date timeBeforeLoadingHighPriority = new Date();
    (new WebDriverWait(getDriver(), 10))
            .until(ExpectedConditions.presenceOfElementLocated(By.id("textbox-TestGadgetHighPriority-0")));
    Date timeBeforeLoadingMediumPriority = new Date();
    (new WebDriverWait(getDriver(), 10))
            .until(ExpectedConditions.presenceOfElementLocated(By.id("textbox-TestGadgetMediumPriority-0")));
    Date timeBeforeLoadingLowPriority = new Date();
    (new WebDriverWait(getDriver(), 10))
            .until(ExpectedConditions.presenceOfElementLocated(By.id("textbox-TestGadgetLowPriority-0")));
    Date timeAfterLoading = new Date();
    if (timeBeforeLoadingMediumPriority.getTime() - timeBeforeLoadingHighPriority.getTime() < 5000
            && timeBeforeLoadingLowPriority.getTime() - timeBeforeLoadingMediumPriority.getTime() >= 5000
            && timeAfterLoading.getTime() - timeBeforeLoadingLowPriority.getTime() >= 5000) {
        correctLoadOrder = true;
    }
    Assert.assertEquals(correctLoadOrder, true);
}

From source file:org.wso2.es.ui.integration.test.store.ESStoreSearchGadgetListTestCase.java

License:Open Source License

@Test(groups = "wso2.es.store", description = "Search by newly added asset Version", dependsOnMethods = "testAddAsset")
public void testESStoreSearchNewlyAddedAssetsVersion() throws Exception {
    driver.get(baseUrl + "/store/pages/top-assets");
    driver.findElement(By.cssSelector("i.icon-cog")).click();
    driver.findElement(By.cssSelector("i.icon-sort-down")).click();
    driver.findElement(By.id("search")).click();
    driver.findElement(By.name("overview_version")).clear();
    driver.findElement(By.name("overview_version")).sendKeys(assetVersion);
    new Select(driver.findElement(By.id("overview_category"))).selectByVisibleText(assetCategory);
    driver.findElement(By.id("search-button2")).click();
    driver.findElementPoll(By.linkText(assetName), 10);
    wait.until(ExpectedConditions//from  ww  w  . j a v  a 2s.  c  o m
            .textToBePresentInElementLocated(By.xpath("//h4[contains(.,'" + assetName + "')]"), assetName));
    assertEquals(assetName, driver.findElement(By.cssSelector("h4")).getText(),
            "Newly added gadget is not found in the result of search by version : " + assetVersion);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("img")));
    driver.findElement(By.cssSelector("img")).click();
    wait.until(ExpectedConditions.textToBePresentInElementLocated(By.linkText("Description"), "Description"));
    assertEquals("Version 1.2.3", driver.findElement(By.cssSelector("small")).getText(),
            "Newly added gadget's version is incorrect in the store");
}

From source file:org.wso2.greg.integration.common.ui.page.wsdllist.WsdlListPage.java

License:Open Source License

public boolean visualize(String wsdlName, String registryPath) throws InterruptedException {
    log.info(wsdlName);//from   ww w  .j a  v  a  2s. c  o m
    driver.navigate().refresh();

    //Waiting maximum 30secs to show updated wsdl list.
    WebElement workArea = (new WebDriverWait(driver, 30)).until(ExpectedConditions
            .presenceOfElementLocated(By.xpath(uiElementMapper.getElement("wsdl.list.workarea"))));

    log.info(serviceNameOnServer);
    if (wsdlName.equals(serviceNameOnServer)) {
        log.info("Uploaded Wsdl exists");
        //click on wsdl
        driver.findElement(By.xpath(uiElementMapper.getElement("wsdl.table.first.element"))).click();
        //execute visualize js
        WebElement resourceMain = (new WebDriverWait(driver, 30))
                .until(ExpectedConditions.presenceOfElementLocated(By.id("resourceMain")));
        JavascriptExecutor js = (JavascriptExecutor) driver;
        String jsFunction = "visualizeXML('" + registryPath + "', 'wsdl')";
        js.executeScript(jsFunction);
        Thread.sleep(3000);
        //switch to visualize iframe
        driver.switchTo().frame(driver.findElement(By.xpath("/html/body/div[contains(@class, "
                + "'ui-dialog ui-draggable ui-resizable')]/div[1]/div[@id=\"dialog\"]/iframe")));

        if (driver.findElement(By.xpath(
                "/html/body/table/tbody/tr/td[contains(@class,'source-area')]/div[contains(@class,'definitions')]")) != null) {
            return true;
        }

    } else {
        String resourceXpath = "/html/body/table/tbody/tr[2]/td[3]/table/tbody/tr[2]/td/div/div/form[4]/table/tbody/tr[";
        String resourceXpath2 = "]/td/a";

        for (int i = 2; i < 10; i++) {
            String serviceNameOnAppServer = resourceXpath + i + resourceXpath2;

            String actualResourceName = driver.findElement(By.xpath(serviceNameOnAppServer)).getText();
            log.info("val on app is -------> " + actualResourceName);
            log.info("Correct is    -------> " + wsdlName);

            try {

                if (wsdlName.contains(actualResourceName)) {
                    log.info("Uploaded Wsdl exists");
                    //click on wsdl
                    driver.findElement(By.xpath(uiElementMapper.getElement("wsdl.table.first.element")))
                            .click();
                    //execute visualize js
                    WebElement myDynamicElement = (new WebDriverWait(driver, 30))
                            .until(ExpectedConditions.presenceOfElementLocated(By.id("resourceMain")));
                    JavascriptExecutor js = (JavascriptExecutor) driver;
                    String jsFunction = "visualizeXML('" + registryPath + "', 'wsdl')";
                    js.executeScript(jsFunction);
                    Thread.sleep(3000);
                    //switch to visualize iframe
                    driver.switchTo().frame(driver.findElement(By.xpath("/html/body/div[contains(@class, "
                            + "'ui-dialog ui-draggable ui-resizable')]/div[1]/div[@id=\"dialog\"]/iframe")));

                    if (driver.findElement(By.xpath(
                            "/html/body/table/tbody/tr/td[contains(@class,'source-area')]/div[contains(@class,'definitions')]")) != null) {
                        return true;
                    }

                } else {
                    return false;
                }

            } catch (NoSuchElementException ex) {
                log.info("Cannot Find the Uploaded Wsdl");

            }

        }

    }

    return false;
}

From source file:org.wso2.identity.ui.integration.test.login.ISLoginTestCase.java

License:Open Source License

@Test(groups = "wso2.identity", description = "verify XSS vulnerability fix")
public void testXSSVulnerability() throws Exception {
    boolean isVulnerable = false;
    String authEndpoint = backendURL.substring(0, 22) + "/authenticationendpoint/login.do?";
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("client_id", "XXXXXXXX"));
    params.add(new BasicNameValuePair("commonAuthCallerPath", "/oauth2/authorize"));
    params.add(new BasicNameValuePair("forceAuth", "false"));
    params.add(new BasicNameValuePair("passiveAuth", "false"));
    params.add(new BasicNameValuePair("redirect_uri", "https://localhost/login"));
    params.add(new BasicNameValuePair("response_type", "code"));
    params.add(new BasicNameValuePair("scope", "openid"));
    params.add(new BasicNameValuePair("state", "XXXXXXXX"));
    params.add(new BasicNameValuePair("tenantDomain", "carbon.super"));
    params.add(new BasicNameValuePair("sessionDataKey", "XXXXXXXX"));
    params.add(new BasicNameValuePair("relyingParty", "XXXXXXXX"));
    params.add(new BasicNameValuePair("type", "oidc"));
    params.add(new BasicNameValuePair("sp", "mytestapp"));
    params.add(new BasicNameValuePair("isSaaSApp", "false"));
    params.add(new BasicNameValuePair("authenticators",
            "BasicAuthenticator:LOCAL\"></script>\"//'//"
                    + "<svg onload=(function(){setTimeout(function(){$('body').prepend($('<div></div>')"
                    + ".attr('id','vulnerable'))},2000)})()//"));
    driver = BrowserManager.getWebDriver();
    driver.get(authEndpoint + URLEncodedUtils.format(params, "UTF-8"));
    WebDriverWait webDriverWait = new WebDriverWait(driver, 5);
    try {//from   w  ww.j a  v  a2s .c o m
        webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("vulnerable")));
        // If not vulnerable, element with #vulnerable would not get injected
        // Therefore it'll throw an exception mentioning that.
        isVulnerable = true;
    } catch (Exception ignored) {
    }
    Assert.assertFalse(isVulnerable);
    driver.close();
}

From source file:org.wso2.iot.integration.ui.pages.UIUtils.java

License:Open Source License

public static boolean isElementPresent(Log log, WebDriver driver, By by) {
    try {// www  .  java2  s . co m
        WebDriverWait wait = new WebDriverWait(driver, webDriverTime);
        wait.until(ExpectedConditions.presenceOfElementLocated(by));
        driver.findElement(by);
        return true;
    } catch (NoSuchElementException e) {
        log.error(by.toString() + " is not present");
        return false;
    }

}

From source file:org.xframium.page.element.SeleniumElement.java

License:Open Source License

@Override
protected boolean _waitFor(long timeOut, TimeUnit timeUnit, WAIT_FOR waitType, String value) {
    long startTime = System.currentTimeMillis();
    if ("V_TEXT".equals(getBy().name().toUpperCase())) {
        boolean returnValue = Boolean.parseBoolean(PerfectoMobile.instance().imaging()
                .textExists(getExecutionId(), getDeviceName(), getKey(), (short) timeOut, 50).getStatus());

        PageManager.instance().addExecutionLog(getExecutionId(), getDeviceName(), getPageName(),
                getElementName(), "waitFor", System.currentTimeMillis(), System.currentTimeMillis() - startTime,
                returnValue ? StepStatus.SUCCESS : StepStatus.FAILURE, getKey(), null, 0, "", false,
                new String[] { waitType.name().toLowerCase() });

        return returnValue;
    } else {//from ww  w.  jav a  2  s  .com

        try {

            String currentContext = null;
            if (webDriver instanceof ContextAware)
                currentContext = ((ContextAware) webDriver).getContext();

            WebDriverWait wait = new WebDriverWait(webDriver, timeOut, 250);
            WebElement webElement = null;

            switch (waitType) {
            case CLICKABLE:
                webElement = wait.until(ExpectedConditions.elementToBeClickable(useBy()));
                break;

            case INVISIBLE:
                return wait.until(ExpectedConditions.invisibilityOfElementLocated(useBy()));

            case PRESENT:

                webElement = wait.until(ExpectedConditions.presenceOfElementLocated(useBy()));
                break;

            case SELECTABLE:
                return wait.until(ExpectedConditions.elementToBeSelected(useBy()));

            case TEXT_VALUE_PRESENT:
                return wait.until(ExpectedConditions.textToBePresentInElementValue(useBy(), value));

            case VISIBLE:
                webElement = wait.until(ExpectedConditions.visibilityOfElementLocated(useBy()));
                break;

            default:
                throw new IllegalArgumentException("Unknown Wait Condition [" + waitType + "]");
            }

            if (currentContext != null && webDriver instanceof ContextAware)
                ((ContextAware) webDriver).context(currentContext);

            PageManager.instance().addExecutionLog(getExecutionId(), getDeviceName(), getPageName(),
                    getElementName(), "waitFor", System.currentTimeMillis(),
                    System.currentTimeMillis() - startTime,
                    webElement != null ? StepStatus.SUCCESS : StepStatus.FAILURE, getKey(), null, 0, "",
                    webElement instanceof CachedElement, new String[] { waitType.name().toLowerCase() });
            return webElement != null;
        } catch (Exception e) {
            log.error(Thread.currentThread().getName() + ": Could not locate " + useBy(), e);
            throw new ObjectIdentificationException(getBy(), useBy());
        }
    }
}