domutils.java

来自「bpel执行引擎用来执行bpel业务流程」· Java 代码 · 共 1,040 行 · 第 1/3 页

JAVA
1,040
字号
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *    http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.ode.utils;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.Reader;import java.io.StringReader;import java.io.StringWriter;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Map;import javax.xml.namespace.QName;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.stream.XMLStreamConstants;import javax.xml.stream.XMLStreamException;import javax.xml.stream.XMLStreamReader;import javax.xml.transform.Source;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMResult;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.sax.SAXSource;import javax.xml.transform.stream.StreamSource;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.ode.utils.sax.LoggingErrorHandler;import org.apache.xerces.dom.DOMOutputImpl;import org.apache.xerces.impl.Constants;import org.apache.xml.serialize.DOMSerializerImpl;import org.apache.xml.serialize.OutputFormat;import org.apache.xml.serialize.XMLSerializer;import org.w3c.dom.Attr;import org.w3c.dom.CharacterData;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.InputSource;import org.xml.sax.SAXException;/** * Utility class for dealing with the Document Object Model (DOM). */public class DOMUtils {    private static Log __log = LogFactory.getLog(DOMUtils.class);    /** The namespaceURI represented by the prefix <code>xmlns</code>. */    public static final String NS_URI_XMLNS = "http://www.w3.org/2000/xmlns/";    private static ThreadLocal<Transformer> __txers = new ThreadLocal();    private static ThreadLocal<DocumentBuilder> __builders = new ThreadLocal();    private static TransformerFactory _transformerFactory = TransformerFactory.newInstance();    private static DocumentBuilderFactory __documentBuilderFactory ;    static {        initDocumentBuilderFactory();    }    /**     * Initialize the document-builder factory.     */    private static void initDocumentBuilderFactory() {        DocumentBuilderFactory f = XMLParserUtils.getDocumentBuilderFactory();        f.setNamespaceAware(true);        __documentBuilderFactory = f;    }    /**     * Returns the value of an attribute of an element. Returns null if the     * attribute is not found (whereas Element.getAttribute returns "" if an     * attrib is not found).     *     * @param el Element whose attrib is looked for     * @param attrName name of attribute to look for     *     * @return the attribute value     */    static public String getAttribute(Element el, String attrName) {        String sRet = null;        Attr attr = el.getAttributeNode(attrName);        if (attr != null) {            sRet = attr.getValue();        }        return sRet;    }    /**     * @deprecated relies on XMLSerializer which is a deprecated Xerces class, use domToString instead     */    static public String prettyPrint(Element e) throws IOException {        OutputFormat format = new OutputFormat(e.getOwnerDocument());        format.setLineWidth(65);        format.setIndenting(true);        format.setIndent(2);        StringWriter out = new StringWriter();        XMLSerializer serializer = new XMLSerializer(out, format);        serializer.serialize(e);        return out.toString();    }    /**     * Returns the value of an attribute of an element. Returns null if the     * attribute is not found (whereas Element.getAttributeNS returns "" if an     * attrib is not found).     *     * @param el Element whose attrib is looked for     * @param namespaceURI namespace URI of attribute to look for     * @param localPart local part of attribute to look for     *     * @return the attribute value     */    static public String getAttributeNS(Element el, String namespaceURI,                                        String localPart) {        String sRet = null;        Attr attr = el.getAttributeNodeNS(namespaceURI, localPart);        if (attr != null) {            sRet = attr.getValue();        }        return sRet;    }    /**     * Concat all the text and cdata node children of this elem and return the     * resulting text.     *     * @param parentEl the element whose cdata/text node values are to be     *        combined.     *     * @return the concatanated string.     */    static public String getChildCharacterData(Element parentEl) {        if (parentEl == null) { return null; }        Node tempNode = parentEl.getFirstChild();        StringBuffer strBuf = new StringBuffer();        CharacterData charData;        while (tempNode != null) {            switch (tempNode.getNodeType()) {                case Node.TEXT_NODE:                case Node.CDATA_SECTION_NODE:                    charData = (CharacterData) tempNode;                    strBuf.append(charData.getData());                    break;            }            tempNode = tempNode.getNextSibling();        }        return strBuf.toString();    }    /**     * DOCUMENTME     *     * @param el DOCUMENTME     * @param id DOCUMENTME     *     * @return DOCUMENTME     */    public static Element getElementByID(Element el, String id) {        if (el == null) { return null; }        String thisId = el.getAttribute("id");        if (id.equals(thisId)) { return el; }        NodeList list = el.getChildNodes();        for (int i = 0; i < list.getLength(); i++) {            Node node = list.item(i);            if (node instanceof Element) {                Element ret = getElementByID((Element) node, id);                if (ret != null) { return ret; }            }        }        return null;    }    /**     * Return the first child element of the given element. Null if no children     * are found.     *     * @param elem Element whose child is to be returned     *     * @return the first child element.     */    public static Element getFirstChildElement(Element elem) {        if (elem == null)            throw new NullPointerException("elem parameter must not be null!");        for (Node n = elem.getFirstChild(); n != null; n = n.getNextSibling()) {            if (n.getNodeType() == Node.ELEMENT_NODE) { return (Element) n; }        }        return null;    }    /**     * Given a prefix and a node, return the namespace URI that the prefix has     * been associated with. This method is useful in resolving the namespace     * URI of attribute values which are being interpreted as QNames. If prefix     * is null, this method will return the default namespace.     *     * @param context the starting node (looks up recursively from here)     * @param prefix the prefix to find an xmlns:prefix=uri for     *     * @return the namespace URI or null if not found     */    public static String getNamespaceURIFromPrefix(Node context, String prefix) {        short nodeType = context.getNodeType();        Node tempNode = null;        switch (nodeType) {            case Node.ATTRIBUTE_NODE: {                tempNode = ((Attr) context).getOwnerElement();                break;            }            case Node.ELEMENT_NODE: {                tempNode = context;                break;            }            default: {                tempNode = context.getParentNode();                break;            }        }        while ((tempNode != null) && (tempNode.getNodeType() == Node.ELEMENT_NODE)) {            Element tempEl = (Element) tempNode;            String namespaceURI = (prefix == null) ? getAttribute(tempEl, "xmlns")                    : getAttributeNS(tempEl, NS_URI_XMLNS, prefix);            if (namespaceURI != null) {                return namespaceURI;            }            tempNode = tempEl.getParentNode();        }        return null;    }    /**     * Return the next sibling element of the given element. Null if no more     * sibling elements are found.     *     * @param elem Element whose sibling element is to be returned     *     * @return the next sibling element.     */    public static Element getNextSiblingElement(Element elem) {        for (Node n = elem.getNextSibling(); n != null; n = n.getNextSibling()) {            if (n.getNodeType() == Node.ELEMENT_NODE) { return (Element) n; }        }        return null;    }    /**     * DOCUMENTME     *     * @param el DOCUMENTME     * @param attrName DOCUMENTME     *     * @return DOCUMENTME     *     * @throws IllegalArgumentException DOCUMENTME     */    public static QName getQualifiedAttributeValue(Element el, String attrName)            throws IllegalArgumentException {        String attrValue = DOMUtils.getAttribute(el, attrName);        if (attrValue != null) {            int index = attrValue.indexOf(':');            String attrValuePrefix = (index != -1) ? attrValue.substring(0, index)                    : null;            String attrValueLocalPart = attrValue.substring(index + 1);            String attrValueNamespaceURI = DOMUtils.getNamespaceURIFromPrefix(el,                    attrValuePrefix);            if (attrValueNamespaceURI != null) {                return new QName(attrValueNamespaceURI, attrValueLocalPart);            }            throw new IllegalArgumentException("Unable to determine "                    + "namespace of '"                    + ((attrValuePrefix != null) ? (attrValuePrefix + ":") : "")                    + attrValueLocalPart + "'.");        }        return null;    }    /**     * Count number of children of a certain type of the given element.     *     * @param elem the element whose kids are to be counted     * @param nodeType DOCUMENTME     *     * @return the number of matching kids.     */    public static int countKids(Element elem, short nodeType) {        int nkids = 0;        for (Node n = elem.getFirstChild(); n != null; n = n.getNextSibling()) {            if (n.getNodeType() == nodeType) {                nkids++;            }        }        return nkids;    }    /**     * This method traverses the DOM and grabs namespace declarations     * on parent elements with the intent of preserving them for children.  <em>Note     * that the DOM level 3 document method {@link Element#getAttribute(java.lang.String)}     * is not desirable in this case, as it does not respect namespace prefix     * bindings that may affect attribute values.  (Namespaces in DOM are     * uncategorically a mess, especially in the context of XML Schema.)</em>     * @param el the starting element     * @return a {@link Map} containing prefix bindings.     */    public static Map<String, String> getParentNamespaces(Element el) {        HashMap<String,String> pref = new HashMap<String,String>();        Map<String,String> mine = getMyNamespaces(el);        Node n = el.getParentNode();        while (n != null && n.getNodeType() != Node.DOCUMENT_NODE) {            if (n instanceof Element) {                Element l = (Element) n;                NamedNodeMap nnm = l.getAttributes();                int len = nnm.getLength();                for (int i = 0; i < len; ++i) {                    Attr a = (Attr) nnm.item(i);                    if (isNSAttribute(a)) {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?