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. 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());
}

7. 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());
}

8. 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());
}

9. 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());
}

10. 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);
}

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. 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");
}

17. 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) {
    }
}

18. 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));
}

19. 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;
}

20. 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 {@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;
}

21. 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);
}

22. 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]/@ref", myBean5));
}

23. 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());
}

24. DOMTreeWalker#previousNode()

Project: batik
Source File: DOMTreeWalker.java
View license
/**
     * <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;
}

25. 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;
}

26. 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;
}

27. 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;
}

28. 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);
}

29. 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;
}

30. 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]/@ref", "produced2");
}

31. 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();
}

32. 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());
}

33. 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);
    }
}

34. 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"));
}

35. 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();
}

36. 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));
    }
}

37. 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;
}

38. 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);
}

39. 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
     * {@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;
}

40. 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();
}

41. 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();
}

42. 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();
}

43. PluginInfoTest#testChild()

Project: lucene-solr
Source File: PluginInfoTest.java
View license
@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);
}

44. PluginInfoTest#testClassRequired()

Project: lucene-solr
Source File: PluginInfoTest.java
View license
@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"));
}

45. PluginInfoTest#testNameRequired()

Project: lucene-solr
Source File: PluginInfoTest.java
View license
// 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"));
}

46. DOMUtil#substituteProperties()

Project: lucene-solr
Source File: DOMUtil.java
View license
/**
   * 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);
        }
    }
}

47. TestMessageTransformer#moveReferenceList()

Project: wss4j
Source File: TestMessageTransformer.java
View license
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);
}

48. XMLCipher#encryptElement()

Project: santuario-java
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
     * {@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;
}

49. CanonicalizerBase#getParentNameSpaces()

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 = ns.getMappingWithoutRendered(XMLNS);
    if (nsprefix != null && "".equals(nsprefix.getValue())) {
        ns.addMappingAndRender(XMLNS, "", getNullNode(nsprefix.getOwnerDocument()));
    }
}

50. DOMUtils#paramsEqual()

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

51. DOMKeyInfo#internalMarshal()

Project: santuario-java
Source File: DOMKeyInfo.java
View license
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);
}

52. RobolectricConfig#parseReceivers()

Project: robolectric
Source File: RobolectricConfig.java
View license
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));
        }
    }
}

53. XMLMultiElementArray#sort()

Project: railo
Source File: XMLMultiElementArray.java
View license
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
}

54. XMLMultiElementArray#sort()

Project: railo
Source File: XMLMultiElementArray.java
View license
@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
}

55. SmilDocumentImpl#getLayout()

Project: qksms
Source File: SmilDocumentImpl.java
View license
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;
}

56. PXDOMStyleAdapter#getAttributeValue()

View license
@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;
}

57. PXDOMStyleAdapter#getIndexInParent()

View license
@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;
}

58. DimensionTableDialog#addAttributesFromFile()

View license
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);
    }
}

59. 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;
}

60. 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);
}

61. 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;
}

62. 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;
}

63. BinarySecurity#getFirstNode()

Project: wss4j
Source File: BinarySecurity.java
View license
/**
     * 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()

View license
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
Source File: PositionManager.java
View license
/**
       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
Source File: FragmentDefinition.java
View license
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()

View license
/**
   * 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()

View license
/*
     * (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()

View license
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
Source File: RsXembly.java
View license
/**
     * 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()

View license
/**
     * 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()

View license
/**
     * 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
Source File: SmilDocumentImpl.java
View license
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
Source File: AbstractAttr.java
View license
/**
     * <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
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());
    }
}

76. 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;
}

77. 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.");
}

78. 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();
}

79. 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);
    }
}

80. 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);
}

81. 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;
}

82. 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;
}

83. 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();
}

84. 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();
}

85. 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();
}

86. DOMTreeWalker#nextNode()

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

87. AbstractText#getWholeText()

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

88. 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;
}

89. 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;
}

90. 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;
}

91. 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;
}

92. 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;
}

93. 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 + ">");
}

94. 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));
}

95. 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();
}

96. 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;
}

97. 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();
}

98. 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);
}

99. 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();
}

100. 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());
}