com.gargoylesoftware.htmlunit.html.DomElement Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.html.DomElement. 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: HTMLAnchorElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of this link's {@code href} property.
 * @return the value of this link's {@code href} property
 */
@JsxGetter
public String getHref() {
    final HtmlAnchor anchor = (HtmlAnchor) getDomNodeOrDie();
    final String hrefAttr = anchor.getHrefAttribute();

    if (hrefAttr == DomElement.ATTRIBUTE_NOT_DEFINED) {
        return "";
    }

    try {
        return getUrl().toString();
    }
    catch (final MalformedURLException e) {
        return hrefAttr;
    }
}
 
Example #2
Source File: WebClient8Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if something goes wrong
 */
@Test
public void appendChildMoved() throws Exception {
    final String html = "<html>\n"
            + "<head><title>foo</title></head>\n"
            + "<body>\n"
            + "<p>hello</p>\n"
            + "</body></html>";

    final String html2 = "<html>\n"
            + "<head><title>foo</title></head>\n"
            + "<body>\n"
            + "<p id='tester'>world</p>\n"
            + "</body></html>";

    try (WebClient webClient = new WebClient(getBrowserVersion(), false, null, -1)) {
        final HtmlPage page = loadPage(webClient, html, null, URL_FIRST);
        final HtmlPage page2 = loadPage(webClient, html2, null, URL_SECOND);

        final DomNodeList<DomElement> elements = page.getElementsByTagName("*");
        assertEquals(5, elements.getLength());

        page.getBody().appendChild(page2.getElementById("tester"));
        assertEquals(6, elements.getLength());
    }
}
 
Example #3
Source File: Element.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the element would be selected by the specified selector string; otherwise, returns false.
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param function the function
 * @return the value
 */
@JsxFunction({CHROME, FF, FF68, FF60})
public static boolean matches(
        final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
    final String selectorString = (String) args[0];
    if (!(thisObj instanceof Element)) {
        throw ScriptRuntime.typeError("Illegal invocation");
    }
    try {
        final DomNode domNode = ((Element) thisObj).getDomNodeOrNull();
        return domNode != null && ((DomElement) domNode).matches(selectorString);
    }
    catch (final CSSException e) {
        throw ScriptRuntime.constructError("SyntaxError",
                "An invalid or illegal selector was specified (selector: '"
                + selectorString + "' error: " + e.getMessage() + ").");
    }
}
 
Example #4
Source File: HTMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private static List<DomNode> getItComputeElements(final HtmlPage page, final String name,
        final boolean forIDAndOrName, final boolean alsoFrames) {
    final List<DomElement> elements;
    if (forIDAndOrName) {
        elements = page.getElementsByIdAndOrName(name);
    }
    else {
        elements = page.getElementsByName(name);
    }
    final List<DomNode> matchingElements = new ArrayList<>();
    for (final DomElement elt : elements) {
        if (elt instanceof HtmlForm || elt instanceof HtmlImage || elt instanceof HtmlApplet
                || (alsoFrames && elt instanceof BaseFrameElement)) {
            matchingElements.add(elt);
        }
    }
    return matchingElements;
}
 
Example #5
Source File: AbstractList.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) {
        if (next instanceof DomElement) {
            final DomElement element = (DomElement) next;
            final String name = element.getAttributeDirect("name");
            if (name != DomElement.ATTRIBUTE_NOT_DEFINED) {
                idList.add(name);
            }
            final String id = element.getId();
            if (id != DomElement.ATTRIBUTE_NOT_DEFINED) {
                idList.add(id);
            }
        }
        if (!getBrowserVersion().hasFeature(JS_NODE_LIST_ENUMERATE_FUNCTIONS)) {
            idList.add(Integer.toString(index));
        }
        index++;
    }
}
 
Example #6
Source File: XmlUtils.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Search for the namespace URI of the given prefix, starting from the specified element.
 * The default namespace can be searched for by specifying "" as the prefix.
 * @param element the element to start searching from
 * @param prefix the namespace prefix
 * @return the namespace URI bound to the prefix; or null if there is no such namespace
 */
public static String lookupNamespaceURI(final DomElement element, final String prefix) {
    String uri = DomElement.ATTRIBUTE_NOT_DEFINED;
    if (prefix.isEmpty()) {
        uri = element.getAttributeDirect("xmlns");
    }
    else {
        uri = element.getAttribute("xmlns:" + prefix);
    }
    if (uri == DomElement.ATTRIBUTE_NOT_DEFINED) {
        final DomNode parentNode = element.getParentNode();
        if (parentNode instanceof DomElement) {
            uri = lookupNamespaceURI((DomElement) parentNode, prefix);
        }
    }
    return uri;
}
 
Example #7
Source File: PageFunctionTest.java    From tool.accelerate.core with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
// TODO: This method of testing does not work for angular, need to find an alternative method of testing
public void techFormTest() {
    final WebClient webClient = new WebClient(BrowserVersion.CHROME);
    HtmlPage page;
    String port = System.getProperty("liberty.test.port");
    try {
        page = webClient.getPage("http://localhost:" + port + "/start/");
        DomElement techForm = page.getElementById("techTable");
        DomElement formBody = techForm.getFirstElementChild();
        int count = formBody.getChildElementCount();
        // We expect there to be more than one child element, otherwise the 
        // javascript has not created the tech table properly.
        assertTrue("Expected more than one element in the tech table, instead found " + count, count > 1);
    } catch (Exception e){
        org.junit.Assert.fail("Caught exception: " + e.getCause().toString());
    } finally {
        webClient.close();
    }
}
 
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: HtmlUnitPrefixResolver.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private String getNamespace(final DomElement element, final String prefix) {
    final Map<String, DomAttr> attributes = element.getAttributesMap();
    final String xmlns = "xmlns:";
    final int xmlnsLength = xmlns.length();

    for (final Map.Entry<String, DomAttr> entry : attributes.entrySet()) {
        final String name = entry.getKey();
        if (name.startsWith(xmlns) && name.regionMatches(xmlnsLength, prefix, 0, prefix.length())) {
            return entry.getValue().getValue();
        }
    }
    for (final DomNode child : element.getChildren()) {
        if (child instanceof DomElement) {
            final String namespace = getNamespace((DomElement) child, prefix);
            if (namespace != null) {
                return namespace;
            }
        }
    }
    return null;
}
 
Example #10
Source File: EventTarget.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Dispatches an event into the event system (standards-conformant browsers only). See
 * <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent">the Gecko
 * DOM reference</a> for more information.
 *
 * @param event the event to be dispatched
 * @return {@code false} if at least one of the event handlers which handled the event
 *         called <tt>preventDefault</tt>; {@code true} otherwise
 */
@JsxFunction
public boolean dispatchEvent(final Event event) {
    event.setTarget(this);
    final DomElement element = (DomElement) getDomNodeOrNull();
    ScriptResult result = null;
    if (event.getType().equals(MouseEvent.TYPE_CLICK)) {
        try {
            element.click(event, true);
        }
        catch (final IOException e) {
            throw Context.reportRuntimeError("Error calling click(): " + e.getMessage());
        }
    }
    else {
        result = fireEvent(event);
    }
    return !event.isAborted(result);
}
 
Example #11
Source File: XMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the element with the specified ID, as long as it is an HTML element; {@code null} otherwise.
 * @param id the ID to search for
 * @return the element with the specified ID, as long as it is an HTML element; {@code null} otherwise
 */
@JsxFunction
public Object getElementById(final String id) {
    final DomNode domNode = getDomNodeOrDie();
    final Object domElement = domNode.getFirstByXPath("//*[@id = \"" + id + "\"]");
    if (domElement != null) {
        if (!(domNode instanceof XmlPage) || domElement instanceof HtmlElement
                || getBrowserVersion().hasFeature(JS_XML_GET_ELEMENT_BY_ID__ANY_ELEMENT)) {
            return ((DomElement) domElement).getScriptableObject();
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("getElementById(" + id + "): no HTML DOM node found with this ID");
        }
    }
    return null;
}
 
Example #12
Source File: XMLDOMElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the attribute.
 * @param name the name of the attribute to return
 * @return the value of the specified attribute, {@code null} if the named attribute does not have a
 *     specified value
 */
@JsxFunction
public Object getAttribute(final String name) {
    if (name == null || "null".equals(name)) {
        throw Context.reportRuntimeError("Type mismatch.");
    }
    if (StringUtils.isEmpty(name)) {
        throw Context.reportRuntimeError("The empty string '' is not a valid name.");
    }

    final String value = getDomNodeOrDie().getAttribute(name);
    if (value == DomElement.ATTRIBUTE_NOT_DEFINED) {
        return null;
    }
    return value;
}
 
Example #13
Source File: XMLDOMDocument.java    From htmlunit 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 #14
Source File: AbstractList.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) {
        if (next instanceof DomElement) {
            final DomElement element = (DomElement) next;
            final String name = element.getAttributeDirect("name");
            if (name != DomElement.ATTRIBUTE_NOT_DEFINED) {
                idList.add(name);
            }
            final String id = element.getId();
            if (id != DomElement.ATTRIBUTE_NOT_DEFINED) {
                idList.add(id);
            }
        }
        if (!getBrowserVersion().hasFeature(JS_NODE_LIST_ENUMERATE_FUNCTIONS)) {
            idList.add(Integer.toString(index));
        }
        index++;
    }
}
 
Example #15
Source File: XmlUtil.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Search for the namespace URI of the given prefix, starting from the specified element.
 * The default namespace can be searched for by specifying "" as the prefix.
 * @param element the element to start searching from
 * @param prefix the namespace prefix
 * @return the namespace URI bound to the prefix; or null if there is no such namespace
 */
public static String lookupNamespaceURI(final DomElement element, final String prefix) {
    String uri = DomElement.ATTRIBUTE_NOT_DEFINED;
    if (prefix.isEmpty()) {
        uri = element.getAttributeDirect("xmlns");
    }
    else {
        uri = element.getAttribute("xmlns:" + prefix);
    }
    if (uri == DomElement.ATTRIBUTE_NOT_DEFINED) {
        final DomNode parentNode = element.getParentNode();
        if (parentNode instanceof DomElement) {
            uri = lookupNamespaceURI((DomElement) parentNode, prefix);
        }
    }
    return uri;
}
 
Example #16
Source File: HTMLAnchorElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
static String getDefaultValue(final HtmlElement element) {
    String href = element.getAttributeDirect("href");

    if (DomElement.ATTRIBUTE_NOT_DEFINED == href) {
        return ""; // for example for named anchors
    }

    href = href.trim();

    final SgmlPage page = element.getPage();
    if (page == null || !page.isHtmlPage()) {
        return href;
    }

    try {
        return HtmlAnchor.getTargetUrl(href, (HtmlPage) page).toExternalForm();
    }
    catch (final MalformedURLException e) {
        return href;
    }
}
 
Example #17
Source File: HtmlUnitPrefixResolver.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private String getNamespace(final DomElement element, final String prefix) {
    final Map<String, DomAttr> attributes = element.getAttributesMap();
    final String xmlns = "xmlns:";
    final int xmlnsLength = xmlns.length();

    for (final Map.Entry<String, DomAttr> entry : attributes.entrySet()) {
        final String name = entry.getKey();
        if (name.startsWith(xmlns) && name.regionMatches(xmlnsLength, prefix, 0, prefix.length())) {
            return entry.getValue().getValue();
        }
    }
    for (final DomNode child : element.getChildren()) {
        if (child instanceof DomElement) {
            final String namespace = getNamespace((DomElement) child, prefix);
            if (namespace != null) {
                return namespace;
            }
        }
    }
    return null;
}
 
Example #18
Source File: XmlUtil.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Search for the prefix associated with specified namespace URI.
 * @param element the element to start searching from
 * @param namespace the namespace prefix
 * @return the prefix bound to the namespace URI; or null if there is no such namespace
 */
public static String lookupPrefix(final DomElement element, final String namespace) {
    final Map<String, DomAttr> attributes = element.getAttributesMap();
    for (final Map.Entry<String, DomAttr> entry : attributes.entrySet()) {
        final String name = entry.getKey();
        final DomAttr value = entry.getValue();
        if (name.startsWith("xmlns:") && value.getValue().equals(namespace)) {
            return name.substring(6);
        }
    }
    for (final DomNode child : element.getChildren()) {
        if (child instanceof DomElement) {
            final String prefix = lookupPrefix((DomElement) child, namespace);
            if (prefix != null) {
                return prefix;
            }
        }
    }
    return null;
}
 
Example #19
Source File: Node.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the children of the current node.
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms537446.aspx">MSDN documentation</a>
 * @return the child at the given position
 */
protected HTMLCollection getChildren() {
    final DomNode node = getDomNodeOrDie();
    final HTMLCollection collection = new HTMLCollection(node, false) {
        @Override
        protected List<DomNode> computeElements() {
            final List<DomNode> children = new LinkedList<>();
            for (DomNode domNode : node.getChildNodes()) {
                if (domNode instanceof DomElement) {
                    children.add(domNode);
                }
            }
            return children;
        }
    };
    return collection;
}
 
Example #20
Source File: Node.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * If we have added a new iframe that
 * had no source attribute, we have to take care the
 * 'onload' handler is triggered.
 *
 * @param childDomNode
 */
private static void initInlineFrameIfNeeded(final DomNode childDomNode) {
    if (childDomNode instanceof HtmlInlineFrame) {
        final HtmlInlineFrame frame = (HtmlInlineFrame) childDomNode;
        if (DomElement.ATTRIBUTE_NOT_DEFINED == frame.getSrcAttribute()) {
            frame.loadInnerPage();
        }
    }
}
 
Example #21
Source File: SgmlPage.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the document element.
 * @return the document element
 */
@Override
public DomElement getDocumentElement() {
    DomNode childNode = getFirstChild();
    while (childNode != null && !(childNode instanceof DomElement)) {
        childNode = childNode.getNextSibling();
    }
    return (DomElement) childNode;
}
 
Example #22
Source File: SgmlPage.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String asXml() {
    final DomElement documentElement = getDocumentElement();
    if (documentElement == null) {
        return "";
    }
    return documentElement.asXml();
}
 
Example #23
Source File: JadeIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsesModel() throws Exception {
    String path = baseURL + "jade?user=mvc%d";
    final HtmlPage page = webClient.getPage(String.format(path, 0));
    assertTrue(page.getTitleText().contains("Jade"));
    for (int i = 0; i < 10; i++) { // just to ensure that not the whole page is cached
        final HtmlPage subPage = webClient.getPage(String.format(path, i));
        final DomElement h1 = subPage.getFirstByXPath("//html/body/h1");
        assertTrue(h1.getTextContent().contains("mvc" + i));
    }
}
 
Example #24
Source File: XMLDOMAttribute.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Detaches this attribute from the parent HTML element after caching the attribute value.
 */
public void detachFromParent() {
    final DomAttr domNode = getDomNodeOrDie();
    final DomElement parent = (DomElement) domNode.getParentNode();
    if (parent != null) {
        domNode.setValue(parent.getAttribute(getName()));
    }
    domNode.remove();
}
 
Example #25
Source File: XMLDOMElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Normalizes all descendant elements by combining two or more adjacent text nodes into one unified text node.
 */
@JsxFunction
public void normalize() {
    final DomElement domElement = getDomNodeOrDie();

    domElement.normalize();
    // normalize all descendants
    normalize(domElement);
}
 
Example #26
Source File: JadeIT.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfiguration() throws Exception {
    final HtmlPage page = webClient.getPage(baseURL + "jade/config");
    final DomElement systemProperties = page.getFirstByXPath("//p[@class='SystemProperties']");
    assertEquals("SystemProperties", systemProperties.getTextContent());
    final DomElement configFile = page.getFirstByXPath("//p[@class='ConfigFile']");
    assertEquals("ConfigFile", configFile.getTextContent());
}
 
Example #27
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 #28
Source File: XMLDOMDocument.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an element node using the specified name.
 * @param tagName the name for the new element node
 * @return the new element object or <code>NOT_FOUND</code> if the tag is not supported
 */
@JsxFunction
public Object createElement(final String tagName) {
    if (tagName == null || "null".equals(tagName)) {
        throw Context.reportRuntimeError("Type mismatch.");
    }
    if (StringUtils.isBlank(tagName) || tagName.indexOf('<') >= 0 || tagName.indexOf('>') >= 0) {
        throw Context.reportRuntimeError("To create a node of type ELEMENT a valid name must be given.");
    }

    Object result = NOT_FOUND;
    try {
        final DomElement domElement = (DomElement) getPage().createElement(tagName);
        final Object jsElement = getScriptableFor(domElement);

        if (jsElement == NOT_FOUND) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("createElement(" + tagName
                    + ") cannot return a result as there isn't a JavaScript object for the element "
                    + domElement.getClass().getName());
            }
        }
        else {
            result = jsElement;
        }
    }
    catch (final ElementNotFoundException e) {
        // Just fall through - result is already set to NOT_FOUND
    }
    return result;
}
 
Example #29
Source File: Node.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * If we have added a new iframe that
 * had no source attribute, we have to take care the
 * 'onload' handler is triggered.
 *
 * @param childDomNode
 */
private static void initInlineFrameIfNeeded(final DomNode childDomNode) {
    if (childDomNode instanceof HtmlInlineFrame) {
        final HtmlInlineFrame frame = (HtmlInlineFrame) childDomNode;
        if (DomElement.ATTRIBUTE_NOT_DEFINED == frame.getSrcAttribute()) {
            frame.loadInnerPage();
        }
    }
}
 
Example #30
Source File: CharacterData.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the previous element sibling.
 * @return the previous element sibling
 */
@JsxGetter({CHROME, FF, FF68, FF60})
public Element getPreviousElementSibling() {
    final DomElement child = getDomNodeOrDie().getPreviousElementSibling();
    if (child != null) {
        return (Element) child.getScriptableObject();
    }
    return null;
}