com.gargoylesoftware.htmlunit.html.HtmlElement Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CSSStyleSheet.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code true} if this stylesheet is active, based on the media types it is associated with (if any).
 * @return {@code true} if this stylesheet is active, based on the media types it is associated with (if any)
 */
public boolean isActive() {
    final String media;
    final HtmlElement e = ownerNode_.getDomNodeOrNull();
    if (e instanceof HtmlStyle) {
        final HtmlStyle style = (HtmlStyle) e;
        media = style.getMediaAttribute();
    }
    else if (e instanceof HtmlLink) {
        final HtmlLink link = (HtmlLink) e;
        media = link.getMediaAttribute();
    }
    else {
        return true;
    }

    if (StringUtils.isBlank(media)) {
        return true;
    }

    final WebClient webClient = getWindow().getWebWindow().getWebClient();
    final MediaListImpl mediaList = parseMedia(webClient.getCssErrorHandler(), media);
    return isActive(this, mediaList);
}
 
Example #2
Source File: HTMLFormElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private List<HtmlElement> findElements(final String name) {
    final List<HtmlElement> elements = new ArrayList<>();
    addElements(name, getHtmlForm().getHtmlElementDescendants(), elements);
    addElements(name, getHtmlForm().getLostChildren(), elements);

    // If no form fields are found, browsers are able to find img elements by ID or name.
    if (elements.isEmpty()) {
        for (final DomNode node : getHtmlForm().getHtmlElementDescendants()) {
            if (node instanceof HtmlImage) {
                final HtmlImage img = (HtmlImage) node;
                if (name.equals(img.getId()) || name.equals(img.getNameAttribute())) {
                    elements.add(img);
                }
            }
        }
    }

    return elements;
}
 
Example #3
Source File: XMLDOMDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public MSXMLScriptable makeScriptableFor(final DomNode domNode) {
    final MSXMLScriptable scriptable;

    if (domNode instanceof DomElement && !(domNode instanceof HtmlElement)) {
        scriptable = new XMLDOMElement();
    }
    else if (domNode instanceof DomAttr) {
        scriptable = new XMLDOMAttribute();
    }
    else {
        return (MSXMLScriptable) super.makeScriptableFor(domNode);
    }

    scriptable.setParentScope(this);
    scriptable.setPrototype(getPrototype(scriptable.getClass()));
    scriptable.setDomNode(domNode);

    return scriptable;
}
 
Example #4
Source File: ConversationIT.java    From krazo with Apache License 2.0 6 votes vote down vote up
@Test
public void testConversation() throws Exception {
    HtmlPage page;
    Iterator<HtmlElement> it;

    page = webClient.getPage(webUrl + "resources/converse/start");
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    final String secret = it.next().asText();
    System.out.println(secret);

    page = webClient.getPage(webUrl + "resources/converse/" +
        page.getDocumentElement().getElementsByTagName("a")
            .iterator().next().getAttribute("href"));
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    assertTrue(secret.equals(it.next().asText()));

    page = webClient.getPage(webUrl + "resources/converse/stop");
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    assertFalse(secret.equals(it.next().asText()));
}
 
Example #5
Source File: XMLDOMNodeList.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the ids of the collection's elements to the idList.
 * @param idList the list to add the ids to
 * @param elements the collection's elements
 */
protected void addElementIds(final List<String> idList, final List<DomNode> elements) {
    int index = 0;
    for (final DomNode next : elements) {
        final HtmlElement element = (HtmlElement) next;
        final String name = element.getAttributeDirect("name");
        if (name != DomElement.ATTRIBUTE_NOT_DEFINED) {
            idList.add(name);
        }
        else {
            final String id = element.getId();
            if (id != DomElement.ATTRIBUTE_NOT_DEFINED) {
                idList.add(id);
            }
            else {
                idList.add(Integer.toString(index));
            }
        }
        index++;
    }
}
 
Example #6
Source File: HTMLFormElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Overridden to allow the retrieval of certain form elements by ID or name.
 *
 * @param name {@inheritDoc}
 * @return {@inheritDoc}
 */
@Override
protected Object getWithPreemption(final String name) {
    if (getDomNodeOrNull() == null) {
        return NOT_FOUND;
    }
    final List<HtmlElement> elements = findElements(name);

    if (elements.isEmpty()) {
        return NOT_FOUND;
    }
    if (elements.size() == 1) {
        return getScriptableFor(elements.get(0));
    }
    final List<DomNode> nodes = new ArrayList<DomNode>(elements);
    final HTMLCollection collection = new HTMLCollection(getHtmlForm(), nodes) {
        @Override
        protected List<DomNode> computeElements() {
            return new ArrayList<DomNode>(findElements(name));
        }
    };
    return collection;
}
 
Example #7
Source File: XMLDOMNodeList.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the HTML elements from cache or retrieve them at first call.
 * @return the list of {@link HtmlElement} contained in this collection
 */
protected List<DomNode> getElements() {
    // a bit strange but we like to avoid sync
    List<DomNode> cachedElements = cachedElements_;

    if (cachedElements == null) {
        cachedElements = computeElements();
        cachedElements_ = cachedElements;
        if (!listenerRegistered_) {
            final DomHtmlAttributeChangeListenerImpl listener = new DomHtmlAttributeChangeListenerImpl(this);
            final DomNode domNode = getDomNodeOrNull();
            if (domNode != null) {
                domNode.addDomChangeListener(listener);
                if (attributeChangeSensitive_ && domNode instanceof HtmlElement) {
                    ((HtmlElement) domNode).addHtmlAttributeChangeListener(listener);
                }
            }
            listenerRegistered_ = true;
        }
    }

    // maybe the cache was cleared in between
    // then this returns the old state and never null
    return cachedElements;
}
 
Example #8
Source File: XMLDOMNodeList.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the ids of the collection's elements to the idList.
 * @param idList the list to add the ids to
 * @param elements the collection's elements
 */
protected void addElementIds(final List<String> idList, final List<DomNode> elements) {
    int index = 0;
    for (final DomNode next : elements) {
        final HtmlElement element = (HtmlElement) next;
        final String name = element.getAttributeDirect("name");
        if (name != DomElement.ATTRIBUTE_NOT_DEFINED) {
            idList.add(name);
        }
        else {
            final String id = element.getId();
            if (id != DomElement.ATTRIBUTE_NOT_DEFINED) {
                idList.add(id);
            }
            else {
                idList.add(Integer.toString(index));
            }
        }
        index++;
    }
}
 
Example #9
Source File: CSSStyleSheet.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code true} if this stylesheet is active, based on the media types it is associated with (if any).
 * @return {@code true} if this stylesheet is active, based on the media types it is associated with (if any)
 */
public boolean isActive() {
    final String media;
    final HtmlElement e = ownerNode_.getDomNodeOrNull();
    if (e instanceof HtmlStyle) {
        final HtmlStyle style = (HtmlStyle) e;
        media = style.getMediaAttribute();
    }
    else if (e instanceof HtmlLink) {
        final HtmlLink link = (HtmlLink) e;
        media = link.getMediaAttribute();
    }
    else {
        return true;
    }

    if (StringUtils.isBlank(media)) {
        return true;
    }

    final WebClient webClient = getWindow().getWebWindow().getWebClient();
    final MediaList mediaList = parseMedia(webClient.getCssErrorHandler(), media);
    return isActive(this, mediaList);
}
 
Example #10
Source File: WebClientTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test reuse of a single {@link HtmlPage} object to submit the same form multiple times.
 * @throws Exception if test fails
 */
@Test
public void reusingHtmlPageToSubmitFormMultipleTimes() throws Exception {
    final String firstContent = "<html><head><title>First</title></head>\n"
            + "<body onload='document.myform.mysubmit.focus()'>\n"
            + "<form action='" + URL_SECOND + "' name='myform'>\n"
            + "<input type='submit' name='mysubmit'>\n"
            + "</form></body></html>";
    final String secondContent = "<html><head><title>Second</title></head><body>Second</body></html>";

    final WebClient webClient = getWebClient();

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setDefaultResponse(secondContent);

    webClient.setWebConnection(webConnection);

    final HtmlPage page = webClient.getPage(URL_FIRST);
    for (int i = 0; i < 100; i++) {
        final HtmlElement button = page.getFormByName("myform").getInputByName("mysubmit");
        button.click();
    }
}
 
Example #11
Source File: ScriptPreProcessorTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that script preprocessing is applied to eval()'ed scripts (bug 2630555).
 * @throws Exception if the test fails
 */
@Test
public void scriptPreProcessor_Eval() throws Exception {
    final String html = "<html><body><script>eval('aX'+'ert(\"abc\")');</script></body></html>";

    final WebClient client = getWebClient();
    final MockWebConnection conn = new MockWebConnection();
    conn.setDefaultResponse(html);
    client.setWebConnection(conn);

    client.setScriptPreProcessor(new ScriptPreProcessor() {
        @Override
        public String preProcess(final HtmlPage p, final String src, final String srcName,
                final int lineNumber, final HtmlElement htmlElement) {
            return src.replaceAll("aXert", "alert");
        }
    });

    final List<String> alerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(alerts));
    client.getPage(URL_FIRST);

    assertEquals(1, alerts.size());
    assertEquals("abc", alerts.get(0));
}
 
Example #12
Source File: CsrfIT.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a form, removes CSRF hidden field and attempts to submit. Should
 * result in a 403 error.
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormFail() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getHtmlElementsByTagName("form").get(0);

    // Remove hidden input field to cause a CSRF validation failure
    HtmlElement input = form.getHtmlElementsByTagName("input").get(1);
    form.removeChild(input);

    // Submit form - should fail
    HtmlSubmitInput button = (HtmlSubmitInput) form.getHtmlElementsByTagName("input").get(0);
    try {
        button.click();
        fail("CSRF validation should have failed!");
    } catch (FailingHttpStatusCodeException e) {
        // falls through
    }
}
 
Example #13
Source File: PopupTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the opened window becomes the current one.
 * @throws Exception if the test fails
 */
@Test
@Alerts("Pop-up window is Open")
public void popupWindowBecomesCurrent() throws Exception {
    final String content = "<html><head><title>First</title><body>\n"
        + "<span id='button' onClick='openPopup()'>Push me</span>\n"
        + "<script>\n"
        + "  function openPopup() {\n "
        + "    window.open('', '_blank', 'width=640, height=600, scrollbars=yes');\n"
        + "    alert('Pop-up window is Open');\n "
        + "  }\n"
        + "</script>\n"
        + "</body></html>";

    final List<String> collectedAlerts = new ArrayList<>();
    final HtmlPage page = loadPage(content, collectedAlerts);
    final HtmlElement button = page.getHtmlElementById("button");

    final HtmlPage secondPage = button.click();
    final String[] expectedAlerts = {"Pop-up window is Open"};
    assertEquals(expectedAlerts, collectedAlerts);
    assertEquals("about:blank", secondPage.getUrl());
    assertSame(secondPage.getEnclosingWindow(), secondPage.getWebClient().getCurrentWindow());
}
 
Example #14
Source File: CaseResultTest.java    From junit-plugin with MIT License 6 votes vote down vote up
/**
    * Verifies that the error message and stacktrace from a failed junit test actually render properly.
    */
   @Issue("JENKINS-4257")
   @Test
   public void testFreestyleErrorMsgAndStacktraceRender() throws Exception {
       FreeStyleBuild b = configureTestBuild("render-test");
       TestResult tr = b.getAction(TestResultAction.class).getResult();
       assertEquals(3,tr.getFailedTests().size());
       CaseResult cr = tr.getFailedTests().get(1);
       assertEquals("org.twia.vendor.VendorManagerTest",cr.getClassName());
       assertEquals("testGetRevokedClaimsForAdjustingFirm",cr.getName());
assertNotNull("Error details should not be null", cr.getErrorDetails());
assertNotNull("Error stacktrace should not be null", cr.getErrorStackTrace());

String testUrl = cr.getRelativePathFrom(tr);

HtmlPage page = rule.createWebClient().goTo("job/render-test/1/testReport/" + testUrl);

HtmlElement errorMsg = (HtmlElement) page.getByXPath("//h3[text()='Error Message']/following-sibling::*").get(0);

assertEquals(cr.annotate(cr.getErrorDetails()).replaceAll("&lt;", "<"), errorMsg.getTextContent());
HtmlElement errorStackTrace = (HtmlElement) page.getByXPath("//h3[text()='Stacktrace']/following-sibling::*").get(0);
// Have to do some annoying replacing here to get the same text Jelly produces in the end.
assertEquals(cr.annotate(cr.getErrorStackTrace()).replaceAll("&lt;", "<").replace("\r\n", "\n"),
	     errorStackTrace.getTextContent());
   }
 
Example #15
Source File: HTMLParserTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the new HTMLParser on a simple HTML string.
 * @throws Exception failure
 */
@Test
public void simpleHTMLString() throws Exception {
    final WebClient webClient = getWebClient();
    final WebResponse webResponse = new StringWebResponse(
        "<html><head><title>TITLE</title></head><body><div>TEST</div></body></html>", URL_FIRST);

    final HtmlPage page = webClient.getPageCreator().getHtmlParser()
                                        .parseHtml(webResponse, webClient.getCurrentWindow());

    final String stringVal = page.<HtmlDivision>getFirstByXPath("//div").getFirstChild().getNodeValue();
    assertEquals("TEST", stringVal);

    final HtmlElement node = (HtmlElement) page.getFirstByXPath("//*[./text() = 'TEST']");
    assertEquals(node.getTagName(), HtmlDivision.TAG_NAME);
}
 
Example #16
Source File: XMLHttpRequest3Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for bug 1209686 (onreadystatechange not called with partial data when emulating FF).
 * @throws Exception if an error occurs
 */
@Test
@NotYetImplemented
public void streaming() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/test", StreamingServlet.class);

    final String resourceBase = "./src/test/resources/com/gargoylesoftware/htmlunit/javascript/host";
    startWebServer(resourceBase, null, servlets);
    final WebClient client = getWebClient();
    final HtmlPage page = client.getPage(URL_FIRST + "XMLHttpRequestTest_streaming.html");
    assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(1000));
    final HtmlElement body = page.getBody();
    assertEquals(10, body.asText().split("\n").length);
}
 
Example #17
Source File: WebClientTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test tabbing where there is only one tabbable element.
 * @throws Exception if something goes wrong
 */
@Test
public void keyboard_OneTabbableElement() throws Exception {
    final WebClient webClient = getWebClient();
    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final HtmlPage page = getPageForKeyboardTest(webClient, new String[]{null});
    final HtmlElement element = page.getHtmlElementById("submit0");

    final DomElement focus = page.getFocusedElement();
    assertTrue("original", (focus == null)
            || (focus == page.getDocumentElement())
            || (focus == page.getBody()));

    final DomElement accessKey = page.pressAccessKey('x');
    assertEquals("accesskey", focus, accessKey);

    assertEquals("next", element, page.tabToNextElement());
    assertEquals("nextAgain", element, page.tabToNextElement());

    page.getFocusedElement().blur();
    assertNull("original", page.getFocusedElement());

    assertEquals("previous", element, page.tabToPreviousElement());
    assertEquals("previousAgain", element, page.tabToPreviousElement());

    assertEquals("accesskey", element, page.pressAccessKey('z'));

    final String[] expectedAlerts = {"focus-0", "blur-0", "focus-0"};
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example #18
Source File: HTMLIFrameElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void removeFrameWindow() throws Exception {
    final String index = "<html><head></head><body>\n"
            + "<div id='content'>\n"
            + "  <iframe name='content' src='second/'></iframe>\n"
            + "</div>\n"
            + "<button id='clickId' "
            +     "onClick=\"document.getElementById('content').innerHTML = 'new content';\">Item</button>\n"
            + "</body></html>";

    final String frame1 = "<html><head></head><body>\n"
            + "<p>frame content</p>\n"
            + "</body></html>";

    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = getMockWebConnection();

    webConnection.setResponse(URL_SECOND, frame1);
    webClient.setWebConnection(webConnection);

    final HtmlPage page = loadPage(index);

    assertEquals("frame content", page.getElementById("content").asText());
    // check frame on page
    List<FrameWindow> frames = page.getFrames();
    assertEquals(1, frames.size());
    assertEquals("frame content", ((HtmlPage) page.getFrameByName("content").getEnclosedPage()).asText());

    // replace frame tag with javascript
    ((HtmlElement) page.getElementById("clickId")).click();

    assertEquals("new content", page.getElementById("content").asText());

    // frame has to be gone
    frames = page.getFrames();
    assertTrue(frames.isEmpty());
}
 
Example #19
Source File: CSSStyleSheet2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test for #1300.
 * @throws Exception if the test fails
 */
@Test
public void brokenExternalCSS() throws Exception {
    final String html = "<html><head>\n"
        + "<link rel='stylesheet' type='text/css' href='" + URL_SECOND + "'/></head></html>";

    getMockWebConnection().setResponse(URL_SECOND, "body { font-weight: 900\\9; }");
    final HtmlPage htmlPage = loadPage(html);

    final NodeList list = htmlPage.getElementsByTagName("body");
    final HtmlElement element = (HtmlElement) list.item(0);
    final ComputedCSSStyleDeclaration style = ((HTMLElement) element.getScriptableObject()).getCurrentStyle();
    assertEquals("CSSStyleDeclaration for ''", style.toString());
}
 
Example #20
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void requestAuthorizationCodeGrantWhenInvalidRedirectUriThenDisplayLoginPageWithError() throws Exception {
	HtmlPage page = this.webClient.getPage("/");
	URL loginPageUrl = page.getBaseURL();
	URL loginErrorPageUrl = new URL(loginPageUrl.toString() + "?error");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();

	WebResponse response = this.followLinkDisableRedirects(clientAnchorElement);

	UriComponents authorizeRequestUriComponents = UriComponentsBuilder.fromUri(
		URI.create(response.getResponseHeaderValue("Location"))).build();

	Map<String, String> params = authorizeRequestUriComponents.getQueryParams().toSingleValueMap();
	String code = "auth-code";
	String state = URLDecoder.decode(params.get(OAuth2ParameterNames.STATE), "UTF-8");
	String redirectUri = URLDecoder.decode(params.get(OAuth2ParameterNames.REDIRECT_URI), "UTF-8");
	redirectUri += "-invalid";

	String authorizationResponseUri =
		UriComponentsBuilder.fromHttpUrl(redirectUri)
			.queryParam(OAuth2ParameterNames.CODE, code)
			.queryParam(OAuth2ParameterNames.STATE, state)
			.build().encode().toUriString();

	page = this.webClient.getPage(new URL(authorizationResponseUri));
	assertThat(page.getBaseURL()).isEqualTo(loginErrorPageUrl);

	HtmlElement errorElement = page.getBody().getFirstByXPath("p");
	assertThat(errorElement).isNotNull();
	assertThat(errorElement.asText()).contains("invalid_redirect_uri_parameter");
}
 
Example #21
Source File: ScriptPreProcessorTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test the ScriptPreProcessor's ability to filter out a JavaScript method
 * that is not implemented without affecting the rest of the page.
 *
 * @throws Exception if the test fails
 */
@Test
public void scriptPreProcessor_UnimplementedJavascript() throws Exception {
    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    final String content = "<html><head><title>foo</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "<script>document.unimplementedFunction();</script>\n"
        + "<script>alert('implemented function');</script>\n"
        + "</body></html>";

    webConnection.setDefaultResponse(content);
    client.setWebConnection(webConnection);

    client.setScriptPreProcessor(new ScriptPreProcessor() {
        @Override
        public String preProcess(final HtmlPage htmlPage, final String sourceCode, final String sourceName,
                final int lineNumber, final HtmlElement htmlElement) {
            if (sourceCode.indexOf("unimplementedFunction") > -1) {
                return "";
            }
            return sourceCode;
        }
    });
    final List<String> alerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(alerts));
    client.getPage("http://page");

    assertEquals(1, alerts.size());
    assertEquals("implemented function", alerts.get(0).toString());
}
 
Example #22
Source File: ViewAnnotationIT.java    From ozark with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringClass() throws Exception {
    final HtmlPage page = webClient.getPage(webUrl + "resources/class/string");
    assertThat(page.getWebResponse().getStatusCode(), is(200));
    final Iterator<HtmlElement> it = page.getDocumentElement().getHtmlElementsByTagName("h1").iterator();
    assertTrue(it.next().asText().contains("Bye World"));
}
 
Example #23
Source File: BookModelsIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testView1() throws Exception {
    final HtmlPage page = webClient.getPage(webUrl + "resources/book/view1/1");
    final Iterator<HtmlElement> it = page.getDocumentElement().getElementsByTagName("p").iterator();
    assertTrue(it.next().asText().contains("Some title"));
    assertTrue(it.next().asText().contains("Some author"));
    assertTrue(it.next().asText().contains("Some ISBN"));
}
 
Example #24
Source File: HTMLElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the attributes of the element in the form of a {@link org.xml.sax.Attributes}.
 * @param element the element to read the attributes from
 * @return the attributes
 */
protected AttributesImpl readAttributes(final HtmlElement element) {
    final AttributesImpl attributes = new AttributesImpl();
    for (final DomAttr entry : element.getAttributesMap().values()) {
        final String name = entry.getName();
        final String value = entry.getValue();
        attributes.addAttribute(null, name, name, null, value);
    }

    return attributes;
}
 
Example #25
Source File: HTMLUnknownElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the JavaScript property {@code nodeName} for the current node.
 * @return the node name
 */
@Override
public String getNodeName() {
    final HtmlElement elem = getDomNodeOrDie();
    final Page page = elem.getPage();
    if (page instanceof XmlPage) {
        return elem.getLocalName();
    }
    return super.getNodeName();
}
 
Example #26
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void requestAuthorizationCodeGrantWhenNoMatchingAuthorizationRequestThenDisplayLoginPageWithError() throws Exception {
	HtmlPage page = this.webClient.getPage("/");
	URL loginPageUrl = page.getBaseURL();
	URL loginErrorPageUrl = new URL(loginPageUrl.toString() + "?error");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	String code = "auth-code";
	String state = "state";
	String redirectUri = AUTHORIZE_BASE_URL + "/" + clientRegistration.getRegistrationId();

	String authorizationResponseUri =
		UriComponentsBuilder.fromHttpUrl(redirectUri)
			.queryParam(OAuth2ParameterNames.CODE, code)
			.queryParam(OAuth2ParameterNames.STATE, state)
			.build().encode().toUriString();

	// Clear session cookie will ensure the 'session-saved'
	// Authorization Request (from previous request) is not found
	this.webClient.getCookieManager().clearCookies();

	page = this.webClient.getPage(new URL(authorizationResponseUri));
	assertThat(page.getBaseURL()).isEqualTo(loginErrorPageUrl);

	HtmlElement errorElement = page.getBody().getFirstByXPath("p");
	assertThat(errorElement).isNotNull();
	assertThat(errorElement.asText()).contains("authorization_request_not_found");
}
 
Example #27
Source File: WebAssert.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Many HTML components can have an <tt>accesskey</tt> attribute which defines a hot key for
 * keyboard navigation. This method verifies that all the <tt>accesskey</tt> attributes on the
 * specified page are unique.
 *
 * @param page the page to check
 */
public static void assertAllAccessKeyAttributesUnique(final HtmlPage page) {
    final List<String> list = new ArrayList<>();
    for (final HtmlElement element : page.getHtmlElementDescendants()) {
        final String key = element.getAttributeDirect("accesskey");
        if (key != null && !key.isEmpty()) {
            if (list.contains(key)) {
                throw new AssertionError("The access key '" + key + "' is not unique.");
            }
            list.add(key);
        }
    }
}
 
Example #28
Source File: HTMLTableElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the table's caption element, or {@code null} if none exists. If more than one
 * caption is declared in the table, this method returns the first one.
 * @return the table's caption element
 */
@JsxGetter
public Object getCaption() {
    final List<HtmlElement> captions = getDomNodeOrDie().getElementsByTagName("caption");
    if (captions.isEmpty()) {
        return null;
    }
    return getScriptableFor(captions.get(0));
}
 
Example #29
Source File: WebAssert.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Many HTML elements are "tabbable" and can have a <tt>tabindex</tt> attribute
 * that determines the order in which the components are navigated when
 * pressing the tab key. To ensure good usability for keyboard navigation,
 * all tabbable elements should have the <tt>tabindex</tt> attribute set.</p>
 *
 * <p>This method verifies that all tabbable elements have a valid value set for
 * the <tt>tabindex</tt> attribute.</p>
 *
 * @param page the page to check
 */
public static void assertAllTabIndexAttributesSet(final HtmlPage page) {
    final List<String> tags =
        Arrays.asList(new String[] {"a", "area", "button", "input", "object", "select", "textarea"});

    for (final String tag : tags) {
        for (final HtmlElement element : page.getDocumentElement().getElementsByTagName(tag)) {
            final Short tabIndex = element.getTabIndex();
            if (tabIndex == null || tabIndex == HtmlElement.TAB_INDEX_OUT_OF_BOUNDS) {
                final String s = element.getAttributeDirect("tabindex");
                throw new AssertionError("Illegal value for tab index: '" + s + "'.");
            }
        }
    }
}
 
Example #30
Source File: ApplicationPathIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testView1() throws Exception {
    final HtmlPage page = webClient.getPage(webUrl + "book/view1/1");
    final Iterator<HtmlElement> it = page.getDocumentElement().getElementsByTagName("p").iterator();
    assertTrue(it.next().asText().contains("Some title"));
    assertTrue(it.next().asText().contains("Some author"));
    assertTrue(it.next().asText().contains("Some ISBN"));
}