Example usage for org.w3c.dom Node DOCUMENT_NODE

List of usage examples for org.w3c.dom Node DOCUMENT_NODE

Introduction

In this page you can find the example usage for org.w3c.dom Node DOCUMENT_NODE.

Prototype

short DOCUMENT_NODE

To view the source code for org.w3c.dom Node DOCUMENT_NODE.

Click Source Link

Document

The node is a Document.

Usage

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Convert a DOM node to a stringified XML representation.
 *//*from  w  ww  .  j  a va2 s .c o  m*/
static public String domToStringLevel2(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value = null;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE);
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding("UTF-8");

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Deep clone, but don't fry, the given node in the context of the given document.
 * For all intents and purposes, the clone is the exact same copy of the node,
 * except that it might have a different owner document.
 *
 * This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods,
 * in that it doesn't assume that the given node has a parent or a owner document.
 *
 * @param document//ww w. j a v  a  2s . com
 * @param sourceNode
 * @return a clone of node
 */
public static Node cloneNode(Document document, Node sourceNode) {
    Node clonedNode = null;

    // what is my name?
    QName sourceQName = getNodeQName(sourceNode);
    String nodeName = sourceQName.getLocalPart();
    String namespaceURI = sourceQName.getNamespaceURI();

    // if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace
    if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) {
        namespaceURI = null;
    }

    switch (sourceNode.getNodeType()) {
    case Node.ATTRIBUTE_NODE:
        if (namespaceURI == null) {
            clonedNode = document.createAttribute(nodeName);
        } else {
            String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI);
            // the prefix for the XML namespace can't be looked up, hence this...
            if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) {
                prefix = "xmlns";
            }
            // if a prefix exists, qualify the name with it
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
            }
            // create the appropriate type of attribute
            if (prefix != null) {
                clonedNode = document.createAttributeNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createAttribute(nodeName);
            }
        }
        break;
    case Node.CDATA_SECTION_NODE:
        clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData());
        break;
    case Node.COMMENT_NODE:
        clonedNode = document.createComment(((Comment) sourceNode).getData());
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        clonedNode = document.createDocumentFragment();
        break;
    case Node.DOCUMENT_NODE:
        clonedNode = document;
        break;
    case Node.ELEMENT_NODE:
        // create the appropriate type of element
        if (namespaceURI == null) {
            clonedNode = document.createElement(nodeName);
        } else {
            String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ? "xmlns"
                    : ((Element) sourceNode).lookupPrefix(namespaceURI);
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
                clonedNode = document.createElementNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createElement(nodeName);
            }
        }
        // attributes are not treated as child nodes, so copy them explicitly
        NamedNodeMap attributes = ((Element) sourceNode).getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Attr attributeClone = (Attr) cloneNode(document, attributes.item(i));
            if (attributeClone.getNamespaceURI() == null) {
                ((Element) clonedNode).setAttributeNode(attributeClone);
            } else {
                ((Element) clonedNode).setAttributeNodeNS(attributeClone);
            }
        }
        break;
    case Node.ENTITY_NODE:
        // TODO
        break;
    case Node.ENTITY_REFERENCE_NODE:
        clonedNode = document.createEntityReference(nodeName);
        // TODO
        break;
    case Node.NOTATION_NODE:
        // TODO
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(),
                nodeName);
        break;
    case Node.TEXT_NODE:
        clonedNode = document.createTextNode(((Text) sourceNode).getData());
        break;
    default:
        break;
    }

    // clone children of element and attribute nodes
    NodeList sourceChildren = sourceNode.getChildNodes();
    if (sourceChildren != null) {
        for (int i = 0; i < sourceChildren.getLength(); i++) {
            Node sourceChild = sourceChildren.item(i);
            Node clonedChild = cloneNode(document, sourceChild);
            clonedNode.appendChild(clonedChild);
            // if the child has a textual value, parse it for any embedded prefixes
            if (clonedChild.getNodeType() == Node.TEXT_NODE
                    || clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) {
                parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild);
            }
        }
    }
    return clonedNode;
}

From source file:org.apache.ode.utils.xsl.XslTransformHandler.java

/**
 * Transforms a Source document to a result using the XSL stylesheet referenced
 * by the provided URI. The stylesheet MUST have been parsed previously.
 * @param uri referencing the stylesheet
 * @param source XML document//w  ww. ja va  2  s.c  om
 * @param parameters passed to the stylesheet
 * @param resolver used to resolve includes and imports
 * @return result of the transformation (XSL, HTML or text depending of the output method specified in stylesheet.
 */
public Object transform(QName processQName, URI uri, Source source, Map<QName, Object> parameters,
        URIResolver resolver) {
    Templates tm;
    synchronized (_templateCache) {
        tm = (Templates) _templateCache.get(processQName, uri);
    }
    if (tm == null)
        throw new XslTransformException("XSL sheet" + uri + " has not been parsed before transformation!");
    try {
        Transformer tf = tm.newTransformer();
        tf.setURIResolver(resolver);
        if (parameters != null) {
            for (Map.Entry<QName, Object> param : parameters.entrySet()) {
                tf.setParameter(param.getKey().getLocalPart(), param.getValue());
            }
        }
        String method = tf.getOutputProperties().getProperty("method");
        if (method == null || "xml".equals(method)) {
            DOMResult result = new DOMResult();
            tf.transform(source, result);
            Node node = result.getNode();
            if (node.getNodeType() == Node.DOCUMENT_NODE)
                node = ((Document) node).getDocumentElement();
            if (__log.isDebugEnabled())
                __log.debug("Returned node: type=" + node.getNodeType() + ", " + DOMUtils.domToString(node));
            return node;
        } else {
            // text and html outputs are handled the same way
            StringWriter writerResult = new StringWriter();
            StreamResult result = new StreamResult(writerResult);
            tf.transform(source, result);
            writerResult.flush();
            String output = writerResult.toString();
            if (__log.isDebugEnabled())
                __log.debug("Returned string: " + output);
            return output;
        }
    } catch (TransformerConfigurationException e) {
        throw new XslTransformException(e);
    } catch (TransformerException e) {
        throw new XslTransformException("XSL Transformation failed!", e);
    }
}

From source file:org.apache.ws.security.message.WSSecSignatureBase.java

/**
 * Get the List of inclusive prefixes from the DOM Element argument 
 *///w  w  w. j a  v  a  2 s. com
public List<String> getInclusivePrefixes(Element target, boolean excludeVisible) {
    List<String> result = new ArrayList<String>();
    Node parent = target;
    while (parent.getParentNode() != null && !(Node.DOCUMENT_NODE == parent.getParentNode().getNodeType())) {
        parent = parent.getParentNode();
        NamedNodeMap attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) {
                if ("xmlns".equals(attribute.getNodeName())) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible) {
        NamedNodeMap attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) {
                if ("xmlns".equals(attribute.getNodeName())) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}

From source file:org.apache.ws.security.processor.ReferenceListProcessor.java

/**
 * Recursively build an absolute xpath (starting with the root &quot;/&quot;)
 * //from w  w w.j av  a2s  .  c  o  m
 * @param xpath the xpath expression built so far
 * @param node the current node whose name is to be prepended
 * @return a fully built xpath
 */
private static String prependFullPath(String xpath, Node node) {
    if (node == null) {
        // probably a detached node... not really useful
        return null;
    } else if (Node.ELEMENT_NODE == node.getNodeType()) {
        xpath = node.getNodeName() + "/" + xpath;
        return prependFullPath(xpath, node.getParentNode());
    } else if (Node.DOCUMENT_NODE == node.getNodeType()) {
        return "/" + xpath;
    } else {
        return prependFullPath(xpath, node.getParentNode());
    }
}

From source file:org.apache.xml.security.encryption.XMLCipher.java

/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException//  w  w w.jav a2s .c o m
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isDebugEnabled()) {
        log.debug("Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.error("XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    String octets;
    try {
        octets = new String(decryptToByteArray(element), "UTF-8");
    } catch (UnsupportedEncodingException uee) {
        throw new XMLEncryptionException("empty", uee);
    }

    if (log.isDebugEnabled()) {
        log.debug("Decrypted octets:\n" + octets);
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}

From source file:org.apache.xml.security.utils.CachedXPathFuncHereAPI.java

/**
 *  Evaluate XPath string to an XObject.
 *  XPath namespace prefixes are resolved from the namespaceNode.
 *  The implementation of this is a little slow, since it creates
 *  a number of objects each time it is called.  This could be optimized
 *  to keep the same objects around, but then thread-safety issues would arise.
 *
 *  @param contextNode The node to start searching from.
 *  @param xpathnode//from   w  w  w  .  j  a va 2  s  .  c om
 *  @param str
 *  @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
 *  @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
 *  @see org.apache.xpath.objects.XObject
 *  @see org.apache.xpath.objects.XNull
 *  @see org.apache.xpath.objects.XBoolean
 *  @see org.apache.xpath.objects.XNumber
 *  @see org.apache.xpath.objects.XString
 *  @see org.apache.xpath.objects.XRTreeFrag
 *
 * @throws TransformerException
 */
public XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode)
        throws TransformerException {
    if (this.funcHereContext == null) {
        this.funcHereContext = new FuncHereContext(xpathnode, this.dtmManager);
    }

    // Create an object to resolve namespace prefixes.
    // XPath namespaces are resolved from the input context node's document element
    // if it is a root node, or else the current context node (for lack of a better
    // resolution space, given the simplicity of this sample code).
    PrefixResolverDefault prefixResolver = new PrefixResolverDefault(
            (namespaceNode.getNodeType() == Node.DOCUMENT_NODE)
                    ? ((Document) namespaceNode).getDocumentElement()
                    : namespaceNode);

    if (!str.equals(xpathStr)) {
        if (str.indexOf("here()") > 0) {
            context.reset();
            dtmManager = context.getDTMManager();
        }
        xpath = createXPath(str, prefixResolver);
        xpathStr = str;
    }

    // Execute the XPath, and have it return the result
    // return xpath.execute(xpathSupport, contextNode, prefixResolver);
    int ctxtNode = this.funcHereContext.getDTMHandleFromNode(contextNode);

    return xpath.execute(this.funcHereContext, ctxtNode, prefixResolver);
}

From source file:org.apache.xml.security.utils.IdResolver.java

private static int getEl(Node currentNode, String id, Element[] els) {
    Node sibling = null;/* ww w. j  a  v  a2  s  . c o  m*/
    Node parentNode = null;
    do {
        switch (currentNode.getNodeType()) {
        case Node.DOCUMENT_FRAGMENT_NODE:
        case Node.DOCUMENT_NODE:
            sibling = currentNode.getFirstChild();
            break;

        case Node.ELEMENT_NODE:
            Element currentElement = (Element) currentNode;
            if (isElement(currentElement, id, els) == 1) {
                return 1;
            }
            sibling = currentNode.getFirstChild();
            if (sibling == null) {
                if (parentNode != null) {
                    sibling = currentNode.getNextSibling();
                }
            } else {
                parentNode = currentElement;
            }
            break;
        }
        while (sibling == null && parentNode != null) {
            sibling = parentNode.getNextSibling();
            parentNode = parentNode.getParentNode();
            if (parentNode != null && Node.ELEMENT_NODE != parentNode.getNodeType()) {
                parentNode = null;
            }
        }
        if (sibling == null) {
            return 1;
        }
        currentNode = sibling;
        sibling = currentNode.getNextSibling();
    } while (true);
}

From source file:org.apache.xml.security.utils.XalanXPathAPI.java

private XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode)
        throws TransformerException {
    if (context == null) {
        context = new XPathContext(xpathnode);
        context.setSecureProcessing(true);
    }//from ww w .j  a va 2 s .  c o m

    // Create an object to resolve namespace prefixes.
    // XPath namespaces are resolved from the input context node's document element
    // if it is a root node, or else the current context node (for lack of a better
    // resolution space, given the simplicity of this sample code).
    Node resolverNode = (namespaceNode.getNodeType() == Node.DOCUMENT_NODE)
            ? ((Document) namespaceNode).getDocumentElement()
            : namespaceNode;
    PrefixResolverDefault prefixResolver = new PrefixResolverDefault(resolverNode);

    if (!str.equals(xpathStr)) {
        if (str.indexOf("here()") > 0) {
            context.reset();
        }
        xpath = createXPath(str, prefixResolver);
        xpathStr = str;
    }

    // Execute the XPath, and have it return the result
    int ctxtNode = context.getDTMHandleFromNode(contextNode);

    return xpath.execute(context, ctxtNode, prefixResolver);
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * This method returns the owner document of a particular node.
 * This method is necessary because it <I>always</I> returns a
 * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
 * if the {@link Node} is a {@link Document}.
 *
 * @param node/*from  ww  w  . ja  va 2  s . co m*/
 * @return the owner document of the node
 */
public static Document getOwnerDocument(Node node) {
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        return (Document) node;
    }
    try {
        return node.getOwnerDocument();
    } catch (NullPointerException npe) {
        throw new NullPointerException(
                I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + npe.getMessage() + "\"");
    }
}