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
File: ContentHosting.java
/*
	 *  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. BinderImpl#updateXML()

Project: openjdk
File: BinderImpl.java
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;
}

3. YamahaReceiverProxy#getState()

Project: openhab
File: YamahaReceiverProxy.java
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);
}

4. NodeValueMerge#merge()

Project: broadleaf_modify
File: NodeValueMerge.java
@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()

Project: BroadleafCommerce
File: NodeValueMerge.java
@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. XmlTest#testDOMParse()

Project: pgjdbc
File: XmlTest.java
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) {
    }
}

7. SignatureFakingOracle#appendCertificate()

Project: WS-Attacker
File: SignatureFakingOracle.java
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");
}

8. NodeTest#testCloneNode()

Project: openjdk
File: NodeTest.java
/*
     * 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);
}

9. NamedNodeMapTest#testSetNamedItem()

Project: openjdk
File: NamedNodeMapTest.java
/*
     * 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(), "");
}

10. RemoveUnsupportedMarkupNotePreProcessor#processUnsupportedDomNode()

Project: communote-server
File: RemoveUnsupportedMarkupNotePreProcessor.java
/**
     * 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);
}

11. IteratorUtilsTest#createNodes()

Project: commons-collections
File: IteratorUtilsTest.java
/**
     * 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 };
}

12. NodeListIteratorTest#setUp()

Project: commons-collections
File: NodeListIteratorTest.java
@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);
}

13. WindowsAzureCertificate#delete()

Project: azure-tools-for-java
File: WindowsAzureCertificate.java
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);
}

14. SchemaLocationMergeTest#testAddedAttributes()

Project: broadleaf_modify
File: SchemaLocationMergeTest.java
@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());
}

15. SchemaLocationMergeTest#testNodeAttributes()

Project: broadleaf_modify
File: SchemaLocationMergeTest.java
@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());
}

16. SchemaLocationMergeTest#testAddedAttributes()

Project: BroadleafCommerce
File: SchemaLocationMergeTest.java
@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());
}

17. SchemaLocationMergeTest#testNodeAttributes()

Project: BroadleafCommerce
File: SchemaLocationMergeTest.java
@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());
}

18. TiledMapPacker#setProperty()

Project: libgdx
File: TiledMapPacker.java
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);
    }
}

19. W3CDomTest#namespacePreservation()

Project: jsoup
File: W3CDomTest.java
@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());
}

20. RegionMetadataParser#getChildElementValue()

Project: aws-sdk-java
File: RegionMetadataParser.java
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. GeneratorTest#testProducesNamedBeans()

Project: aries
File: GeneratorTest.java
@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]/@ref", "produced2");
}

22. PackageManifestDocumentUtils#addMemberNode()

Project: idecore
File: PackageManifestDocumentUtils.java
/**
     * 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;
}

23. XmlNode#coalesceTextNodes()

Project: gocd
File: XmlNode.java
/**
     * 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);
}

24. XMLUtil#changeTagName()

Project: empire-db
File: XMLUtil.java
/**
     * 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;
}

25. InsertChildrenOf#merge()

Project: broadleaf_modify
File: InsertChildrenOf.java
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;
}

26. InsertChildrenOf#merge()

Project: BroadleafCommerce
File: InsertChildrenOf.java
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;
}

27. DOMTreeWalker#previousNode()

Project: batik
File: DOMTreeWalker.java
/**
     * <b>DOM</b>: Implements {@link 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;
}

28. IteratorUtilsTest#testNodeIterator()

Project: commons-collections
File: IteratorUtilsTest.java
/**
     * 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());
}

29. GeneratorTest#testProducesNamedBeans()

Project: apache-aries
File: GeneratorTest.java
@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]/@ref", myBean5));
}

30. Conf#processRuleBasics()

Project: urlrewritefilter
File: Conf.java
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);
}

31. Assembler#replaceByBody()

Project: sis
File: Assembler.java
/**
     * Copies the body of the given source HTML file in-place of the given target node.
     * This method is doing the work of {@code <xi:include>} element. We do this work ourself instead than relying on
     * {@link DocumentBuilder} build-in support mostly because we have been unable to get the {@code 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;
}

32. PDI_11319Test#getNullIfStep()

Project: pentaho-kettle
File: PDI_11319Test.java
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;
}

33. NodeTest#testImportNode()

Project: openjdk
File: NodeTest.java
/*
     * 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));
}

34. XmlUtils#getAttribute()

Project: APKParser
File: XmlUtils.java
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. XmlNode#insertChildAt()

Project: pad
File: XmlNode.java
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));
    }
}

36. ShortHistogramTest#upgradeMetadata()

Project: openjdk
File: ShortHistogramTest.java
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;
}

37. DOMUtils#paramsEqual()

Project: openjdk
File: DOMUtils.java
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);
}

38. XMLCipher#encryptElement()

Project: openjdk
File: XMLCipher.java
/**
     * 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
     * {@link #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;
}

39. PNGMetadata#getAttribute()

Project: openjdk
File: PNGMetadata.java
// 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();
}

40. PNGMetadata#getStringAttribute()

Project: openjdk
File: PNGMetadata.java
// 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();
}

41. GIFMetadata#getAttribute()

Project: openjdk
File: GIFMetadata.java
// 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();
}

42. PluginInfoTest#testChild()

Project: lucene-solr
File: PluginInfoTest.java
@Test
public void testChild() throws Exception {
    Node node = getNode(configWith2Children, "plugin");
    PluginInfo pi = new PluginInfo(node, "with children", false, false);
    PluginInfo childInfo = pi.getChild("child");
    assertNotNull(childInfo);
    PluginInfo notExistent = pi.getChild("doesnotExist");
    assertNull(notExistent);
    assertTrue(childInfo instanceof PluginInfo);
    assertTrue((Integer) childInfo.initArgs.get("index") == 0);
    Node node2 = getNode(configWithNoChildren, "plugin");
    PluginInfo pi2 = new PluginInfo(node2, "with No Children", false, false);
    PluginInfo noChild = pi2.getChild("long");
    assertNull(noChild);
}

43. PluginInfoTest#testClassRequired()

Project: lucene-solr
File: PluginInfoTest.java
@Test
public void testClassRequired() throws Exception {
    Node nodeWithNoClass = getNode("<plugin></plugin>", "plugin");
    AbstractSolrTestCase.ignoreException("missing mandatory attribute");
    try {
        @SuppressWarnings("unused") PluginInfo pi = new PluginInfo(nodeWithNoClass, "Node with No Class", false, true);
        fail("Exception should have been thrown");
    } catch (RuntimeException e) {
        assertTrue(e.getMessage().contains("missing mandatory attribute"));
    } finally {
        AbstractSolrTestCase.resetExceptionIgnores();
    }
    Node nodeWithAClass = getNode("<plugin class=\"myName\" />", "plugin");
    PluginInfo pi2 = new PluginInfo(nodeWithAClass, "Node with a Class", false, true);
    assertTrue(pi2.className.equals("myName"));
}

44. PluginInfoTest#testNameRequired()

Project: lucene-solr
File: PluginInfoTest.java
// This is in fact a DOMUtil test, but it is here for completeness  
@Test
public void testNameRequired() throws Exception {
    Node nodeWithNoName = getNode("<plugin></plugin>", "plugin");
    AbstractSolrTestCase.ignoreException("missing mandatory attribute");
    try {
        PluginInfo pi = new PluginInfo(nodeWithNoName, "Node with No name", true, false);
        fail("Exception should have been thrown");
    } catch (RuntimeException e) {
        assertTrue(e.getMessage().contains("missing mandatory attribute"));
    } finally {
        AbstractSolrTestCase.resetExceptionIgnores();
    }
    Node nodeWithAName = getNode("<plugin name=\"myName\" />", "plugin");
    PluginInfo pi2 = new PluginInfo(nodeWithAName, "Node with a Name", true, false);
    assertTrue(pi2.name.equals("myName"));
}

45. DOMUtil#substituteProperties()

Project: lucene-solr
File: DOMUtil.java
/**
   * Replaces ${property[:default value]} references in all attributes
   * and text nodes of supplied node.  If the property is not defined neither in the
   * given Properties instance nor in System.getProperty and no
   * default value is provided, a runtime exception is thrown.
   *
   * @param node DOM node to walk for substitutions
   * @param properties the Properties instance from which a value can be looked up
   */
public static void substituteProperties(Node node, Properties properties) {
    // loop through child nodes
    Node child;
    Node next = node.getFirstChild();
    while ((child = next) != null) {
        // set next before we change anything
        next = child.getNextSibling();
        // handle child by node type
        if (child.getNodeType() == Node.TEXT_NODE) {
            child.setNodeValue(PropertiesUtil.substituteProperty(child.getNodeValue(), properties));
        } else if (child.getNodeType() == Node.ELEMENT_NODE) {
            // handle child elements with recursive call
            NamedNodeMap attributes = child.getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                Node attribute = attributes.item(i);
                attribute.setNodeValue(PropertiesUtil.substituteProperty(attribute.getNodeValue(), properties));
            }
            substituteProperties(child, properties);
        }
    }
}

46. TestMessageTransformer#moveReferenceList()

Project: wss4j
File: TestMessageTransformer.java
private static void moveReferenceList(Element saaj) {
    Element sh = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Header"), true);
    Element encKey = getFirstChildElement(sh, new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"), true);
    Element refList = getFirstChildElement(encKey, new QName("http://www.w3.org/2001/04/xmlenc#", "ReferenceList"), true);
    Node wsseHeader = encKey.getParentNode();
    encKey.removeChild(refList);
    wsseHeader.appendChild(refList);
}

47. XMLCipher#encryptElement()

Project: santuario-java
File: XMLCipher.java
/**
     * 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
     * {@link #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.isDebugEnabled()) {
        log.debug("Encrypting element...");
    }
    if (null == element) {
        throw new XMLEncryptionException("empty", "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE) {
        throw new XMLEncryptionException("empty", "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }
    if (algorithm == null) {
        throw new XMLEncryptionException("empty", "XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);
    Element encryptedElement = factory.toElement(ed);
    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);
    return contextDocument;
}

48. CanonicalizerBase#getParentNameSpaces()

Project: santuario-java
File: CanonicalizerBase.java
/**
     * 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 = ns.getMappingWithoutRendered(XMLNS);
    if (nsprefix != null && "".equals(nsprefix.getValue())) {
        ns.addMappingAndRender(XMLNS, "", getNullNode(nsprefix.getOwnerDocument()));
    }
}

49. DOMUtils#paramsEqual()

Project: santuario-java
File: DOMUtils.java
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);
}

50. DOMKeyInfo#internalMarshal()

Project: santuario-java
File: DOMKeyInfo.java
private void internalMarshal(javax.xml.crypto.dom.DOMStructure parent, XMLCryptoContext context) throws MarshalException {
    Node pNode = parent.getNode();
    String dsPrefix = DOMUtils.getSignaturePrefix(context);
    Node nextSibling = null;
    if (context instanceof DOMSignContext) {
        nextSibling = ((DOMSignContext) context).getNextSibling();
    }
    XmlWriterToTree xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), pNode, nextSibling);
    marshalInternal(xwriter, this, dsPrefix, context, true);
}

51. RobolectricConfig#parseReceivers()

Project: robolectric
File: RobolectricConfig.java
private void parseReceivers(final Document manifestDocument) {
    Node application = manifestDocument.getElementsByTagName("application").item(0);
    if (application == null) {
        return;
    }
    for (Node receiverNode : getChildrenTags(application, "receiver")) {
        Node namedItem = receiverNode.getAttributes().getNamedItem("android:name");
        if (namedItem == null) {
            continue;
        }
        String receiverName = namedItem.getTextContent();
        for (Node intentFilterNode : getChildrenTags(receiverNode, "intent-filter")) {
            List<String> actions = new ArrayList<String>();
            for (Node actionNode : getChildrenTags(intentFilterNode, "action")) {
                Node nameNode = actionNode.getAttributes().getNamedItem("android:name");
                if (nameNode != null) {
                    actions.add(nameNode.getTextContent());
                }
            }
            receivers.add(new ReceiverAndIntentFilter(receiverName, actions));
        }
    }
}

52. XMLMultiElementArray#sort()

Project: railo
File: XMLMultiElementArray.java
public void sort(Comparator comp) throws PageException {
    if (size() <= 1)
        return;
    struct.getInnerArray().sort(comp);
    Object[] nodes = struct.getInnerArray().toArray();
    Node last = (Node) nodes[nodes.length - 1], current;
    Node parent = last.getParentNode();
    for (int i = nodes.length - 2; i >= 0; i--) {
        current = (Node) nodes[i];
        parent.insertBefore(current, last);
        last = current;
    }
// MUST testen
}

53. XMLMultiElementArray#sort()

Project: railo
File: XMLMultiElementArray.java
@Override
public void sort(String sortType, String sortOrder) throws PageException {
    if (size() <= 1)
        return;
    struct.getInnerArray().sort(sortType, sortOrder);
    Object[] nodes = struct.getInnerArray().toArray();
    Node last = (Node) nodes[nodes.length - 1], current;
    Node parent = last.getParentNode();
    for (int i = nodes.length - 2; i >= 0; i--) {
        current = (Node) nodes[i];
        parent.insertBefore(current, last);
        last = current;
    }
// MUST testen
}

54. SmilDocumentImpl#getLayout()

Project: qksms
File: SmilDocumentImpl.java
public SMILLayoutElement getLayout() {
    Node headElement = getHead();
    Node layoutElement = null;
    // Find the layout element under <code>HEAD</code>
    layoutElement = headElement.getFirstChild();
    while ((layoutElement != null) && !(layoutElement instanceof SMILLayoutElement)) {
        layoutElement = layoutElement.getNextSibling();
    }
    if (layoutElement == null) {
        // The layout doesn't exist. Create a default one.
        layoutElement = new SmilLayoutElementImpl(this, "layout");
        headElement.appendChild(layoutElement);
    }
    return (SMILLayoutElement) layoutElement;
}

55. PXDOMStyleAdapter#getAttributeValue()

Project: pixate-freestyle-android
File: PXDOMStyleAdapter.java
@Override
public String getAttributeValue(Object styleable, String attributeName, String namespaceURI) {
    Node node = (Node) styleable;
    if (node.hasAttributes()) {
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attr = attributes.item(i);
            if (attr.getLocalName().equals(attributeName)) {
                // now we keep both)
                if (namespaceURI == null) {
                    return attr.getNamespaceURI() == null ? attr.getNodeValue() : null;
                }
                if ("*".equals(namespaceURI) || namespaceURI.equals(attr.getNamespaceURI())) {
                    return attr.getNodeValue();
                }
            }
        }
    }
    return null;
}

56. PXDOMStyleAdapter#getIndexInParent()

Project: pixate-freestyle-android
File: PXDOMStyleAdapter.java
@Override
public int getIndexInParent(Object styleable) {
    Node node = (Node) styleable;
    Node parentNode = node.getParentNode();
    if (parentNode != null) {
        NodeList siblings = parentNode.getChildNodes();
        // find the node's index
        for (int i = 0; i < siblings.getLength(); i++) {
            Node sibling = siblings.item(i);
            if (sibling == node) {
                return i;
            }
        }
    }
    return -1;
}

57. DimensionTableDialog#addAttributesFromFile()

Project: pentaho-kettle
File: DimensionTableDialog.java
private void addAttributesFromFile(String filename) throws KettleException {
    InputStream inputStream = getClass().getResourceAsStream(filename);
    Document document = XMLHandler.loadXMLFile(inputStream);
    Node attributesNode = XMLHandler.getSubNode(document, "attributes");
    List<Node> attributeNodes = XMLHandler.getNodes(attributesNode, "attribute");
    for (Node node : attributeNodes) {
        String name = XMLHandler.getTagValue(node, "name");
        String description = XMLHandler.getTagValue(node, "description");
        String phName = XMLHandler.getTagValue(node, "physicalname");
        AttributeType attributeType = AttributeType.getAttributeType(XMLHandler.getTagValue(node, "attribute_type"));
        DataType dataType = ConceptUtil.getDataType(XMLHandler.getTagValue(node, "data_type"));
        int length = Const.toInt(XMLHandler.getTagValue(node, "length"), -1);
        int precision = Const.toInt(XMLHandler.getTagValue(node, "precision"), -1);
        // String sourceDb = XMLHandler.getTagValue(node, "source_db");
        // String sourceTable = XMLHandler.getTagValue(node, "source_table");
        // String sourceColumn = XMLHandler.getTagValue(node, "source_column");
        String remarks = XMLHandler.getTagValue(node, "remarks");
        addAttribute(name, description, phName, attributeType, dataType, length, precision, remarks);
    }
}

58. SAX2DOMEx#characters()

Project: openjdk
File: SAX2DOMEx.java
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;
}

59. Bug5072946#test1()

Project: openjdk
File: Bug5072946.java
@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"));
}

60. TextTest#testSplitText()

Project: openjdk
File: TextTest.java
/*
     * 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);
}

61. RangeImpl#hasLegalRootContainer()

Project: openjdk
File: RangeImpl.java
/**
         * 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;
}

62. ParentNode#isEqualNode()

Project: openjdk
File: ParentNode.java
/**
     * 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;
}

63. BinarySecurity#getFirstNode()

Project: wss4j
File: BinarySecurity.java
/**
     * return the first text node.
     *
     * @return the first text node.
     */
private Text getFirstNode() {
    Node node = element.getFirstChild();
    while (node != null && Node.TEXT_NODE != node.getNodeType()) {
        node = node.getNextSibling();
    }
    if (node instanceof Text) {
        return (Text) node;
    }
    // Otherwise we have no Text child. Just remove the child nodes + add a new text node
    node = element.getFirstChild();
    while (node != null) {
        Node nextNode = node.getNextSibling();
        element.removeChild(node);
        node = nextNode;
    }
    Node textNode = element.getOwnerDocument().createTextNode("");
    return (Text) element.appendChild(textNode);
}

64. DifferenceListenerIgnoreWhitespace#differenceFound()

Project: wink
File: DifferenceListenerIgnoreWhitespace.java
public int differenceFound(Difference difference) {
    Node controlNode = difference.getControlNodeDetail().getNode();
    Node testNode = difference.getTestNodeDetail().getNode();
    if (controlNode.getNodeType() == Node.TEXT_NODE && testNode.getNodeType() == Node.TEXT_NODE) {
        String controlText = controlNode.getNodeValue().trim();
        String testText = testNode.getNodeValue().trim();
        if (controlText.equals("") && testText.equals("")) {
            return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
        }
    }
    return RETURN_ACCEPT_DIFFERENCE;
}

65. PositionManager#applyToNodes()

Project: uPortal
File: PositionManager.java
/**
       This method applies the ordering specified in the passed in order list
       to the child nodes of the compViewParent. Nodes specified in the list
       but located elsewhere are pulled in.
     */
static void applyToNodes(List<NodeInfo> order, Element compViewParent) {
    // first set up a bogus node to assist with inserting
    Node insertPoint = compViewParent.getOwnerDocument().createElement("bogus");
    Node first = compViewParent.getFirstChild();
    if (first != null)
        compViewParent.insertBefore(insertPoint, first);
    else
        compViewParent.appendChild(insertPoint);
    // now pass through the order list inserting the nodes as you go
    for (int i = 0; i < order.size(); i++) compViewParent.insertBefore(((NodeInfo) order.get(i)).node, insertPoint);
    compViewParent.removeChild(insertPoint);
}

66. FragmentDefinition#loadAttribute()

Project: uPortal
File: FragmentDefinition.java
private String loadAttribute(String name, NamedNodeMap atts, boolean required, Element e) {
    Node att = atts.getNamedItem(name);
    if (required && (att == null || att.getNodeValue().equals("")))
        throw new RuntimeException("Missing or empty attribute '" + name + "' required by <fragment> in\n'" + XmlUtilitiesImpl.toString(e) + "'");
    if (att == null)
        return null;
    return att.getNodeValue();
}

67. MetaDataObjectSerializer_indent#getFirstPrevCoIw()

Project: uima-uimaj
File: MetaDataObjectSerializer_indent.java
/**
   * Scan backwards from argument node, continuing until get something other than
   * comment or ignorable whitespace.
   * Return the first node after a nl 
   *   If no nl found, return original node
   * 
   * NOTE: never called with original == the top node
   * @param r - guaranteed non-null
   * @return first node after a new line
   */
private Node getFirstPrevCoIw(Node original) {
    boolean newlineFound = false;
    // tracks one behind r
    Node p = original;
    for (Node r = p.getPreviousSibling(); isCoIw(r); r = r.getPreviousSibling()) {
        if (hasNewline(r)) {
            newlineFound = true;
        }
        p = r;
    }
    if (!newlineFound) {
        return original;
    }
    return skipUpToFirstAfterNL(p);
}

68. SOAP11Service#examineResponseDOMForFault()

Project: team-explorer-everywhere
File: SOAP11Service.java
/*
     * (non-Javadoc)
     *
     * @seecom.microsoft.tfs.core.ws.runtime.client.SOAPService#
     * examineResponseDOMForFault (org.w3c.dom.Document)
     */
@Override
protected void examineResponseDOMForFault(final Document responseDOM) {
    //$NON-NLS-1$
    Node node = getChildByName(responseDOM, "soap:Envelope");
    //$NON-NLS-1$
    node = getChildByName(node, "soap:Body");
    //$NON-NLS-1$
    final Node faultNode = getChildByName(node, "soap:Fault");
    if (faultNode != null) {
        //$NON-NLS-1$
        final String code = DOMUtils.getText(getChildByName(faultNode, "faultcode"));
        //$NON-NLS-1$
        final String message = DOMUtils.getText(getChildByName(faultNode, "faultstring"));
        throw new SOAPFault(message, (code != null) ? new QName(code) : null, null, null, null, null, null);
    }
}

69. TestStepUtil#extractParamData()

Project: team-explorer-everywhere
File: TestStepUtil.java
public static ParamDataTable[] extractParamData(final String xml) {
    Node n;
    try {
        n = parse(xml).getDocumentElement();
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
        return new ParamDataTable[0];
    } catch (final SAXException e) {
        e.printStackTrace();
        return new ParamDataTable[0];
    } catch (final IOException e) {
        e.printStackTrace();
        return new ParamDataTable[0];
    }
    //$NON-NLS-1$
    final Node[] tableNodes = DOMUtils.getChildElements(n, "Table1");
    final ParamDataTable[] tables = new ParamDataTable[tableNodes.length];
    for (int i = 0; i < tables.length; i++) {
        tables[i] = new ParamDataTable(tableNodes[i]);
    }
    return tables;
}

70. RsXembly#render()

Project: takes
File: RsXembly.java
/**
     * Render source as XML.
     * @param dom DOM node to build upon
     * @param src Source
     * @return XML
     * @throws IOException If fails
     */
private static InputStream render(final Node dom, final XeSource src) throws IOException {
    final Node copy = cloneNode(dom);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Node node = new Xembler(src.toXembly()).applyQuietly(copy);
    try {
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(node), new StreamResult(new Utf8OutputStreamWriter(baos)));
    } catch (final TransformerException ex) {
        throw new IllegalStateException(ex);
    }
    return new ByteArrayInputStream(baos.toByteArray());
}

71. XmlSchemaParser#getAttributeValueOrNull()

Project: simple-binary-encoding
File: XmlSchemaParser.java
/**
     * Helper function that hides the null return from {@link org.w3c.dom.NamedNodeMap#getNamedItem(String)}
     *
     * @param elementNode that could be null
     * @param attrName    that is to be looked up
     * @return null or value of the attribute
     */
public static String getAttributeValueOrNull(final Node elementNode, final String attrName) {
    if (null == elementNode || null == elementNode.getAttributes()) {
        return null;
    }
    final Node attrNode = elementNode.getAttributes().getNamedItem(attrName);
    if (null == attrNode) {
        return null;
    }
    return attrNode.getNodeValue();
}

72. XmlSchemaParser#getAttributeValue()

Project: simple-binary-encoding
File: XmlSchemaParser.java
/**
     * Helper function that throws an exception when the attribute is not set.
     *
     * @param elementNode that should have the attribute
     * @param attrName    that is to be looked up
     * @return value of the attribute
     * @throws IllegalArgumentException if the attribute is not present
     */
public static String getAttributeValue(final Node elementNode, final String attrName) {
    final Node attrNode = elementNode.getAttributes().getNamedItem(attrName);
    if (attrNode == null || "".equals(attrNode.getNodeValue())) {
        throw new IllegalStateException("Element '" + elementNode.getNodeName() + "' has empty or missing attribute: " + attrName);
    }
    return attrNode.getNodeValue();
}

73. SmilDocumentImpl#getLayout()

Project: Silence
File: SmilDocumentImpl.java
public SMILLayoutElement getLayout() {
    Node headElement = getHead();
    Node layoutElement = null;
    // Find the layout element under <code>HEAD</code>
    layoutElement = headElement.getFirstChild();
    while ((layoutElement != null) && !(layoutElement instanceof SMILLayoutElement)) {
        layoutElement = layoutElement.getNextSibling();
    }
    if (layoutElement == null) {
        // The layout doesn't exist. Create a default one.
        layoutElement = new SmilLayoutElementImpl(this, "layout");
        headElement.appendChild(layoutElement);
    }
    return (SMILLayoutElement) layoutElement;
}

74. AbstractAttr#getNodeValue()

Project: batik
File: AbstractAttr.java
/**
     * <b>DOM</b>: Implements {@link 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();
}

75. SVGTextElementBridge#handleDOMNodeInsertedEvent()

Project: batik
File: SVGTextElementBridge.java
/**
     * 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());
    }
}

76. DefaultXBLManager#getXblParentNode()

Project: batik
File: DefaultXBLManager.java
/**
     * 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;
}

77. XmlUserManager#parseGroupRoleTag()

Project: azkaban
File: XmlUserManager.java
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.");
}

78. WSDLElementQualifier#getNameAttribute()

Project: axis2-java
File: WSDLElementQualifier.java
/**
     * 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();
}

79. ParsedUpdateStmt#parse()

Project: h-store
File: ParsedUpdateStmt.java
@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);
    }
}

80. ParsedInsertStmt#parseInsertColumn()

Project: h-store
File: ParsedInsertStmt.java
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);
}

81. ParsedDeleteStmt#parse()

Project: h-store
File: ParsedDeleteStmt.java
@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);
    }
}

82. BuildTargetsSerializer#doReadFromString()

Project: goclipse
File: BuildTargetsSerializer.java
@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;
}

83. XmlNode#previous_element()

Project: gocd
File: XmlNode.java
@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);
}

84. XmlNode#next_element()

Project: gocd
File: XmlNode.java
@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);
}

85. XmlDtd#newFromExternalSubset()

Project: gocd
File: XmlDtd.java
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;
    }
}

86. XmlDtd#newFromInternalSubset()

Project: gocd
File: XmlDtd.java
/**
     * 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;
    }
}

87. CanonicalizerBase#getParentNameSpaces()

Project: gocd
File: CanonicalizerBase.java
/**
     * 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);
    }
}

88. ShortHistogramTest#upgradeMetadata()

Project: jdk7u-jdk
File: ShortHistogramTest.java
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;
}

89. DOMUtils#paramsEqual()

Project: jdk7u-jdk
File: DOMUtils.java
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);
}

90. XMLCipher#encryptElement()

Project: jdk7u-jdk
File: XMLCipher.java
/**
     * 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
     * {@link #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);
}

91. PNGMetadata#getAttribute()

Project: jdk7u-jdk
File: PNGMetadata.java
// 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();
}

92. PNGMetadata#getStringAttribute()

Project: jdk7u-jdk
File: PNGMetadata.java
// 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();
}

93. GIFMetadata#getAttribute()

Project: jdk7u-jdk
File: GIFMetadata.java
// 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();
}

94. InnerNodeImpl#getTextContent()

Project: j2objc
File: InnerNodeImpl.java
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();
}

95. InnerNodeImpl#normalize()

Project: j2objc
File: InnerNodeImpl.java
/**
     * 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();
        }
    }
}

96. CDATASectionImpl#split()

Project: j2objc
File: CDATASectionImpl.java
/**
     * 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]);
}

97. ObjUtil#xmlEqualsAllowNull()

Project: incubator-openaz
File: ObjUtil.java
/**
     * 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;
}

98. StdRequestAttributes#getContentNodeByXpathExpression()

Project: incubator-openaz
File: StdRequestAttributes.java
@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;
}

99. StdMutableRequestAttributes#getContentNodeByXpathExpression()

Project: incubator-openaz
File: StdMutableRequestAttributes.java
@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;
}

100. GeneNetworkTest#tstOutputNetwork()

Project: igv
File: GeneNetworkTest.java
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));
    }
}