Example usage for org.openqa.selenium WebElement getAttribute

List of usage examples for org.openqa.selenium WebElement getAttribute

Introduction

In this page you can find the example usage for org.openqa.selenium WebElement getAttribute.

Prototype

String getAttribute(String name);

Source Link

Document

Get the value of the given attribute of the element.

Usage

From source file:com.liferay.faces.bridge.test.integration.issue.FACES_1635ResourcesTester.java

License:Open Source License

@Test
public void runFACES_1635ResourcesTest() {

    String container = TestUtil.getContainer();
    Assume.assumeTrue("The FACES-1635 test is only valid on Liferay Portal and Pluto 3.0+.",
            container.startsWith("liferay") || BridgeTestUtil.isContainerPluto(3, container));

    BrowserDriver browserDriver = getBrowserDriver();
    browserDriver.navigateWindowTo(BridgeTestUtil.getIssuePageURL("faces-1635") + "?p_p_parallel=0");
    browserDriver.waitForElementDisplayed(
            "//div[contains(@id,'jsf')][contains(@id,'applicant')][contains(@class,'liferay-faces-bridge-body')]//img[contains(@src, 'liferay-logo.png')]");
    browserDriver.waitForElementDisplayed(
            "//div[contains(@id,'prime')][contains(@id,'applicant')][contains(@class,'liferay-faces-bridge-body')]//img[contains(@src, 'liferay-logo.png')]");

    // Test that the head does not contain duplicate scripts.
    Set<String> resourceIds = new HashSet<String>();
    List<WebElement> headScripts = browserDriver.findElementsByXpath("//head//script");

    for (WebElement headScript : headScripts) {

        String scriptSrc = headScript.getAttribute("src");

        if (isExternalJavaScriptResource(headScript, scriptSrc)) {

            String resourceId = getResourceId(scriptSrc, container);

            if (resourceId != null) {
                Assert.assertTrue("Head contains duplicate script with resourceId=\"" + resourceId
                        + "\" and src=\"" + scriptSrc + "\".", resourceIds.add(resourceId));
            }//from w  w  w.ja va  2  s  .c om
        }
    }

    // Test that the head does not contain duplicate stylesheets.
    List<WebElement> headLinks = browserDriver.findElementsByXpath("//head//link");

    for (WebElement headLink : headLinks) {

        String linkHref = headLink.getAttribute("href");

        if (isCSSLink(headLink, linkHref)) {

            String resourceId = getResourceId(linkHref, container);

            if (resourceId != null) {
                Assert.assertTrue("Head contains duplicate stylesheet with resourceId=\"" + resourceId
                        + "\" and href=\"" + linkHref + "\".", resourceIds.add(resourceId));
            }
        }
    }

    Assert.assertTrue("No head resources found.", !resourceIds.isEmpty());

    // Test that the entire document does not contain duplicate scripts.
    List<WebElement> bodyScripts = browserDriver.findElementsByXpath("//body//script");

    for (WebElement bodyScript : bodyScripts) {
        String scriptSrc = bodyScript.getAttribute("src");

        if (isExternalJavaScriptResource(bodyScript, scriptSrc)) {

            String resourceId = getResourceId(scriptSrc, container);

            if (resourceId != null) {
                Assert.assertTrue("Body contains duplicate script with resourceId=\"" + resourceId
                        + "\" and src=\"" + scriptSrc + "\".", resourceIds.add(resourceId));
            }
        }
    }

    // Test that the entire document does not contain duplicate stylesheets.
    List<WebElement> bodyLinks = browserDriver.findElementsByXpath("//body//link");

    for (WebElement bodyLink : bodyLinks) {

        String linkHref = bodyLink.getAttribute("href");

        if (isCSSLink(bodyLink, linkHref)) {

            String resourceId = getResourceId(linkHref, container);

            if (resourceId != null) {
                Assert.assertTrue("Body contains duplicate stylesheet with resourceId=\"" + resourceId
                        + "\" and href=\"" + linkHref + "\".", resourceIds.add(resourceId));
            }
        }
    }

    Assert.assertTrue("No resources found.", !resourceIds.isEmpty());
}

From source file:com.liferay.faces.bridge.test.integration.issue.FACES_1635ResourcesTester.java

License:Open Source License

private boolean isCSSLink(WebElement webElement, String linkHref) {

    String linkRel = webElement.getAttribute("rel");

    return ((linkHref != null) && !linkHref.equals("")) && "stylesheet".equals(linkRel);
}

From source file:com.liferay.faces.bridge.test.integration.issue.FACES_1635ResourcesTester.java

License:Open Source License

private boolean isExternalJavaScriptResource(WebElement webElement, String scriptSrc) {

    String scriptType = webElement.getAttribute("type");

    return ((scriptSrc != null) && !scriptSrc.equals(""))
            && ((scriptType == null) || scriptType.equals("text/javascript"));
}

From source file:com.liferay.faces.bridge.test.integration.issue.FACES_1638PortletTester.java

License:Open Source License

@Test
public void runFACES_1638PortletTest() {

    String container = TestUtil.getContainer();
    Assume.assumeTrue("The FACES-1635 test is only valid on Liferay Portal.", container.startsWith("liferay"));

    BrowserDriver browserDriver = getBrowserDriver();
    browserDriver.navigateWindowTo(BridgeTestUtil.getIssuePageURL("faces-1638"));

    List<WebElement> listItems = browserDriver
            .findElementsByXpath("//div[contains(@class,'liferay-faces-bridge-body')]//ul/li");
    int expectedNumberOfListItems = 6;
    Assert.assertEquals("There are not " + expectedNumberOfListItems + " links on the page.",
            expectedNumberOfListItems, listItems.size());

    // Test that each link contains only one *-Item param which has the correct value.
    for (WebElement listItem : listItems) {

        WebElement paramNameSpan = listItem.findElement(By.xpath(".//span[@class='param-name']"));
        String paramName = paramNameSpan.getText();

        WebElement paramValueSpan = listItem.findElement(By.xpath(".//span[@class='param-value']"));
        String paramValue = paramValueSpan.getText();

        String param = paramName + "=" + paramValue;

        WebElement link = listItem.findElement(By.xpath(".//a[contains(text(),'-Item')][@href]"));
        String url = link.getAttribute("href");

        logger.info("URL:\n\n{}", url);
        Assert.assertTrue("The link does not contain the parameter.", url.contains(param));

        int expectedOccurencesOfParamName = 1;
        Assert.assertEquals("The link contains more than than " + expectedOccurencesOfParamName + " \""
                + paramName + "\" parameter.", expectedOccurencesOfParamName, occurencesOf(paramName, url));
    }//from   w  w w  . ja  v a2 s.  com
}

From source file:com.liferay.faces.bridge.test.integration.issue.FACES_3300PortletTester.java

License:Open Source License

private static List<String> getURLsFromLinks(BrowserDriver browserDriver, String linksXpath, String container) {

    List<WebElement> linkElements = browserDriver.findElementsByXpath(linksXpath);
    List<String> urls = new ArrayList<String>();

    for (WebElement linkElement : linkElements) {

        String link = linkElement.getAttribute("href");

        if ((container != null) && container.startsWith("liferay")) {
            link = link.replace("p_p_state=normal", "p_p_state=exclusive");
        }//from   w  w  w  .  j  a v  a2s  .c  o m

        urls.add(link);
    }

    Assert.assertTrue(!urls.isEmpty());

    return Collections.unmodifiableList(urls);
}

From source file:com.liferay.faces.bridge.test.integration.issue.primefaces.ExporterComponentsTestUtil.java

License:Open Source License

static void runDownloadUsersCSVFileTest(BrowserDriver browserDriver, String buttonId)
        throws IOException {

    // TECHNICAL NOTE: Since browsers handle file downloads differently, download files with a plain
    // HttpURLConnection in order to avoid handling each browser case.
    String buttonXpath = "//form/button[contains(@id,':" + buttonId + "')]";
    browserDriver.waitForElementEnabled(buttonXpath);

    String formXpath = buttonXpath + "/..";
    WebElement formElement = browserDriver.findElementByXpath(formXpath);
    String formActionURLString = formElement.getAttribute("action");
    URL formActionURL = new URL(formActionURLString);
    HttpURLConnection httpURLConnection = (HttpURLConnection) formActionURL.openConnection();
    InputStream inputStream = null;

    try {/*  ww w.  j av  a  2s . co  m*/

        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.addRequestProperty("Accept", "text/csv");

        // TECHNICAL NOTE: Add all cookies from the browser to the HttpURLConnection so that it can imitate the
        // session of the browser and access the test portlet and files.
        Set<Cookie> cookies = browserDriver.getBrowserCookies();
        String cookieString = "";

        for (Cookie cookie : cookies) {
            cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
        }

        httpURLConnection.addRequestProperty("Cookie", cookieString);

        // TECHNICAL NOTE: Add all input (and button) name, value pairs to the POST parameters of the
        // HttpURLConnection so that it can imitate the session of the browser and download the files.
        List<WebElement> namedElements = new ArrayList<WebElement>(
                browserDriver.findElementsByXpath(formXpath + "/input"));
        WebElement button = browserDriver.findElementByXpath(buttonXpath);
        namedElements.add(button);

        StringBuilder requestBuilder = new StringBuilder();
        boolean first = true;

        for (WebElement namedElement : namedElements) {

            if (!first) {
                requestBuilder.append("&");
            }

            String name = namedElement.getAttribute("name");
            requestBuilder.append(URLEncoder.encode(name, "UTF-8")).append("=");

            String value = namedElement.getAttribute("value");

            if (value != null) {
                requestBuilder.append(URLEncoder.encode(value, "UTF-8"));
            }

            first = false;
        }

        String requestString = requestBuilder.toString();
        httpURLConnection.addRequestProperty("Content-Length", String.valueOf(requestString.length()));

        String enctype = formElement.getAttribute("enctype");
        httpURLConnection.addRequestProperty("Content-Type", enctype);

        Writer writer = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");
        writer.write(requestString);
        writer.flush();

        Assert.assertEquals(HttpURLConnection.HTTP_OK, httpURLConnection.getResponseCode());

        String contentDisposition = httpURLConnection.getHeaderField("Content-Disposition");

        if (contentDisposition == null) {
            contentDisposition = httpURLConnection.getHeaderField("Content-disposition");
        }

        if (contentDisposition == null) {
            contentDisposition = httpURLConnection.getHeaderField("content-disposition");
        }

        String usersCSVFileName;

        if ((contentDisposition == null) && TestUtil.getContainer().startsWith("pluto")) {
            usersCSVFileName = buttonId + "Users.csv";
        } else {
            usersCSVFileName = contentDisposition.replace("attachment;filename=", "");
        }

        inputStream = httpURLConnection.getInputStream();

        String downloadedUsersCSV = getContents(inputStream);
        httpURLConnection.disconnect();

        logger.info("Expected " + EXPECTED_USERS_CSV_FILE_NAME + " text:\n\n{}\nDownloaded " + usersCSVFileName
                + " text:\n\n{}", EXPECTED_USERS_CSV, downloadedUsersCSV);
        Assert.assertEquals(
                "The downloaded " + usersCSVFileName + " file's text does not match the expected "
                        + EXPECTED_USERS_CSV_FILE_NAME + " file's text.",
                EXPECTED_USERS_CSV, downloadedUsersCSV);
    } finally {

        ClosableUtil.close(inputStream);

        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
}

From source file:com.liferay.faces.portal.test.showcase.inputrichtext.InputRichTextTester.java

License:Open Source License

protected final void submitRichText(BrowserDriver browserDriver, String elementToClickXpath,
        int ckeditorExampleNumber, String expectedText) {

    browserDriver.getWebDriver().switchTo().parentFrame();

    //J-//w  w w .ja v  a2  s.c  om
    browserDriver.executeScriptInCurrentWindow("for (var ckeditorKey in CKEDITOR.instances) {"
            + "CKEDITOR.instances[ckeditorKey].updateElement();" + "}");
    //J+

    try {

        browserDriver.setWaitTimeOut(1);

        WebElement textarea = browserDriver.findElementByXpath(
                "(//textarea[contains(@id,':comments_input')])[" + ckeditorExampleNumber + "]");

        //J-
        browserDriver.waitFor(
                ExpectedConditions.jsReturnsValue("if (document.getElementById('" + textarea.getAttribute("id")
                        + "').value" + "=== '" + expectedText + "') {" + "return true;" + "}"));
        //J+
    } catch (TimeoutException e) {
        // Do nothing.
    }

    browserDriver.setWaitTimeOut(TestUtil.getBrowserDriverWaitTimeOut());
    browserDriver.clickElement(elementToClickXpath);
}

From source file:com.liferay.faces.test.FACES1635ResourcesTest.java

License:Open Source License

public ArrayList<HeadResource> convertToHeadResources(List<WebElement> webElements, String attribute) {
    ArrayList<HeadResource> resources = new ArrayList<HeadResource>();

    for (WebElement webElement : webElements) {
        String url = webElement.getAttribute(attribute);
        String type = ("src".equals(attribute)) ? "script" : "link";

        if (url != null) {

            if ("".equals(url)) {
                // logger.log(Level.INFO, "convertToHeadResources: ignoring inline " + type + " ...");
            } else {

                if ("link".equals(type)) {
                    String rel = webElement.getAttribute("rel");

                    if (rel == null) {
                        logger.log(Level.INFO, "rel == null, type = " + type);
                    } else {

                        if ("stylesheet".equals(rel)) {
                            //                              logger.log(Level.INFO, "convertToHeadResources: url = " + url);
                            resources.add(new HeadResource(type, url));
                        }/*from  w  w  w  . ja  v  a  2s.c  o m*/
                    }
                } else { // SCRIPT.equals(type)

                    if (url.contains("jsf.js")) {
                        logger.log(Level.INFO, "convertToHeadResources: type = " + type + " url = " + url);
                    }

                    resources.add(new HeadResource(type, url));
                }
            }
        }
    }

    return resources;
}

From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java

License:Open Source License

@Override
public void clearElement(String elementXpath) {

    centerElementInCurrentWindow(elementXpath);

    WebElement element = findElementByXpath(elementXpath);
    String value = element.getAttribute("value");

    if ((value != null) && !value.equals("")) {

        CharSequence[] clearKeys = new CharSequence[value.length()];

        for (int i = 0; i < value.length(); i++) {
            clearKeys[i] = Keys.BACK_SPACE;
        }//www .  j  a v a 2 s .c  om

        sendKeysToElement(elementXpath, Keys.END);
        sendKeysToElement(elementXpath, clearKeys);
    }
}

From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java

License:Open Source License

@Override
public String getCurrentDocumentMarkup() {

    WebElement documentElement = findElementByXpath("/html");
    String outerHTMLAttrName = "outerHTML";
    String browserName = getBrowserName();

    // https://github.com/SeleniumHQ/htmlunit-driver/issues/45
    if ("htmlunit".equals(browserName)) {
        outerHTMLAttrName = "innerHTML";
    }//from w  ww.  j a  v  a  2 s.  c  om

    return documentElement.getAttribute(outerHTMLAttrName);
}