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.lazerycode.ebselen.customhandlers.FileDownloader.java

License:Apache License

public String downloader(WebElement element, String attribute) throws Exception {
    //Assuming that getAttribute does some magic to return a fully qualified URL
    String downloadLocation = element.getAttribute(attribute);
    if (downloadLocation.trim().equals("")) {
        throw new Exception("The element you have specified does not link to anything!");
    }//w  w w. java2s.com
    URL downloadURL = new URL(downloadLocation);
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
    client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort()));
    client.setState(mimicCookieState(driver.manage().getCookies()));
    HttpMethod getRequest = new GetMethod(downloadURL.getPath());
    FileHandler downloadedFile = new FileHandler(
            downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""), true);
    try {
        int status = client.executeMethod(getRequest);
        LOGGER.info("HTTP Status {} when getting '{}'", status, downloadURL.toExternalForm());
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            downloadedFile.getWritableFileOutputStream().write(block, 0, bytes);
        }
        downloadedFile.close();
        in.close();
        LOGGER.info("File downloaded to '{}'", downloadedFile.getAbsoluteFile());
    } catch (Exception Ex) {
        LOGGER.error("Download failed: {}", Ex);
        throw new Exception("Download failed!");
    } finally {
        getRequest.releaseConnection();
    }
    return downloadedFile.getAbsoluteFile();
}

From source file:com.lazerycode.selenium.filedownloader.FileDownloader.java

License:Apache License

/**
 * Perform the file/image download.//ww w.  jav  a  2  s.com
 *
 * @param element
 * @param attribute
 * @return
 * @throws IOException
 * @throws NullPointerException
 */
private String downloader(WebElement element, String attribute, String Filename)
        throws IOException, NullPointerException, URISyntaxException {
    String fileToDownloadLocation = element.getAttribute(attribute);
    if (fileToDownloadLocation.trim().equals(""))
        throw new NullPointerException("The element you have specified does not link to anything!");

    URL fileToDownload = new URL(fileToDownloadLocation);
    //changed by Raul
    File downloadedFile = new File(Filename);
    //+ " fileToDownload.getFile().replaceFirst("/|\\\\", "").replace("?", ""));

    if (downloadedFile.canWrite() == false)
        downloadedFile.setWritable(true);

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    //LOG.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
    if (this.mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE,
                mimicCookieState(this.driver.manage().getCookies()));
    }

    HttpGet httpget = new HttpGet(fileToDownload.toURI());
    HttpParams httpRequestParameters = httpget.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
    httpget.setParams(httpRequestParameters);

    // LOG.info("Sending GET request for: " + httpget.getURI());
    HttpResponse response = client.execute(httpget, localContext);
    this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
    //LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
    //LOG.info("Downloading file: " + downloadedFile.getName());
    FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
    response.getEntity().getContent().close();

    String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
    // LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'");

    return downloadedFileAbsolutePath;
}

From source file:com.liferay.blade.samples.configuration.action.test.BladeConfigurationActionTest.java

License:Apache License

@Test
public void testBladeConfigurationAction() throws InterruptedException, PortalException {

    _webDriver.get(_portletURL.toExternalForm());

    String url = _webDriver.getCurrentUrl();

    Assert.assertTrue("Portlet was not deployed",
            BladeSampleFunctionalActionUtil.isVisible(_webDriver, _bladeMessagePortlet));

    _bodyWebElement.click();//from www . j  av a  2s. c  om

    BladeSampleFunctionalActionUtil.customClick(_webDriver, _verticalEllipsis);

    WebElement configuration = _webDriver.findElement(By.linkText("Configuration"));

    String configurationLink = configuration.getAttribute("href");

    _newWebDriverWindow.get(configurationLink);

    BladeSampleFunctionalActionUtil.customClick(_newWebDriverWindow, _saveButton);

    Assert.assertTrue("Success Message is not visible",
            BladeSampleFunctionalActionUtil.isVisible(_webDriver, _successMessage));

    _webDriver.get(url);

    Assert.assertTrue("Expected Blade Message Portlet, but saw: " + _portletTitle.getText(),
            _portletTitle.getText().contentEquals("Blade Message Portlet"));

    Assert.assertTrue("Expected Hello from BLADE JSP!, but saw: " + _portletBody.getText(),
            _portletBody.getText().contentEquals("Hello from BLADE JSP!"));
}

From source file:com.liferay.cucumber.selenium.BaseWebDriverImpl.java

License:Open Source License

public String getElementValue(String locator, String timeout) throws Exception {

    WebElement webElement = getWebElement(locator, timeout);

    if (webElement == null) {
        throw new Exception("Element is not present at \"" + locator + "\"");
    }//ww  w  .  j  a v a 2  s . co m

    scrollWebElementIntoView(webElement);

    return webElement.getAttribute("value");
}

From source file:com.liferay.cucumber.selenium.WebDriverHelper.java

License:Open Source License

public static String getAttribute(WebDriver webDriver, String attributeLocator) {

    int pos = attributeLocator.lastIndexOf(CharPool.AT);

    String locator = attributeLocator.substring(0, pos);

    WebElement webElement = getWebElement(webDriver, locator);

    String attribute = attributeLocator.substring(pos + 1);

    return webElement.getAttribute(attribute);
}

From source file:com.liferay.cucumber.selenium.WebDriverHelper.java

License:Open Source License

public static void select(WebDriver webDriver, String selectLocator, String optionLocator) {

    WebElement webElement = getWebElement(webDriver, selectLocator);

    Select select = new Select(webElement);

    String label = optionLocator;

    if (optionLocator.startsWith("index=")) {
        String indexString = optionLocator.substring(6);

        int index = GetterUtil.getInteger(indexString);

        select.selectByIndex(index - 1);
    } else if (optionLocator.startsWith("value=")) {
        String value = optionLocator.substring(6);

        if (value.startsWith("regexp:")) {
            String regexp = value.substring(7);

            selectByRegexpValue(webDriver, selectLocator, regexp);
        } else {//  w w  w.j a v  a  2 s .co  m
            List<WebElement> optionWebElements = select.getOptions();

            for (WebElement optionWebElement : optionWebElements) {
                String optionWebElementValue = optionWebElement.getAttribute("value");

                if (optionWebElementValue.equals(value)) {
                    label = optionWebElementValue;

                    break;
                }
            }

            select.selectByValue(label);
        }
    } else {
        if (optionLocator.startsWith("label=")) {
            label = optionLocator.substring(6);
        }

        if (label.startsWith("regexp:")) {
            String regexp = label.substring(7);

            selectByRegexpText(webDriver, selectLocator, regexp);
        } else {
            select.selectByVisibleText(label);
        }
    }
}

From source file:com.liferay.cucumber.selenium.WebDriverHelper.java

License:Open Source License

protected static void selectByRegexpValue(WebDriver webDriver, String selectLocator, String regexp) {

    WebElement webElement = getWebElement(webDriver, selectLocator);

    Select select = new Select(webElement);

    List<WebElement> optionWebElements = select.getOptions();

    Pattern pattern = Pattern.compile(regexp);

    int index = -1;

    for (WebElement optionWebElement : optionWebElements) {
        String optionWebElementValue = optionWebElement.getAttribute("value");

        Matcher matcher = pattern.matcher(optionWebElementValue);

        if (matcher.matches()) {
            index = optionWebElements.indexOf(optionWebElement);

            break;
        }//from ww  w  .ja va 2  s. co  m
    }

    select.selectByIndex(index);
}

From source file:com.liferay.faces.bridge.test.integration.demo.JSFExportPDFPortletTester.java

License:Open Source License

@Test
public void runJSFExportPDFPortletTest() throws IOException {

    // Test that the view contains links to all three pdfs.
    BrowserDriver browserDriver = getBrowserDriver();
    browserDriver.navigateWindowTo(BridgeTestUtil.getDemoPageURL("jsf-pdf"));

    WaitingAsserter waitingAsserter = getWaitingAsserter();
    waitingAsserter.assertElementDisplayed(
            "//td[contains(text(),'Green')]/preceding-sibling::td/a[contains(text(),'Export')]");
    waitingAsserter.assertElementDisplayed(
            "//td[contains(text(),'Kessler')]/preceding-sibling::td/a[contains(text(),'Export')]");

    String shearerPDFLinkXpath = "//td[contains(text(),'Shearer')]/preceding-sibling::td/a[contains(text(),'Export')]";

    waitingAsserter.assertElementDisplayed(shearerPDFLinkXpath);

    // Test that the "Rich Shearer" link generates a PDF with the correct test. Note: since different browsers
    // and WebDriver implementations handle downloading files differently, download the file using a Java URL
    // connection.
    WebElement shearerPDFLinkElement = browserDriver.findElementByXpath(shearerPDFLinkXpath);
    String shearerPDFLink = shearerPDFLinkElement.getAttribute("href");
    URL shearerPDFURL = new URL(shearerPDFLink);
    HttpURLConnection httpURLConnection = (HttpURLConnection) shearerPDFURL.openConnection();
    httpURLConnection.setRequestMethod("GET");

    Set<Cookie> cookies = browserDriver.getBrowserCookies();
    String cookieString = "";

    for (Cookie cookie : cookies) {
        cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
    }/*from  w w  w. ja  v  a  2s  . c om*/

    httpURLConnection.addRequestProperty("Cookie", cookieString);

    InputStream inputStream = httpURLConnection.getInputStream();

    // Compare the text of the PDFs rather than the files (via a hash such as md5) becuase the portlet generates
    // slightly different PDFs each time the link is clicked (CreationDate, ModDate, and Info 7 0 R/ID are
    // different each time).
    String shearerRichPDFText = getPDFText(inputStream);
    inputStream = JSFExportPDFPortletTester.class.getResourceAsStream("/Shearer-Rich.pdf");

    String expectedShearerRichPDFText = getPDFText(inputStream);
    logger.info("Expected Shearer-Rich.pdf text:\n\n{}\nDownloaded Shearer-Rich.pdf text:\n\n{}",
            expectedShearerRichPDFText, shearerRichPDFText);
    Assert.assertEquals(
            "The downloaded Shearer-Rich.pdf file's text does not match the expected Shearer-Rich.pdf file's text.",
            expectedShearerRichPDFText, shearerRichPDFText);
}

From source file:com.liferay.faces.bridge.test.integration.demo.JSFFlowsPortletTester.java

License:Open Source License

private void selectOptionContainingText(BrowserDriver browserDriver, String selectXpath, String text) {

    WebElement option = browserDriver
            .findElementByXpath(selectXpath + "/option[contains(text(),'" + text + "')]");
    String value = option.getAttribute("value");
    createSelect(browserDriver, selectXpath).selectByValue(value);
}

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

License:Open Source License

@Test
public void runFACES_1478PortletTest() {

    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-1478"));
    browserDriver.waitForElementEnabled("//a[contains(text(),'FACES-1478')]");

    // Test that the displayed url is the same as the link's href url.
    WebElement urlSpan = browserDriver.findElementByXpath("//span[contains(@id,':url')]");
    String url = urlSpan.getText();
    WebElement link = browserDriver
            .findElementByXpath("//a[contains(text(),'should be the same as the href')]");
    String href = link.getAttribute("href");
    logger.info("URL:\n\n{}\nLink href value:\n\n{}", url, href);
    Assert.assertEquals("The URL value does not equal the value of the link's href attribute", url, href);

    // Test that the url contains both parameters.
    WebElement parameter1Span = browserDriver.findElementByXpath("//span[contains(@id,':parameter1')]");
    String parameter1 = parameter1Span.getText();
    Assert.assertTrue("The URL does not contain the first parameter: " + parameter1, url.contains(parameter1));

    WebElement parameter2Span = browserDriver.findElementByXpath("//span[contains(@id,':parameter2')]");
    String parameter2 = parameter2Span.getText();
    Assert.assertTrue("The URL does not contain the second parameter: " + parameter2, url.contains(parameter2));
}