org.w3c.dom.node

Here are the examples of the java api class org.w3c.dom.node taken from open source projects.

1. ContentHosting#getVirtualBlock()

Project: sakai
Source File: ContentHosting.java
View license
/*
	 *  Create a resouce XML node for the virtual root containing:
	 *  <ul>
	 *  <li>id - resource identifier</li>
	 *  <li>name - display name</li>
	 *  <li>type - resource type</li>
	 *  </ul>
	 *
	 *  @author Mark Norton
	 */
private Node getVirtualBlock(Document dom) {
    String id = ContentHosting.VIRTUAL_ROOT_ID;
    String name = ContentHosting.VIRTUAL_ROOT_NAME;
    String type = ContentHosting.RESOURCE_TYPE_COLLECTION;
    //  Create the resource element.
    Node item = dom.createElement("resource");
    //  Create and append the id child element.
    Node resId = dom.createElement("id");
    resId.appendChild(dom.createTextNode(id));
    item.appendChild(resId);
    //  Create and append the name child element.
    Node resName = dom.createElement("name");
    resName.appendChild(dom.createTextNode(name));
    item.appendChild(resName);
    //  Create and append the type child element.
    Node resType = dom.createElement("type");
    resType.appendChild(dom.createTextNode(type));
    item.appendChild(resType);
    return item;
}

2. YamahaReceiverProxy#getState()

Project: openhab
Source File: YamahaReceiverProxy.java
View license
public YamahaReceiverState getState(Zone zone) throws IOException {
    Document doc = postAndGetXmlResponse("<?xml version=\"1.0\" encoding=\"utf-8\"?><YAMAHA_AV cmd=\"GET\"><" + zone + "><Basic_Status>GetParam</Basic_Status></" + zone + "></YAMAHA_AV>");
    Node basicStatus = getNode(doc.getFirstChild(), "" + zone + "/Basic_Status");
    Node powerNode = getNode(basicStatus, "Power_Control/Power");
    boolean power = powerNode != null ? "On".equalsIgnoreCase(powerNode.getTextContent()) : false;
    Node inputNode = getNode(basicStatus, "Input/Input_Sel");
    String input = inputNode != null ? inputNode.getTextContent() : null;
    Node soundProgramNode = getNode(basicStatus, "Surround/Program_Sel/Current/Sound_Program");
    String soundProgram = soundProgramNode != null ? soundProgramNode.getTextContent() : null;
    Node volumeNode = getNode(basicStatus, "Volume/Lvl/Val");
    float volume = volumeNode != null ? Float.parseFloat(volumeNode.getTextContent()) * .1f : VOLUME_MIN;
    Node muteNode = getNode(basicStatus, "Volume/Mute");
    boolean mute = muteNode != null ? "On".equalsIgnoreCase(muteNode.getTextContent()) : false;
    return new YamahaReceiverState(power, input, soundProgram, volume, mute);
}

3. BinderImpl#updateXML()

Project: openjdk
Source File: BinderImpl.java
View license
public XmlNode updateXML(Object jaxbObject, XmlNode xmlNode) throws JAXBException {
    if (jaxbObject == null || xmlNode == null)
        throw new IllegalArgumentException();
    // TODO
    // for now just marshal
    // TODO: object model independenc
    Element e = (Element) xmlNode;
    Node ns = e.getNextSibling();
    Node p = e.getParentNode();
    p.removeChild(e);
    // if the type object is passed, the following step is necessary to make
    // the marshalling successful.
    JaxBeanInfo bi = context.getBeanInfo(jaxbObject, true);
    if (!bi.isElement())
        jaxbObject = new JAXBElement(new QName(e.getNamespaceURI(), e.getLocalName()), bi.jaxbType, jaxbObject);
    getMarshaller().marshal(jaxbObject, p);
    Node newNode = p.getLastChild();
    p.removeChild(newNode);
    p.insertBefore(newNode, ns);
    return (XmlNode) newNode;
}

4. NodeValueMerge#merge()

View license
@Override
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }
    Node node1 = nodeList1.get(0);
    Node node2 = nodeList2.get(0);
    Set<String> finalItems = getMergedNodeValues(node1, node2);
    StringBuilder sb = new StringBuilder();
    Iterator<String> itr = finalItems.iterator();
    while (itr.hasNext()) {
        sb.append(itr.next());
        if (itr.hasNext()) {
            sb.append(getDelimiter());
        }
    }
    node1.setNodeValue(sb.toString());
    node2.setNodeValue(sb.toString());
    Node[] response = new Node[nodeList2.size()];
    for (int j = 0; j < response.length; j++) {
        response[j] = nodeList2.get(j);
    }
    return response;
}

5. NodeValueMerge#merge()

View license
@Override
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }
    Node node1 = nodeList1.get(0);
    Node node2 = nodeList2.get(0);
    Set<String> finalItems = getMergedNodeValues(node1, node2);
    StringBuilder sb = new StringBuilder();
    Iterator<String> itr = finalItems.iterator();
    while (itr.hasNext()) {
        sb.append(itr.next());
        if (itr.hasNext()) {
            sb.append(getDelimiter());
        }
    }
    node1.setNodeValue(sb.toString());
    node2.setNodeValue(sb.toString());
    Node[] response = new Node[nodeList2.size()];
    for (int j = 0; j < response.length; j++) {
        response[j] = nodeList2.get(j);
    }
    return response;
}

6. WindowsAzureCertificate#delete()

View license
public void delete() throws WindowsAzureInvalidProjectOperationException {
    if (isRemoteAccess()) {
        throw new WindowsAzureInvalidProjectOperationException("This certificate is assoiciated with remote access");
    }
    // remove from map
    wRole.certMap.remove(getName());
    // Remove from cscfg
    Element certEle = getCscfgCertNode();
    Node parentNode = certEle.getParentNode();
    parentNode.removeChild(certEle);
    removeParentNodeIfNeeded(parentNode);
    // Remove from csdef
    Element certCsdefEle = getCsdefCertNode();
    Node parentCsdefNode = certCsdefEle.getParentNode();
    parentCsdefNode.removeChild(certCsdefEle);
    removeParentNodeIfNeeded(parentCsdefNode);
}

7. SchemaLocationMergeTest#testNodeAttributes()

View license
@Test
public void testNodeAttributes() {
    Node node1 = new DummyNode();
    node1.setNodeValue("http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" + "\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-8.4.xsd" + "\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-9.4.xsd" + "\nhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd");
    Node node2 = new DummyNode();
    node2.setNodeValue("http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans.xsd");
    Set<String> mergedVals = merge.getMergedNodeValues(node1, node2);
    assertArrayEquals(new String[] { "http://www.springframework.org/schema/beans", "http://www.springframework.org/schema/beans/spring-beans.xsd", "http://www.springframework.org/schema/tx", "http://www.springframework.org/schema/tx/spring-tx.xsd" }, mergedVals.toArray());
}

8. SchemaLocationMergeTest#testAddedAttributes()

View license
@Test
public void testAddedAttributes() {
    Node node1 = new DummyNode();
    node1.setNodeValue("http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd");
    Node node2 = new DummyNode();
    node2.setNodeValue("http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd");
    Set<String> mergedVals = merge.getMergedNodeValues(node1, node2);
    assertArrayEquals(new String[] { "http://www.springframework.org/schema/beans", "http://www.springframework.org/schema/beans/spring-beans.xsd", "http://www.springframework.org/schema/tx", "http://www.springframework.org/schema/tx/spring-tx.xsd" }, mergedVals.toArray());
}

9. SchemaLocationMergeTest#testNodeAttributes()

View license
@Test
public void testNodeAttributes() {
    Node node1 = new DummyNode();
    node1.setNodeValue("http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" + "\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-8.4.xsd" + "\nhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-9.4.xsd" + "\nhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd");
    Node node2 = new DummyNode();
    node2.setNodeValue("http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans.xsd");
    Set<String> mergedVals = merge.getMergedNodeValues(node1, node2);
    assertArrayEquals(new String[] { "http://www.springframework.org/schema/beans", "http://www.springframework.org/schema/beans/spring-beans.xsd", "http://www.springframework.org/schema/tx", "http://www.springframework.org/schema/tx/spring-tx.xsd" }, mergedVals.toArray());
}

10. SchemaLocationMergeTest#testAddedAttributes()

View license
@Test
public void testAddedAttributes() {
    Node node1 = new DummyNode();
    node1.setNodeValue("http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd");
    Node node2 = new DummyNode();
    node2.setNodeValue("http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd");
    Set<String> mergedVals = merge.getMergedNodeValues(node1, node2);
    assertArrayEquals(new String[] { "http://www.springframework.org/schema/beans", "http://www.springframework.org/schema/beans/spring-beans.xsd", "http://www.springframework.org/schema/tx", "http://www.springframework.org/schema/tx/spring-tx.xsd" }, mergedVals.toArray());
}

11. NodeListIteratorTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    super.setUp();
    // Default: use standard constr.
    createIteratorWithStandardConstr = true;
    // create mocked Node Instances and fill Node[] to be used by test cases
    final Node node1 = createMock(Element.class);
    final Node node2 = createMock(Element.class);
    final Node node3 = createMock(Text.class);
    final Node node4 = createMock(Element.class);
    nodes = new Node[] { node1, node2, node3, node4 };
    replay(node1);
    replay(node2);
    replay(node3);
    replay(node4);
}

12. IteratorUtilsTest#createNodes()

View license
/**
     * creates an array of four Node instances, mocked by EasyMock.
     */
private Node[] createNodes() {
    final Node node1 = createMock(Node.class);
    final Node node2 = createMock(Node.class);
    final Node node3 = createMock(Node.class);
    final Node node4 = createMock(Node.class);
    replay(node1);
    replay(node2);
    replay(node3);
    replay(node4);
    return new Node[] { node1, node2, node3, node4 };
}

13. RemoveUnsupportedMarkupNotePreProcessor#processUnsupportedDomNode()

View license
/**
     * Moves all children of the unsupported node one layer upwards in DOM hierarchy and removes the
     * unsupported node afterwards. The children will be inserted before the unsupported node in
     * correct order.
     * 
     * @param unsupportedNode
     *            the unsupported node
     */
private void processUnsupportedDomNode(Node unsupportedNode) {
    Node parent = unsupportedNode.getParentNode();
    Node refNode = unsupportedNode;
    // start with last node because there is only an insertBefore method
    Node child = unsupportedNode.getLastChild();
    while (child != null) {
        Node nextChild = child.getPreviousSibling();
        // insert before reference node (removes child automatically before
        // insert)
        parent.insertBefore(child, refNode);
        refNode = child;
        child = nextChild;
    }
    // remove the unsupported node
    parent.removeChild(unsupportedNode);
}

14. NamedNodeMapTest#testSetNamedItem()

Project: openjdk
Source File: NamedNodeMapTest.java
View license
/*
     * Test setNamedItem method with a node having the same name as an existing
     * one, and then test with a non-existing node.
     */
@Test
public void testSetNamedItem() throws Exception {
    Document document = createDOMWithNS("NamedNodeMap03.xml");
    NodeList nodeList = document.getElementsByTagName("body");
    nodeList = nodeList.item(0).getChildNodes();
    Node n = nodeList.item(1);
    NamedNodeMap namedNodeMap = n.getAttributes();
    Attr attr = document.createAttribute("name");
    Node replacedAttr = namedNodeMap.setNamedItem(attr);
    assertEquals(replacedAttr.getNodeValue(), "attributeValue");
    Node updatedAttrNode = namedNodeMap.getNamedItem("name");
    assertEquals(updatedAttrNode.getNodeValue(), "");
    Attr newAttr = document.createAttribute("nonExistingName");
    assertNull(namedNodeMap.setNamedItem(newAttr));
    Node newAttrNode = namedNodeMap.getNamedItem("nonExistingName");
    assertEquals(newAttrNode.getNodeValue(), "");
}

15. NodeTest#testCloneNode()

Project: openjdk
Source File: NodeTest.java
View license
/*
     * Test cloneNode deeply, and the clone node can be appended on the same document.
     */
@Test
public void testCloneNode() throws Exception {
    Document document = createDOMWithNS("Node02.xml");
    NodeList nodeList = document.getElementsByTagName("body");
    Node node = nodeList.item(0);
    Node cloneNode = node.cloneNode(true);
    assertTrue(node.isEqualNode(cloneNode));
    assertNotEquals(node, cloneNode);
    nodeList = document.getElementsByTagName("html");
    Node node2 = nodeList.item(0);
    node2.appendChild(cloneNode);
}

16. XmlTest#testDOMParse()

Project: pgjdbc
Source File: XmlTest.java
View license
public void testDOMParse() throws SQLException {
    ResultSet rs = getRS();
    assertTrue(rs.next());
    SQLXML xml = rs.getSQLXML(1);
    DOMSource source = xml.getSource(DOMSource.class);
    Node doc = source.getNode();
    Node root = doc.getFirstChild();
    assertEquals("a", root.getNodeName());
    Node first = root.getFirstChild();
    assertEquals("b", first.getNodeName());
    assertEquals("1", first.getTextContent());
    Node last = root.getLastChild();
    assertEquals("b", last.getNodeName());
    assertEquals("2", last.getTextContent());
    assertTrue(rs.next());
    try {
        xml = rs.getSQLXML(1);
        source = xml.getSource(DOMSource.class);
        fail("Can't retrieve a fragment.");
    } catch (SQLException sqle) {
    }
}

17. SignatureFakingOracle#appendCertificate()

View license
private void appendCertificate(Node keyInfo, String certificate) {
    keyInfo.setTextContent("");
    String prefix = keyInfo.getPrefix();
    if (prefix == null) {
        prefix = "";
    } else {
        prefix = prefix + ":";
    }
    Node data = keyInfo.getOwnerDocument().createElementNS(NamespaceConstants.URI_NS_DS, prefix + "X509Data");
    keyInfo.appendChild(data);
    Node cert = keyInfo.getOwnerDocument().createElementNS(NamespaceConstants.URI_NS_DS, prefix + "X509Certificate");
    data.appendChild(cert);
    cert.setTextContent(certificate);
    log.debug("Appending Certificate \r\n" + certificate + "\r\nto the" + prefix + "X509Certificate element");
}

18. GeneratorTest#testProducesNamedBeans()

Project: apache-aries
Source File: GeneratorTest.java
View license
@Test
public void testProducesNamedBeans() throws Exception {
    Node bean1 = getBeanById("produced1");
    assertEquals("org.apache.aries.blueprint.plugin.test.MyProduced", xpath.evaluate("@class", bean1));
    assertEquals("myFactoryNamedBean", xpath.evaluate("@factory-ref", bean1));
    assertEquals("createBean1", xpath.evaluate("@factory-method", bean1));
    assertEquals("prototype", xpath.evaluate("@scope", bean1));
    Node bean2 = getBeanById("produced2");
    assertEquals("org.apache.aries.blueprint.plugin.test.MyProduced", xpath.evaluate("@class", bean1));
    assertEquals("myFactoryNamedBean", xpath.evaluate("@factory-ref", bean2));
    assertEquals("createBean2", xpath.evaluate("@factory-method", bean2));
    assertEquals("", xpath.evaluate("@scope", bean2));
    Node myBean5 = getBeanById("myBean5");
    assertEquals("produced2", xpath.evaluate("argument[8][email protected]", myBean5));
}

19. GeneratorTest#testProducesNamedBeans()

Project: aries
Source File: GeneratorTest.java
View license
@Test
public void testProducesNamedBeans() throws Exception {
    Node bean1 = getBeanById("produced1");
    assertXpathEquals(bean1, "@class", "org.apache.aries.blueprint.plugin.test.MyProduced");
    assertXpathEquals(bean1, "@factory-ref", "myFactoryNamedBean");
    assertXpathEquals(bean1, "@factory-method", "createBean1");
    assertXpathEquals(bean1, "@scope", "prototype");
    Node bean2 = getBeanById("produced2");
    assertXpathEquals(bean1, "@class", "org.apache.aries.blueprint.plugin.test.MyProduced");
    assertXpathEquals(bean2, "@factory-ref", "myFactoryNamedBean");
    assertXpathEquals(bean2, "@factory-method", "createBean2");
    assertXpathDoesNotExist(bean2, "@scope");
    Node myBean5 = getBeanById("myBean5");
    assertXpathEquals(myBean5, "argument[8][email protected]", "produced2");
}

20. RegionMetadataParser#getChildElementValue()

View license
private static String getChildElementValue(final String tagName, final Element element) {
    Node tagNode = element.getElementsByTagName(tagName).item(0);
    if (tagNode == null)
        return null;
    NodeList nodes = tagNode.getChildNodes();
    Node node = (Node) nodes.item(0);
    return node.getNodeValue();
}

21. DOMTreeWalker#previousNode()

Project: batik
Source File: DOMTreeWalker.java
View license
/**
     * <b>DOM</b>: Implements [email protected] TreeWalker#previousNode()}.
     */
public Node previousNode() {
    Node result = previousSibling(currentNode, root);
    if (result == null) {
        result = parentNode(currentNode);
        if (result != null) {
            currentNode = result;
        }
        return result;
    }
    Node n = lastChild(result);
    Node last = n;
    while (n != null) {
        last = n;
        n = lastChild(last);
    }
    return currentNode = (last != null) ? last : result;
}

22. InsertChildrenOf#merge()

View license
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }
    Node node1 = nodeList1.get(0);
    Node node2 = nodeList2.get(0);
    NodeList list2 = node2.getChildNodes();
    for (int j = 0; j < list2.getLength(); j++) {
        node1.appendChild(node1.getOwnerDocument().importNode(list2.item(j).cloneNode(true), true));
    }
    Node[] response = new Node[nodeList2.size()];
    for (int j = 0; j < response.length; j++) {
        response[j] = nodeList2.get(j);
    }
    return response;
}

23. InsertChildrenOf#merge()

View license
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }
    Node node1 = nodeList1.get(0);
    Node node2 = nodeList2.get(0);
    NodeList list2 = node2.getChildNodes();
    for (int j = 0; j < list2.getLength(); j++) {
        node1.appendChild(node1.getOwnerDocument().importNode(list2.item(j).cloneNode(true), true));
    }
    Node[] response = new Node[nodeList2.size()];
    for (int j = 0; j < response.length; j++) {
        response[j] = nodeList2.get(j);
    }
    return response;
}

24. IteratorUtilsTest#testNodeIterator()

View license
/**
     * Tests method nodeListIterator(Node)
     */
@Test
public void testNodeIterator() {
    final Node[] nodes = createNodes();
    final NodeList nodeList = createNodeList(nodes);
    final Node parentNode = createMock(Node.class);
    expect(parentNode.getChildNodes()).andStubReturn(nodeList);
    replay(parentNode);
    final Iterator<Node> iterator = IteratorUtils.nodeListIterator(parentNode);
    int expectedNodeIndex = 0;
    for (final Node actual : IteratorUtils.asIterable(iterator)) {
        assertEquals(nodes[expectedNodeIndex], actual);
        ++expectedNodeIndex;
    }
    // insure iteration occurred
    assertTrue(expectedNodeIndex > 0);
    // single use iterator
    assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext());
}

25. XMLUtil#changeTagName()

Project: empire-db
Source File: XMLUtil.java
View license
/**
     * Changes the tag name of an element.
     * 
     * @param elem Element which name should be changed
     * @param newName new tag name of the element
     * @return true if the name was changed successfully or false otherwise
     */
public static boolean changeTagName(Element elem, String newName) {
    if (elem == null)
        // not Found!
        return false;
    Document doc = elem.getOwnerDocument();
    Element newElem = doc.createElement(newName);
    // Copy the attributes to the new element
    NamedNodeMap attrs = elem.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
        newElem.getAttributes().setNamedItem(attr2);
    }
    // Copy all Child Elements
    for (Node node = elem.getFirstChild(); node != null; node = node.getNextSibling()) newElem.appendChild(node.cloneNode(true));
    // insert
    Node parent = elem.getParentNode();
    parent.replaceChild(newElem, elem);
    return true;
}

26. XmlNode#coalesceTextNodes()

Project: gocd
Source File: XmlNode.java
View license
/**
     * Coalesce to adjacent TextNodes.
     * @param context
     * @param prev Previous node to cur.
     * @param cur Next node to prev.
     */
public static void coalesceTextNodes(ThreadContext context, IRubyObject prev, IRubyObject cur) {
    XmlNode p = asXmlNode(context, prev);
    XmlNode c = asXmlNode(context, cur);
    Node pNode = p.node;
    Node cNode = c.node;
    pNode.setNodeValue(pNode.getNodeValue() + cNode.getNodeValue());
    // clear cached content
    p.content = null;
    c.assimilateXmlNode(context, p);
}

27. PackageManifestDocumentUtils#addMemberNode()

View license
/**
     * creates a new member element and adds it as a child of the given type element. If the member element already
     * exists will return the existing element
     * 
     * @param componentTypeNode
     *            the type element
     * @param memberName
     *            the name of the new member element
     * @return the member element which has name memberName
     */
public static Node addMemberNode(Node componentTypeNode, String memberName) {
    Node nameNode = getComponentNameNode(componentTypeNode);
    Node wildcard = getMemberNode(componentTypeNode, Constants.PACKAGE_MANIFEST_WILDCARD);
    Node member = getMemberNode(componentTypeNode, memberName);
    if (member == null) {
        member = componentTypeNode.getOwnerDocument().createElementNS(Constants.PACKAGE_MANIFEST_NAMESPACE_URI, Constants.PACKAGE_MANIFEST_TYPE_MEMBERS);
        Text memberNameNode = componentTypeNode.getOwnerDocument().createTextNode(memberName);
        member.appendChild(memberNameNode);
        if (wildcard == null) {
            componentTypeNode.insertBefore(member, nameNode);
        } else {
            componentTypeNode.insertBefore(member, wildcard);
        }
    }
    return member;
}

28. W3CDomTest#namespacePreservation()

Project: jsoup
Source File: W3CDomTest.java
View license
@Test
public void namespacePreservation() throws IOException {
    File in = ParseTest.getFile("/htmltests/namespaces.xhtml");
    org.jsoup.nodes.Document jsoupDoc;
    jsoupDoc = Jsoup.parse(in, "UTF-8");
    Document doc;
    org.jsoup.helper.W3CDom jDom = new org.jsoup.helper.W3CDom();
    doc = jDom.fromJsoup(jsoupDoc);
    Node htmlEl = doc.getChildNodes().item(0);
    assertEquals("http://www.w3.org/1999/xhtml", htmlEl.getNamespaceURI());
    assertEquals("html", htmlEl.getLocalName());
    assertEquals("html", htmlEl.getNodeName());
    Node epubTitle = htmlEl.getChildNodes().item(2).getChildNodes().item(3);
    assertEquals("http://www.idpf.org/2007/ops", epubTitle.getNamespaceURI());
    assertEquals("title", epubTitle.getLocalName());
    assertEquals("epub:title", epubTitle.getNodeName());
    Node xSection = epubTitle.getNextSibling().getNextSibling();
    assertEquals("urn:test", xSection.getNamespaceURI());
    assertEquals("section", xSection.getLocalName());
    assertEquals("x:section", xSection.getNodeName());
}

29. TiledMapPacker#setProperty()

Project: libgdx
Source File: TiledMapPacker.java
View license
private static void setProperty(Document doc, Node parent, String name, String value) {
    Node properties = getFirstChildNodeByName(parent, "properties");
    Node property = getFirstChildByNameAttrValue(properties, "property", "name", name);
    NamedNodeMap attributes = property.getAttributes();
    Node valueNode = attributes.getNamedItem("value");
    if (valueNode == null) {
        valueNode = doc.createAttribute("value");
        valueNode.setNodeValue(value);
        attributes.setNamedItem(valueNode);
    } else {
        valueNode.setNodeValue(value);
    }
}

30. NodeTest#testImportNode()

Project: openjdk
Source File: NodeTest.java
View license
/*
     * Test importing node from one document to another.
     */
@Test
public void testImportNode() throws Exception {
    Document document = createDOMWithNS("Node02.xml");
    Document otherDocument = createDOMWithNS("ElementSample01.xml");
    NodeList otherNodeList = otherDocument.getElementsByTagName("body");
    Node importedNode = otherNodeList.item(0);
    Node clone = importedNode.cloneNode(true);
    Node retNode = document.importNode(importedNode, true);
    //verify importedNode is not changed
    assertTrue(clone.isEqualNode(importedNode));
    assertNotEquals(retNode, importedNode);
    assertTrue(importedNode.isEqualNode(retNode));
    retNode = document.importNode(importedNode, false);
    //verify importedNode is not changed
    assertTrue(clone.isEqualNode(importedNode));
    assertEquals(retNode.getNodeName(), importedNode.getNodeName());
    assertFalse(importedNode.isEqualNode(retNode));
}

31. PDI_11319Test#getNullIfStep()

Project: pentaho-kettle
Source File: PDI_11319Test.java
View license
private Node getNullIfStep(Node doc) {
    Node trans = XMLHandler.getSubNode(doc, "transformation");
    List<Node> steps = XMLHandler.getNodes(trans, "step");
    Node nullIfStep = null;
    for (Node step : steps) {
        if ("IfNull".equals(XMLHandler.getNodeValue(XMLHandler.getSubNode(step, "type")))) {
            nullIfStep = step;
            break;
        }
    }
    return nullIfStep;
}

32. Assembler#replaceByBody()

Project: sis
Source File: Assembler.java
View license
/**
     * Copies the body of the given source HTML file in-place of the given target node.
     * This method is doing the work of [email protected] <xi:include>} element. We do this work ourself instead than relying on
     * [email protected] DocumentBuilder} build-in support mostly because we have been unable to get the [email protected] xpointer} to work.
     *
     * @param filename  the source XML file in the same directory than the input file given to the constructor.
     * @param toReplace the target XML node to be replaced by the content of the given file.
     */
private Node[] replaceByBody(final String filename, final Node toReplace) throws IOException, SAXException, BookException {
    final NodeList nodes = load(filename).getElementsByTagName("body");
    if (nodes.getLength() != 1) {
        throw new BookException(filename + ": expected exactly one <body> element.");
    }
    final Node parent = toReplace.getParentNode();
    parent.removeChild(toReplace);
    Node[] childNodes = toArray(nodes.item(0).getChildNodes());
    for (int i = 0; i < childNodes.length; i++) {
        Node child = childNodes[i];
        // document.adoptNode(child) would have been more efficient but does not seem to work.
        child = document.importNode(child, true);
        if (child == null) {
            throw new BookException("Failed to copy subtree.");
        }
        parent.appendChild(child);
        childNodes[i] = child;
    }
    return childNodes;
}

33. Conf#processRuleBasics()

Project: urlrewritefilter
Source File: Conf.java
View license
private void processRuleBasics(Element ruleElement, RuleBase rule) {
    if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "enabled")))
        rule.setEnabled(false);
    String ruleMatchType = getAttrValue(ruleElement, "match-type");
    if (StringUtils.isBlank(ruleMatchType))
        ruleMatchType = defaultMatchType;
    rule.setMatchType(ruleMatchType);
    Node nameNode = ruleElement.getElementsByTagName("name").item(0);
    rule.setName(getNodeValue(nameNode));
    Node noteNode = ruleElement.getElementsByTagName("note").item(0);
    rule.setNote(getNodeValue(noteNode));
    Node fromNode = ruleElement.getElementsByTagName("from").item(0);
    rule.setFrom(getNodeValue(fromNode));
    if ("true".equalsIgnoreCase(getAttrValue(fromNode, "casesensitive")))
        rule.setFromCaseSensitive(true);
}

34. XmlUtils#getAttribute()

Project: APKParser
Source File: XmlUtils.java
View license
public static String getAttribute(NamedNodeMap namedNodeMap, String name) {
    Node node = namedNodeMap.getNamedItem(name);
    if (node == null) {
        if (name.startsWith("android:")) {
            name = name.substring("android:".length());
        }
        node = namedNodeMap.getNamedItem(name);
        if (node == null) {
            return null;
        }
    }
    return node.getNodeValue();
}

35. WSDLElementQualifier#getNameAttribute()

View license
/**
     * Obtain the name attribute for the node
     * @param node an Element for which the Name attribute is sought
     * @return the name attribute for the node if the "name" attribute
     *  exists, otherwise return ""
     */
protected String getNameAttribute(Node node) {
    NamedNodeMap nnMap = node.getAttributes();
    if (nnMap.getLength() == 0) {
        return "";
    }
    Node nameAttrNode = nnMap.getNamedItem("name");
    if (nameAttrNode == null) {
        return "";
    }
    return nameAttrNode.getNodeValue();
}

36. XmlUserManager#parseGroupRoleTag()

Project: azkaban
Source File: XmlUserManager.java
View license
private void parseGroupRoleTag(Node node, HashMap<String, Set<String>> groupRoles) {
    NamedNodeMap groupAttrMap = node.getAttributes();
    Node groupNameAttr = groupAttrMap.getNamedItem(GROUPNAME_ATTR);
    if (groupNameAttr == null) {
        throw new RuntimeException("Error loading role. The role 'name' attribute doesn't exist");
    }
    String groupName = groupNameAttr.getNodeValue();
    Set<String> roleSet = new HashSet<String>();
    Node roles = groupAttrMap.getNamedItem(ROLES_ATTR);
    if (roles != null) {
        String value = roles.getNodeValue();
        String[] roleSplit = value.split("\\s*,\\s*");
        for (String role : roleSplit) {
            roleSet.add(role);
        }
    }
    groupRoles.put(groupName, roleSet);
    logger.info("Group roles " + groupName + " added.");
}

37. DefaultXBLManager#getXblParentNode()

Project: batik
Source File: DefaultXBLManager.java
View license
/**
     * Get the parent of a node in the fully flattened tree.
     */
public Node getXblParentNode(Node n) {
    Node contentElement = getXblContentElement(n);
    Node parent = contentElement == null ? n.getParentNode() : contentElement.getParentNode();
    if (parent instanceof XBLOMContentElement) {
        parent = parent.getParentNode();
    }
    if (parent instanceof XBLOMShadowTreeElement) {
        parent = getXblBoundElement(parent);
    }
    return parent;
}

38. SVGTextElementBridge#handleDOMNodeInsertedEvent()

Project: batik
Source File: SVGTextElementBridge.java
View license
/**
     * Invoked when an MutationEvent of type 'DOMNodeInserted' is fired.
     */
public void handleDOMNodeInsertedEvent(MutationEvent evt) {
    Node childNode = (Node) evt.getTarget();
    //is unchanged
    switch(childNode.getNodeType()) {
        // fall-through is intended
        case Node.TEXT_NODE:
        case Node.CDATA_SECTION_NODE:
            laidoutText = null;
            break;
        case Node.ELEMENT_NODE:
            {
                Element childElement = (Element) childNode;
                if (isTextChild(childElement)) {
                    addContextToChild(ctx, childElement);
                    laidoutText = null;
                }
                break;
            }
    }
    if (laidoutText == null) {
        computeLaidoutText(ctx, e, getTextNode());
    }
}

39. AbstractAttr#getNodeValue()

Project: batik
Source File: AbstractAttr.java
View license
/**
     * <b>DOM</b>: Implements [email protected] org.w3c.dom.Node#getNodeValue()}.
     * @return The content of the attribute.
     */
public String getNodeValue() throws DOMException {
    Node first = getFirstChild();
    if (first == null) {
        return "";
    }
    Node n = first.getNextSibling();
    if (n == null) {
        return first.getNodeValue();
    }
    StringBuffer result = new StringBuffer(first.getNodeValue());
    do {
        result.append(n.getNodeValue());
        n = n.getNextSibling();
    } while (n != null);
    return result.toString();
}

40. AbstractText#getPreviousLogicallyAdjacentTextNode()

Project: batik
Source File: AbstractText.java
View license
/**
     * Get the previous <a href="http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/glossary.html#dt-logically-adjacent-text-nodes">logically
     * adjacent text node</a>.
     */
protected Node getPreviousLogicallyAdjacentTextNode(Node n) {
    Node p = n.getPreviousSibling();
    Node parent = n.getParentNode();
    while (p == null && parent != null && parent.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
        p = parent;
        parent = p.getParentNode();
        p = p.getPreviousSibling();
    }
    while (p != null && p.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
        p = p.getLastChild();
    }
    if (p == null) {
        return null;
    }
    int nt = p.getNodeType();
    if (nt == Node.TEXT_NODE || nt == Node.CDATA_SECTION_NODE) {
        return p;
    }
    return null;
}

41. AbstractText#getNextLogicallyAdjacentTextNode()

Project: batik
Source File: AbstractText.java
View license
/**
     * Get the next <a href="http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/glossary.html#dt-logically-adjacent-text-nodes">logically
     * adjacent text node</a>.
     */
protected Node getNextLogicallyAdjacentTextNode(Node n) {
    Node p = n.getNextSibling();
    Node parent = n.getParentNode();
    while (p == null && parent != null && parent.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
        p = parent;
        parent = p.getParentNode();
        p = p.getNextSibling();
    }
    while (p != null && p.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
        p = p.getFirstChild();
    }
    if (p == null) {
        return null;
    }
    int nt = p.getNodeType();
    if (nt == Node.TEXT_NODE || nt == Node.CDATA_SECTION_NODE) {
        return p;
    }
    return null;
}

42. AbstractText#getWholeText()

Project: batik
Source File: AbstractText.java
View license
/**
     * <b>DOM</b>: Implements [email protected] org.w3c.dom.Text#getWholeText()}.
     */
public String getWholeText() {
    StringBuffer sb = new StringBuffer();
    for (Node n = this; n != null; n = getPreviousLogicallyAdjacentTextNode(n)) {
        sb.insert(0, n.getNodeValue());
    }
    for (Node n = getNextLogicallyAdjacentTextNode(this); n != null; n = getNextLogicallyAdjacentTextNode(n)) {
        sb.append(n.getNodeValue());
    }
    return sb.toString();
}

43. DOMTreeWalker#nextNode()

Project: batik
Source File: DOMTreeWalker.java
View license
/**
     * <b>DOM</b>: Implements [email protected] TreeWalker#nextNode()}.
     */
public Node nextNode() {
    Node result;
    if ((result = firstChild(currentNode)) != null) {
        return currentNode = result;
    }
    if ((result = nextSibling(currentNode, root)) != null) {
        return currentNode = result;
    }
    Node parent = currentNode;
    for (; ; ) {
        parent = parentNode(parent);
        if (parent == null) {
            return null;
        }
        if ((result = nextSibling(parent, root)) != null) {
            return currentNode = result;
        }
    }
}

44. RegisterValuesParser#getAttribute()

Project: binnavi
Source File: RegisterValuesParser.java
View license
/**
   * Returns the value of a node attribute.
   *
   * @param node The node whose attribute string is returned.
   * @param attribute The name of the attribute whose value is returned.
   *
   * @return The value of the given node attribute.
   *
   * @throws MessageParserException If the node attribute does not exist.
   */
private static String getAttribute(final Node node, final String attribute) throws MessageParserException {
    final Node attributeNode = node.getAttributes().getNamedItem(attribute);
    if (attributeNode == null) {
        throw new MessageParserException(String.format("IE01041: Thread node of register values message does not have a '%s' attribute", attribute));
    }
    return attributeNode.getNodeValue();
}

45. BMPMetadata#getAttribute()

Project: bioformats
Source File: BMPMetadata.java
View license
// Get a String-valued attribute
private String getAttribute(Node node, String name, String defaultValue, boolean required) throws IIOInvalidTreeException {
    Node attr = node.getAttributes().getNamedItem(name);
    if (attr == null) {
        if (!required) {
            return defaultValue;
        } else {
            fatal(node, "Required attribute " + name + " not present!");
        }
    }
    return attr.getNodeValue();
}

46. GIFMetadata#getAttribute()

Project: bioformats
Source File: GIFMetadata.java
View license
// Get a String-valued attribute
protected static String getAttribute(Node node, String name, String defaultValue, boolean required) throws IIOInvalidTreeException {
    Node attr = node.getAttributes().getNamedItem(name);
    if (attr == null) {
        if (!required) {
            return defaultValue;
        } else {
            fatal(node, "Required attribute " + name + " not present!");
        }
    }
    return attr.getNodeValue();
}

47. Http#nextNode()

Project: BotLibre
Source File: Http.java
View license
/**
	 * Return the next sibling or parent sibling node.
	 * Only walk up to root at most.
	 */
public Node nextNode(Node node, Node root) {
    if (node == null) {
        return null;
    }
    // Need to walk back up to parent if no more siblings.
    Node nextNode = node.getNextSibling();
    Node parent = node.getParentNode();
    while ((nextNode == null) && (parent != null)) {
        if (parent == root) {
            return null;
        }
        nextNode = parent.getNextSibling();
        parent = parent.getParentNode();
    }
    return nextNode;
}

48. NodeReplaceInsert#merge()

View license
@Override
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }
    Node[] primaryNodes = new Node[nodeList1.size()];
    for (int j = 0; j < primaryNodes.length; j++) {
        primaryNodes[j] = nodeList1.get(j);
    }
    ArrayList<Node> list = new ArrayList<Node>();
    for (int j = 0; j < nodeList2.size(); j++) {
        list.add(nodeList2.get(j));
    }
    List<Node> usedNodes = matchNodes(exhaustedNodes, primaryNodes, list);
    Node[] response = {};
    response = usedNodes.toArray(response);
    return response;
}

49. NodeReplaceInsert#merge()

View license
public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) {
    if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) {
        return null;
    }
    Node[] primaryNodes = new Node[nodeList1.size()];
    for (int j = 0; j < primaryNodes.length; j++) {
        primaryNodes[j] = nodeList1.get(j);
    }
    ArrayList<Node> list = new ArrayList<Node>();
    for (int j = 0; j < nodeList2.size(); j++) {
        list.add(nodeList2.get(j));
    }
    List<Node> usedNodes = matchNodes(exhaustedNodes, primaryNodes, list);
    Node[] response = {};
    response = usedNodes.toArray(response);
    return response;
}

50. ManifestMerger#selectPreviousSiblings()

Project: buck
Source File: ManifestMerger.java
View license
// -----
/**
   * Given an element E, select which previous siblings we want to merge.
   * We want to include any whitespace up to the closing of the previous element.
   * We also want to include up preceding comment nodes and their preceding whitespace.
   * <p/>
   * This may returns either [email protected] end} or a previous sibling. Never returns null.
   */
@NonNull
private Node selectPreviousSiblings(Node end) {
    Node start = end;
    Node prev = start.getPreviousSibling();
    while (prev != null) {
        short t = prev.getNodeType();
        if (t == Node.TEXT_NODE) {
            String text = prev.getNodeValue();
            if (text == null || text.trim().length() != 0) {
                // Not whitespace, we don't want it.
                break;
            }
        } else if (t == Node.COMMENT_NODE) {
        // It's a comment. We'll take it.
        } else {
            // Not a comment node nor a whitespace text. We don't want it.
            break;
        }
        start = prev;
        prev = start.getPreviousSibling();
    }
    return start;
}

51. AbstractElementStack#stripIgnorableText()

Project: caja
Source File: AbstractElementStack.java
View license
/** Strip ignorable whitespace nodes from the root. */
protected void stripIgnorableText() {
    if (rootElement.getFirstChild() == null) {
        return;
    }
    // No need to loop because processText normalizes.
    Node firstChild = rootElement.getFirstChild();
    if (isIgnorableTextNode(firstChild)) {
        rootElement.removeChild(firstChild);
        if (rootElement.getFirstChild() == null) {
            return;
        }
    }
    // No need to loop because processText normalizes.
    Node lastChild = rootElement.getLastChild();
    if (isIgnorableTextNode(lastChild)) {
        rootElement.removeChild(lastChild);
    }
}

52. Element#insertAfter()

Project: che
Source File: Element.java
View license
/**
     * Inserts new element after current
     *
     * @param newElement
     *         element which will be inserted after current
     * @return this element instance
     * @throws XMLTreeException
     *         when this element has been removed from xml tree
     *         or this element is root element
     * @throws NullPointerException
     *         when newElement parameter is [email protected] null}
     */
public Element insertAfter(NewElement newElement) {
    checkNotRemoved();
    notPermittedOnRootElement();
    requireNonNull(newElement, "Required not null new element");
    final Node newNode = createNode(newElement);
    final Element element = createElement(newNode);
    //if element has next sibling append child to parent
    //else insert before next sibling
    final Node nextNode = nextElementNode(delegate);
    if (nextNode != null) {
        delegate.getParentNode().insertBefore(newNode, nextNode);
    } else {
        delegate.getParentNode().appendChild(newNode);
    }
    //let tree do dirty job
    xmlTree.insertAfter(newElement, element, this);
    return this;
}

53. XmpReader#add()

Project: clj-pdf
Source File: XmpReader.java
View license
/**
	 * Adds a tag.
	 * @param	namespaceURI	the URI of the namespace
	 * @param	parent			the tag name of the parent
	 * @param	localName		the name of the tag to add
	 * @param	value			the new content for the tag
	 * @return	true if the content was successfully added
	 * @since	2.1.6
	 */
public boolean add(String parent, String namespaceURI, String localName, String value) {
    NodeList nodes = domDocument.getElementsByTagName(parent);
    if (nodes.getLength() == 0)
        return false;
    Node pNode;
    Node node;
    for (int i = 0; i < nodes.getLength(); i++) {
        pNode = nodes.item(i);
        NamedNodeMap attrs = pNode.getAttributes();
        for (int j = 0; j < attrs.getLength(); j++) {
            node = attrs.item(j);
            if (namespaceURI.equals(node.getNodeValue())) {
                node = domDocument.createElement(localName);
                node.appendChild(domDocument.createTextNode(value));
                pNode.appendChild(node);
                return true;
            }
        }
    }
    return false;
}

54. Invoker#toDOMNodeList()

Project: cocoon
Source File: Invoker.java
View license
public static NodeList toDOMNodeList(String elementName, Instruction si, ExpressionContext expressionContext, ExecutionContext executionContext, MacroContext macroContext) throws SAXException {
    DOMBuilder builder = new DOMBuilder();
    builder.startDocument();
    builder.startElement(JXTemplateGenerator.NS, elementName, elementName, EMPTY_ATTRS);
    execute(builder, expressionContext, executionContext, macroContext, si.getNext(), si.getEndInstruction());
    builder.endElement(JXTemplateGenerator.NS, elementName, elementName);
    builder.endDocument();
    Node node = builder.getDocument().getDocumentElement();
    return node.getChildNodes();
}

55. AnimationImpl#getPixelOffsets()

Project: CodenameOne
Source File: AnimationImpl.java
View license
public static Point getPixelOffsets(ImageReader reader, int num) throws IOException {
    IIOMetadata meta = reader.getImageMetadata(num);
    Point point = new Point(-1, -1);
    Node root = meta.getAsTree("javax_imageio_1.0");
    //printNodeTree(root);
    for (Node c = root.getFirstChild(); c != null; c = c.getNextSibling()) {
        String name = c.getNodeName();
        if ("Dimension".equals(name)) {
            for (c = c.getFirstChild(); c != null; c = c.getNextSibling()) {
                name = c.getNodeName();
                if ("HorizontalPixelOffset".equals(name))
                    point.x = getValueAttribute(c);
                else if ("VerticalPixelOffset".equals(name))
                    point.y = getValueAttribute(c);
            }
            return point;
        }
    }
    return point;
}

56. IteratorUtilsTest#testNodeListIterator()

View license
/**
     * Tests method nodeListIterator(NodeList)
     */
@Test
public void testNodeListIterator() {
    final Node[] nodes = createNodes();
    final NodeList nodeList = createNodeList(nodes);
    final Iterator<Node> iterator = IteratorUtils.nodeListIterator(nodeList);
    int expectedNodeIndex = 0;
    for (final Node actual : IteratorUtils.asIterable(iterator)) {
        assertEquals(nodes[expectedNodeIndex], actual);
        ++expectedNodeIndex;
    }
    // insure iteration occurred
    assertTrue(expectedNodeIndex > 0);
    // single use iterator
    assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext());
}

57. MbeansSource#processArg()

Project: commons-modeler
Source File: MbeansSource.java
View license
private ArgsInfo processArg(Node mbeanN) {
    Node firstArgN = DomUtil.getChild(mbeanN, "arg");
    if (firstArgN == null) {
        return null;
    }
    ArgsInfo info = new ArgsInfo();
    // process all args
    for (Node argN = firstArgN; argN != null; argN = DomUtil.getNext(argN)) {
        String type = DomUtil.getAttribute(argN, "type");
        String value = DomUtil.getAttribute(argN, "value");
        if (value == null) {
            // The value may be specified as CDATA
            value = DomUtil.getContent(argN);
        }
        info.addArgPair(type, registry.convertValue(type, value));
    }
    return info;
}

58. DomUtil#getChild()

Project: commons-modeler
Source File: DomUtil.java
View license
/** Get the first element child.
     * @param parent lookup direct childs
     * @param name name of the element. If null return the first element.
     */
public static Node getChild(Node parent, String name) {
    if (parent == null)
        return null;
    Node first = parent.getFirstChild();
    if (first == null)
        return null;
    for (Node node = first; node != null; node = node.getNextSibling()) {
        //System.out.println("getNode: " + name + " " + node.getNodeName());
        if (node.getNodeType() != Node.ELEMENT_NODE)
            continue;
        if (name != null && name.equals(node.getNodeName())) {
            return node;
        }
        if (name == null) {
            return node;
        }
    }
    return null;
}

59. DomUtil#getChildContent()

Project: commons-modeler
Source File: DomUtil.java
View license
/** Get the first child's content ( ie it's included TEXT node ).
     */
public static String getChildContent(Node parent, String name) {
    Node first = parent.getFirstChild();
    if (first == null)
        return null;
    for (Node node = first; node != null; node = node.getNextSibling()) {
        //System.out.println("getNode: " + name + " " + node.getNodeName());
        if (name.equals(node.getNodeName())) {
            return getContent(node);
        }
    }
    return null;
}

60. DomUtil#getNext()

Project: commons-modeler
Source File: DomUtil.java
View license
/** Return the next sibling with a given name and type
     */
public static Node getNext(Node current, String name, int type) {
    Node first = current.getNextSibling();
    if (first == null)
        return null;
    for (Node node = first; node != null; node = node.getNextSibling()) {
        if (type >= 0 && node.getNodeType() != type)
            continue;
        //System.out.println("getNode: " + name + " " + node.getNodeName());
        if (name == null)
            return node;
        if (name.equals(node.getNodeName())) {
            return node;
        }
    }
    return null;
}

61. ConfigurationParser#getRequiredAttribute()

Project: esper
Source File: ConfigurationParser.java
View license
private static String getRequiredAttribute(Node node, String key) {
    Node valueNode = node.getAttributes().getNamedItem(key);
    if (valueNode == null) {
        String name = node.getLocalName();
        if (name == null) {
            name = node.getNodeName();
        }
        throw new ConfigurationException("Required attribute by name '" + key + "' not found for element '" + name + "'");
    }
    return valueNode.getTextContent();
}

62. DOMConvertingGetter#get()

Project: esper
Source File: DOMConvertingGetter.java
View license
public Object get(EventBean obj) throws PropertyAccessException {
    // The underlying is expected to be a map
    if (!(obj.getUnderlying() instanceof Node)) {
        throw new PropertyAccessException("Mismatched property getter to event bean type, " + "the underlying data object is not of type Node");
    }
    Node node = (Node) obj.getUnderlying();
    Node result = getter.getValueAsNode(node);
    if (result == null) {
        return null;
    }
    String text = result.getTextContent();
    if (text == null) {
        return null;
    }
    return parser.parse(text);
}

63. TestSchemaXMLEventTranspose#testXPathExpression()

View license
/**
     * For testing XPath expressions.
     *
     */
public void testXPathExpression() throws Exception {
    XPathNamespaceContext ctx = new XPathNamespaceContext();
    ctx.addPrefix("n0", "samples:schemas:simpleSchema");
    Node node = SupportXML.getDocument().getDocumentElement();
    XPath pathOne = XPathFactory.newInstance().newXPath();
    pathOne.setNamespaceContext(ctx);
    XPathExpression pathExprOne = pathOne.compile("/n0:simpleEvent/n0:nested1");
    Node result = (Node) pathExprOne.evaluate(node, XPathConstants.NODE);
    //System.out.println("Result:\n" + SchemaUtil.serialize(result));
    XPath pathTwo = XPathFactory.newInstance().newXPath();
    pathTwo.setNamespaceContext(ctx);
    XPathExpression pathExprTwo = pathTwo.compile("/n0:simpleEvent/n0:nested1/n0:prop1");
    String resultTwo = (String) pathExprTwo.evaluate(result, XPathConstants.STRING);
    //System.out.println("Result 2: <" + resultTwo + ">");
    XPath pathThree = XPathFactory.newInstance().newXPath();
    pathThree.setNamespaceContext(ctx);
    XPathExpression pathExprThree = pathThree.compile("/n0:simpleEvent/n0:nested3");
    String resultThress = (String) pathExprThree.evaluate(result, XPathConstants.STRING);
//System.out.println("Result 3: <" + resultThress + ">");
}

64. CanonicalizerBase#getParentNameSpaces()

Project: gocd
Source File: CanonicalizerBase.java
View license
/**
     * Adds to ns the definitions from the parent elements of el
     * @param el
     * @param ns
     */
protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns) {
    Node n1 = el.getParentNode();
    if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) {
        return;
    }
    //Obtain all the parents of the element
    List<Element> parents = new ArrayList<Element>();
    Node parent = n1;
    while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) {
        parents.add((Element) parent);
        parent = parent.getParentNode();
    }
    //Visit them in reverse order.
    ListIterator<Element> it = parents.listIterator(parents.size());
    while (it.hasPrevious()) {
        Element ele = it.previous();
        handleParent(ele, ns);
    }
    parents.clear();
    Attr nsprefix;
    if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null) && "".equals(nsprefix.getValue())) {
        ns.addMappingAndRender(XMLNS, "", nullNode);
    }
}

65. XmlDtd#newFromInternalSubset()

Project: gocd
Source File: XmlDtd.java
View license
/**
     * Create an unparented element that contains DTD declarations
     * parsed from the internal subset attached as user data to
     * <code>doc</code>.  The attached dtd must be the tree from
     * NekoDTD. The owner document of the returned tree will be
     * <code>doc</doc>.
     *
     * NekoDTD parser returns a new document node containing elements
     * representing the dtd declarations. The plan is to get the root
     * element and adopt it into the correct document, stipping the
     * Document provided by NekoDTD.
     *
     */
public static XmlDtd newFromInternalSubset(Ruby runtime, Document doc) {
    Object dtdTree_ = doc.getUserData(XmlDocument.DTD_RAW_DOCUMENT);
    if (dtdTree_ == null) {
        XmlDtd xmlDtd = (XmlDtd) NokogiriService.XML_DTD_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime, "Nokogiri::XML::DTD"));
        xmlDtd.setNode(runtime, null);
        return xmlDtd;
    }
    Node dtdTree = (Node) dtdTree_;
    Node dtd = getInternalSubset(dtdTree);
    if (dtd == null) {
        XmlDtd xmlDtd = (XmlDtd) NokogiriService.XML_DTD_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime, "Nokogiri::XML::DTD"));
        xmlDtd.setNode(runtime, null);
        return xmlDtd;
    } else {
        // Import the node into doc so it has the correct owner document.
        dtd = doc.importNode(dtd, true);
        XmlDtd xmlDtd = (XmlDtd) NokogiriService.XML_DTD_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime, "Nokogiri::XML::DTD"));
        xmlDtd.setNode(runtime, dtd);
        return xmlDtd;
    }
}

66. XmlDtd#newFromExternalSubset()

Project: gocd
Source File: XmlDtd.java
View license
public static IRubyObject newFromExternalSubset(Ruby runtime, Document doc) {
    Object dtdTree_ = doc.getUserData(XmlDocument.DTD_RAW_DOCUMENT);
    if (dtdTree_ == null) {
        return runtime.getNil();
    }
    Node dtdTree = (Node) dtdTree_;
    Node dtd = getExternalSubset(dtdTree);
    if (dtd == null) {
        return runtime.getNil();
    } else if (!dtd.hasChildNodes()) {
        return runtime.getNil();
    } else {
        // Import the node into doc so it has the correct owner document.
        dtd = doc.importNode(dtd, true);
        XmlDtd xmlDtd = (XmlDtd) NokogiriService.XML_DTD_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime, "Nokogiri::XML::DTD"));
        xmlDtd.setNode(runtime, dtd);
        return xmlDtd;
    }
}

67. XmlNode#next_element()

Project: gocd
Source File: XmlNode.java
View license
@JRubyMethod
public IRubyObject next_element(ThreadContext context) {
    Node nextNode = node.getNextSibling();
    Ruby ruby = context.getRuntime();
    if (nextNode == null)
        return ruby.getNil();
    if (nextNode instanceof Element) {
        return getCachedNodeOrCreate(context.getRuntime(), nextNode);
    }
    Node deeper = nextNode.getNextSibling();
    if (deeper == null)
        return ruby.getNil();
    return getCachedNodeOrCreate(context.getRuntime(), deeper);
}

68. XmlNode#previous_element()

Project: gocd
Source File: XmlNode.java
View license
@JRubyMethod
public IRubyObject previous_element(ThreadContext context) {
    Node prevNode = node.getPreviousSibling();
    Ruby ruby = context.getRuntime();
    if (prevNode == null)
        return ruby.getNil();
    if (prevNode instanceof Element) {
        return getCachedNodeOrCreate(context.getRuntime(), prevNode);
    }
    Node shallower = prevNode.getPreviousSibling();
    if (shallower == null)
        return ruby.getNil();
    return getCachedNodeOrCreate(context.getRuntime(), shallower);
}

69. BuildTargetsSerializer#doReadFromString()

View license
@Override
public ArrayList2<BuildTargetData> doReadFromString(String targetsXml) throws CommonException {
    Document doc = parseDocumentFromXml(targetsXml);
    Node buildTargetsElem = doc.getFirstChild();
    if (buildTargetsElem == null || !buildTargetsElem.getNodeName().equals(BUILD_TARGETS_ElemName)) {
        throw new CommonException("Expected element " + BUILD_TARGETS_ElemName + ".");
    }
    ArrayList2<BuildTargetData> buildTargets = new ArrayList2<>();
    Node targetElem = buildTargetsElem.getFirstChild();
    for (; targetElem != null; targetElem = targetElem.getNextSibling()) {
        if (targetElem.getNodeType() == Node.TEXT_NODE) {
            continue;
        }
        buildTargets.add(readBuildTargetElement(targetElem));
    }
    return buildTargets;
}

70. ParsedDeleteStmt#parse()

Project: h-store
Source File: ParsedDeleteStmt.java
View license
@Override
void parse(Node stmtNode, Database db) {
    NamedNodeMap attrs = stmtNode.getAttributes();
    Node node = attrs.getNamedItem("table");
    assert (node != null);
    String tableName = node.getNodeValue().trim();
    table = db.getTables().getIgnoreCase(tableName);
    tableList.add(table);
    for (Node child = stmtNode.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() != Node.ELEMENT_NODE)
            continue;
        else if (child.getNodeName().equalsIgnoreCase("condition"))
            parseCondition(child, db);
    }
}

71. ParsedInsertStmt#parseInsertColumn()

Project: h-store
Source File: ParsedInsertStmt.java
View license
void parseInsertColumn(Node columnNode, Database db, Table table) {
    NamedNodeMap attrs = columnNode.getAttributes();
    Node tableNameAttr = attrs.getNamedItem("table");
    Node columnNameAttr = attrs.getNamedItem("name");
    String tableName = tableNameAttr.getNodeValue();
    String columnName = columnNameAttr.getNodeValue();
    assert (tableName.equalsIgnoreCase(table.getTypeName()));
    Column column = table.getColumns().getIgnoreCase(columnName);
    AbstractExpression expr = null;
    NodeList children = columnNode.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            expr = parseExpressionTree(node, db);
            ExpressionUtil.assignLiteralConstantTypesRecursively(expr, VoltType.get((byte) column.getType()));
            ExpressionUtil.assignOutputValueTypesRecursively(expr);
        }
    }
    columns.put(column, expr);
}

72. ParsedUpdateStmt#parse()

Project: h-store
Source File: ParsedUpdateStmt.java
View license
@Override
void parse(Node stmtNode, Database db) {
    NamedNodeMap attrs = stmtNode.getAttributes();
    Node node = attrs.getNamedItem("table");
    assert (node != null);
    String tableName = node.getNodeValue().trim();
    table = db.getTables().getIgnoreCase(tableName);
    tableList.add(table);
    for (Node child = stmtNode.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() != Node.ELEMENT_NODE)
            continue;
        if (child.getNodeName().equalsIgnoreCase("columns"))
            parseColumns(child, db);
        else if (child.getNodeName().equalsIgnoreCase("condition"))
            parseCondition(child, db);
    }
}

73. GeneNetworkTest#tstOutputNetwork()

Project: igv
Source File: GeneNetworkTest.java
View license
public void tstOutputNetwork(GeneNetwork network, String outPath) throws Exception {
    Set<Node> nodes = network.vertexSet();
    Set<String> nodeNames = new HashSet<String>();
    for (Node node : nodes) {
        nodeNames.add(GeneNetwork.getNodeKeyData(node, "label"));
    }
    assertTrue(network.exportGraph(outPath) > 0);
    GeneNetwork at = new GeneNetwork();
    assertTrue(at.loadNetwork(outPath) > 0);
    //Check that node set matches
    Set<Node> outNodes = at.vertexSet();
    assertEquals("Output has a different number of nodes than input", nodes.size(), outNodes.size());
    for (Node oNode : outNodes) {
        String nodeName = GeneNetwork.getNodeKeyData(oNode, "label");
        assertTrue(nodeNames.contains(nodeName));
    }
}

74. StdMutableRequestAttributes#getContentNodeByXpathExpression()

View license
@Override
public Node getContentNodeByXpathExpression(XPathExpression xpathExpression) {
    if (xpathExpression == null) {
        throw new NullPointerException("Null XPathExpression");
    }
    Node nodeRootThis = this.getContentRoot();
    if (nodeRootThis == null) {
        return null;
    }
    Node matchingNode = null;
    try {
        matchingNode = (Node) xpathExpression.evaluate(nodeRootThis, XPathConstants.NODE);
    } catch (XPathExpressionException ex) {
        this.logger.warn("Failed to retrieve node for \"" + xpathExpression.toString() + "\"", ex);
    }
    return matchingNode;
}

75. StdRequestAttributes#getContentNodeByXpathExpression()

View license
@Override
public Node getContentNodeByXpathExpression(XPathExpression xpathExpression) {
    if (xpathExpression == null) {
        throw new NullPointerException("Null XPathExpression");
    }
    Node nodeRootThis = this.getContentRoot();
    if (nodeRootThis == null) {
        return null;
    }
    Node matchingNode = null;
    try {
        matchingNode = (Node) xpathExpression.evaluate(nodeRootThis, XPathConstants.NODE);
    } catch (XPathExpressionException ex) {
        this.logger.warn("Failed to retrieve node for \"" + xpathExpression.toString() + "\"", ex);
    }
    return matchingNode;
}

76. ObjUtil#xmlEqualsAllowNull()

Project: incubator-openaz
Source File: ObjUtil.java
View license
/**
     * Determines if two XML Nodes are equivalent, including the case where both are <code>null</code>. For
     * XML Nodes the .equals() method does not work (the objects must actually be the same Node). In this
     * project we want to allow XML with different textual layout (newlines and spaces) to be equal because
     * the text formatting is not significant to the meaning of the content. Therefore the
     * (Node).isEqualNode() method is not appropriate either. This method looks at the Node elements and each
     * of their children: - ignoring empty text nodes - ignoring comment nodes - checking that all attributes
     * on the nodes are the same - checking that each non-empty-text child is in the same order
     *
     * @param node1 the first Node object to compare
     * @param node2 the second Node object to compare
     * @return true if both objects are null, or the first is non-null and <code>equals</code> the second as
     *         described in the method description.
     */
public static boolean xmlEqualsAllowNull(Node node1, Node node2) {
    if (node1 == null) {
        return node2 == null;
    } else if (node2 == null) {
        return false;
    }
    // create deep copies of the nodes so we can manipulate them before testing
    Node clone1 = node1.cloneNode(true);
    cleanXMLNode(clone1);
    Node clone2 = node2.cloneNode(true);
    cleanXMLNode(clone2);
    boolean compareReturn = compareXML(clone1, clone2);
    return compareReturn;
}

77. CDATASectionImpl#split()

Project: j2objc
Source File: CDATASectionImpl.java
View license
/**
     * Splits this CDATA node into parts that do not contain a "]]>" sequence.
     * Any newly created nodes will be inserted before this node.
     */
public void split() {
    if (!needsSplitting()) {
        return;
    }
    Node parent = getParentNode();
    String[] parts = getData().split("\\]\\]>");
    parent.insertBefore(new CDATASectionImpl(document, parts[0] + "]]"), this);
    for (int p = 1; p < parts.length - 1; p++) {
        parent.insertBefore(new CDATASectionImpl(document, ">" + parts[p] + "]]"), this);
    }
    setData(">" + parts[parts.length - 1]);
}

78. InnerNodeImpl#normalize()

Project: j2objc
Source File: InnerNodeImpl.java
View license
/**
     * Normalize the text nodes within this subtree. Although named similarly,
     * this method is unrelated to Document.normalize.
     */
@Override
public final void normalize() {
    Node next;
    for (Node node = getFirstChild(); node != null; node = next) {
        next = node.getNextSibling();
        node.normalize();
        if (node.getNodeType() == Node.TEXT_NODE) {
            ((TextImpl) node).minimize();
        }
    }
}

79. InnerNodeImpl#getTextContent()

Project: j2objc
Source File: InnerNodeImpl.java
View license
public String getTextContent() throws DOMException {
    Node child = getFirstChild();
    if (child == null) {
        return "";
    }
    Node next = child.getNextSibling();
    if (next == null) {
        return hasTextContent(child) ? child.getTextContent() : "";
    }
    StringBuilder buf = new StringBuilder();
    getTextContent(buf);
    return buf.toString();
}

80. GIFMetadata#getAttribute()

Project: jdk7u-jdk
Source File: GIFMetadata.java
View license
// Get a String-valued attribute
protected static String getAttribute(Node node, String name, String defaultValue, boolean required) throws IIOInvalidTreeException {
    Node attr = node.getAttributes().getNamedItem(name);
    if (attr == null) {
        if (!required) {
            return defaultValue;
        } else {
            fatal(node, "Required attribute " + name + " not present!");
        }
    }
    return attr.getNodeValue();
}

81. PNGMetadata#getStringAttribute()

Project: jdk7u-jdk
Source File: PNGMetadata.java
View license
// Get an integer-valued attribute
private String getStringAttribute(Node node, String name, String defaultValue, boolean required) throws IIOInvalidTreeException {
    Node attr = node.getAttributes().getNamedItem(name);
    if (attr == null) {
        if (!required) {
            return defaultValue;
        } else {
            fatal(node, "Required attribute " + name + " not present!");
        }
    }
    return attr.getNodeValue();
}

82. PNGMetadata#getAttribute()

Project: jdk7u-jdk
Source File: PNGMetadata.java
View license
// Get a String-valued attribute
private String getAttribute(Node node, String name, String defaultValue, boolean required) throws IIOInvalidTreeException {
    Node attr = node.getAttributes().getNamedItem(name);
    if (attr == null) {
        if (!required) {
            return defaultValue;
        } else {
            fatal(node, "Required attribute " + name + " not present!");
        }
    }
    return attr.getNodeValue();
}

83. XMLCipher#encryptElement()

Project: jdk7u-jdk
Source File: XMLCipher.java
View license
/**
     * Encrypts an <code>Element</code> and replaces it with its encrypted
     * counterpart in the context <code>Document</code>, that is, the
     * <code>Document</code> specified when one calls
     * [email protected] #getInstance(String) getInstance}.
     *
     * @param element the <code>Element</code> to encrypt.
     * @return the context <code>Document</code> with the encrypted
     *   <code>Element</code> having replaced the source <code>Element</code>.
     *  @throws Exception
     */
private Document encryptElement(Element element) throws Exception {
    logger.log(java.util.logging.Level.FINE, "Encrypting element...");
    if (null == element)
        logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    if (_cipherMode != ENCRYPT_MODE)
        logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    if (_algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(_contextDocument, element, false);
    Element encryptedElement = _factory.toElement(_ed);
    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);
    return (_contextDocument);
}

84. DOMUtils#paramsEqual()

Project: jdk7u-jdk
Source File: DOMUtils.java
View license
private static boolean paramsEqual(XSLTTransformParameterSpec spec1, XSLTTransformParameterSpec spec2) {
    XMLStructure ostylesheet = spec2.getStylesheet();
    if (!(ostylesheet instanceof javax.xml.crypto.dom.DOMStructure)) {
        return false;
    }
    Node ostylesheetElem = ((javax.xml.crypto.dom.DOMStructure) ostylesheet).getNode();
    XMLStructure stylesheet = spec1.getStylesheet();
    Node stylesheetElem = ((javax.xml.crypto.dom.DOMStructure) stylesheet).getNode();
    return nodesEqual(stylesheetElem, ostylesheetElem);
}

85. ShortHistogramTest#upgradeMetadata()

Project: jdk7u-jdk
Source File: ShortHistogramTest.java
View license
private IIOMetadata upgradeMetadata(IIOMetadata src, BufferedImage bi) {
    String format = src.getNativeMetadataFormatName();
    System.out.println("Native format: " + format);
    Node root = src.getAsTree(format);
    // add hIST node
    Node n = lookupChildNode(root, "hIST");
    if (n == null) {
        System.out.println("Appending new hIST node...");
        Node hIST = gethISTNode(bi);
        root.appendChild(hIST);
    }
    System.out.println("Upgraded metadata tree:");
    dump(root, "");
    System.out.println("Merging metadata...");
    try {
        src.mergeTree(format, root);
    } catch (IIOInvalidTreeException e) {
        throw new RuntimeException("Test FAILED!", e);
    }
    return src;
}

86. IOUtil#modifyDocElementAttribute()

Project: keycloak
Source File: IOUtil.java
View license
public static void modifyDocElementAttribute(Document doc, String tagName, String attributeName, String regex, String replacement) {
    NodeList nodes = doc.getElementsByTagName(tagName);
    if (nodes.getLength() != 1) {
        System.out.println("Not able to find element: " + tagName);
        return;
    }
    Node node = nodes.item(0).getAttributes().getNamedItem(attributeName);
    if (node == null) {
        System.out.println("Not able to find attribute " + attributeName + " within element: " + tagName);
        return;
    }
    node.setTextContent(node.getTextContent().replace(regex, replacement));
}

87. XPSAssembler#assemble()

Project: lenya
Source File: XPSAssembler.java
View license
/**
     * DOCUMENT ME!
     *
     * @param reference DOCUMENT ME!
     * @param cocoon DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
public Document assemble(String reference, String cocoon) {
    File workingDirectory = new File(System.getProperty("user.dir"));
    XPSSourceInformation sourceInfo = new XPSSourceInformation("file:" + workingDirectory + "/dummy.xml", cocoon);
    String[] args = new String[1];
    args[0] = reference;
    XPSSourceInformation currentInfo = new XPSSourceInformation(args[0], sourceInfo, cocoon);
    deleteFromCache(currentInfo.url);
    Vector nodes = include(args, sourceInfo);
    log.debug(sourceInfo);
    Node node = (Node) nodes.elementAt(0);
    return node.getOwnerDocument();
}

88. ASSIGN#replaceElement()

Project: ode
Source File: ASSIGN.java
View license
private Element replaceElement(Element lval, Element ptr, Element src, boolean keepSrcElement) {
    Document doc = ptr.getOwnerDocument();
    Node parent = ptr.getParentNode();
    if (keepSrcElement) {
        Element replacement = (Element) doc.importNode(src, true);
        parent.replaceChild(replacement, ptr);
        return (lval == ptr) ? replacement : lval;
    }
    Element replacement = doc.createElementNS(ptr.getNamespaceURI(), ptr.getTagName());
    NodeList nl = src.getChildNodes();
    for (int i = 0; i < nl.getLength(); ++i) replacement.appendChild(doc.importNode(nl.item(i), true));
    copyAttributes(doc, ptr, replacement);
    copyAttributes(doc, src, replacement);
    parent.replaceChild(replacement, ptr);
    DOMUtils.copyNSContext(ptr, replacement);
    return (lval == ptr) ? replacement : lval;
}

89. ParentNode#isEqualNode()

Project: openjdk
Source File: ParentNode.java
View license
/**
     * DOM Level 3 WD- Experimental.
     * Override inherited behavior from NodeImpl to support deep equal.
     */
public boolean isEqualNode(Node arg) {
    if (!super.isEqualNode(arg)) {
        return false;
    }
    // there are many ways to do this test, and there isn't any way
    // better than another. Performance may vary greatly depending on
    // the implementations involved. This one should work fine for us.
    Node child1 = getFirstChild();
    Node child2 = arg.getFirstChild();
    while (child1 != null && child2 != null) {
        if (!((NodeImpl) child1).isEqualNode(child2)) {
            return false;
        }
        child1 = child1.getNextSibling();
        child2 = child2.getNextSibling();
    }
    if (child1 != child2) {
        return false;
    }
    return true;
}

90. RangeImpl#hasLegalRootContainer()

Project: openjdk
Source File: RangeImpl.java
View license
/**
         * Finds the root container for the given node and determines
         * if that root container is legal with respect to the
         * DOM 2 specification.  At present, that means the root
         * container must be either an attribute, a document,
         * or a document fragment.
         */
private boolean hasLegalRootContainer(Node node) {
    if (node == null)
        return false;
    Node rootContainer = getRootContainer(node);
    switch(rootContainer.getNodeType()) {
        case Node.ATTRIBUTE_NODE:
        case Node.DOCUMENT_NODE:
        case Node.DOCUMENT_FRAGMENT_NODE:
            return true;
    }
    return false;
}

91. TextTest#testSplitText()

Project: openjdk
Source File: TextTest.java
View license
/*
     * Verify splitText method works as the spec.
     */
@Test
public void testSplitText() throws Exception {
    Document document = createDOMWithNS("Text01.xml");
    NodeList nodeList = document.getElementsByTagName("p");
    Node node = nodeList.item(0);
    Text textNode = document.createTextNode("This is a text node");
    node.appendChild(textNode);
    int rawChildNum = node.getChildNodes().getLength();
    textNode.splitText(0);
    int increased = node.getChildNodes().getLength() - rawChildNum;
    assertEquals(increased, 1);
}

92. Bug5072946#test1()

Project: openjdk
Source File: Bug5072946.java
View license
@Test
public void test1() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml"));
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema s = sf.newSchema(Bug5072946.class.getResource("Bug5072946.xsd"));
    Validator v = s.newValidator();
    DOMResult r = new DOMResult();
    // r.setNode(dbf.newDocumentBuilder().newDocument());
    v.validate(new DOMSource(dom), r);
    Node node = r.getNode();
    Assert.assertNotNull(node);
    Node fc = node.getFirstChild();
    Assert.assertTrue(fc instanceof Element);
    Element e = (Element) fc;
    Assert.assertEquals("value", e.getAttribute("foo"));
}

93. SAX2DOMEx#characters()

Project: openjdk
Source File: SAX2DOMEx.java
View license
protected Text characters(String s) {
    Node parent = nodeStack.peek();
    Node lastChild = parent.getLastChild();
    Text text;
    if (isConsolidate && lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) {
        text = (Text) lastChild;
        text.appendData(s);
    } else {
        text = document.createTextNode(s);
        parent.appendChild(text);
    }
    return text;
}

94. GIFMetadata#getAttribute()

Project: openjdk
Source File: GIFMetadata.java
View license
// Get a String-valued attribute
protected static String getAttribute(Node node, String name, String defaultValue, boolean required) throws IIOInvalidTreeException {
    Node attr = node.getAttributes().getNamedItem(name);
    if (attr == null) {
        if (!required) {
            return defaultValue;
        } else {
            fatal(node, "Required attribute " + name + " not present!");
        }
    }
    return attr.getNodeValue();
}

95. PNGMetadata#getStringAttribute()

Project: openjdk
Source File: PNGMetadata.java
View license
// Get an integer-valued attribute
private String getStringAttribute(Node node, String name, String defaultValue, boolean required) throws IIOInvalidTreeException {
    Node attr = node.getAttributes().getNamedItem(name);
    if (attr == null) {
        if (!required) {
            return defaultValue;
        } else {
            fatal(node, "Required attribute " + name + " not present!");
        }
    }
    return attr.getNodeValue();
}

96. PNGMetadata#getAttribute()

Project: openjdk
Source File: PNGMetadata.java
View license
// Get a String-valued attribute
private String getAttribute(Node node, String name, String defaultValue, boolean required) throws IIOInvalidTreeException {
    Node attr = node.getAttributes().getNamedItem(name);
    if (attr == null) {
        if (!required) {
            return defaultValue;
        } else {
            fatal(node, "Required attribute " + name + " not present!");
        }
    }
    return attr.getNodeValue();
}

97. XMLCipher#encryptElement()

Project: openjdk
Source File: XMLCipher.java
View license
/**
     * Encrypts an <code>Element</code> and replaces it with its encrypted
     * counterpart in the context <code>Document</code>, that is, the
     * <code>Document</code> specified when one calls
     * [email protected] #getInstance(String) getInstance}.
     *
     * @param element the <code>Element</code> to encrypt.
     * @return the context <code>Document</code> with the encrypted
     *   <code>Element</code> having replaced the source <code>Element</code>.
     *  @throws Exception
     */
private Document encryptElement(Element element) throws Exception {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting element...");
    }
    if (null == element) {
        log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }
    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);
    Element encryptedElement = factory.toElement(ed);
    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);
    return contextDocument;
}

98. DOMUtils#paramsEqual()

Project: openjdk
Source File: DOMUtils.java
View license
private static boolean paramsEqual(XSLTTransformParameterSpec spec1, XSLTTransformParameterSpec spec2) {
    XMLStructure ostylesheet = spec2.getStylesheet();
    if (!(ostylesheet instanceof javax.xml.crypto.dom.DOMStructure)) {
        return false;
    }
    Node ostylesheetElem = ((javax.xml.crypto.dom.DOMStructure) ostylesheet).getNode();
    XMLStructure stylesheet = spec1.getStylesheet();
    Node stylesheetElem = ((javax.xml.crypto.dom.DOMStructure) stylesheet).getNode();
    return nodesEqual(stylesheetElem, ostylesheetElem);
}

99. ShortHistogramTest#upgradeMetadata()

Project: openjdk
Source File: ShortHistogramTest.java
View license
private IIOMetadata upgradeMetadata(IIOMetadata src, BufferedImage bi) {
    String format = src.getNativeMetadataFormatName();
    System.out.println("Native format: " + format);
    Node root = src.getAsTree(format);
    // add hIST node
    Node n = lookupChildNode(root, "hIST");
    if (n == null) {
        System.out.println("Appending new hIST node...");
        Node hIST = gethISTNode(bi);
        root.appendChild(hIST);
    }
    System.out.println("Upgraded metadata tree:");
    dump(root, "");
    System.out.println("Merging metadata...");
    try {
        src.mergeTree(format, root);
    } catch (IIOInvalidTreeException e) {
        throw new RuntimeException("Test FAILED!", e);
    }
    return src;
}

100. XmlNode#insertChildAt()

Project: pad
Source File: XmlNode.java
View license
void insertChildAt(int index, XmlNode node) {
    Node parent = this.dom;
    Node child = parent.getOwnerDocument().importNode(node.dom, true);
    if (parent.getChildNodes().getLength() < index) {
        //    TODO    Check ECMA for what happens here
        throw new IllegalArgumentException("index=" + index + " length=" + parent.getChildNodes().getLength());
    }
    if (parent.getChildNodes().getLength() == index) {
        parent.appendChild(child);
    } else {
        parent.insertBefore(child, parent.getChildNodes().item(index));
    }
}