KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > util > xml > DOMUtils


1 /*
2  * JBoss, Home of Professional Open Source
3  * Copyright 2005, JBoss Inc., and individual contributors as indicated
4  * by the @authors tag. See the copyright.txt in the distribution for a
5  * full listing of individual contributors.
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this software; if not, write to the Free
19  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21  */

22 package org.jboss.util.xml;
23
24 // $Id: DOMUtils.java 2017 2006-09-04 23:31:14Z thomas.diesler@jboss.com $
25

26 import java.io.ByteArrayInputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33
34 import javax.xml.namespace.QName JavaDoc;
35 import javax.xml.parsers.DocumentBuilder JavaDoc;
36 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
37 import javax.xml.parsers.ParserConfigurationException JavaDoc;
38
39 import org.jboss.logging.Logger;
40 import org.w3c.dom.Attr JavaDoc;
41 import org.w3c.dom.Document JavaDoc;
42 import org.w3c.dom.Element JavaDoc;
43 import org.w3c.dom.NamedNodeMap JavaDoc;
44 import org.w3c.dom.Node JavaDoc;
45 import org.w3c.dom.NodeList JavaDoc;
46 import org.w3c.dom.Text JavaDoc;
47 import org.xml.sax.InputSource JavaDoc;
48 import org.xml.sax.SAXException JavaDoc;
49
50 /**
51  * DOM2 utilites
52  *
53  * @author Thomas.Diesler@jboss.org
54  * @version $Revision: 2017 $
55  */

56 public final class DOMUtils
57 {
58     private static Logger log = Logger.getLogger(DOMUtils.class);
59
60     // All elements created by the same thread are created by the same builder and belong to the same doc
61
private static ThreadLocal JavaDoc documentThreadLocal = new ThreadLocal JavaDoc();
62     private static ThreadLocal JavaDoc builderThreadLocal = new ThreadLocal JavaDoc() {
63         protected Object JavaDoc initialValue() {
64             try
65             {
66                 DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
67                 factory.setValidating(false);
68                 factory.setNamespaceAware(true);
69                 DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
70                 builder.setEntityResolver(new JBossEntityResolver());
71                 return builder;
72             }
73             catch (ParserConfigurationException JavaDoc e)
74             {
75                 throw new RuntimeException JavaDoc("Failed to create DocumentBuilder", e);
76             }
77         }
78     };
79
80     // Hide the constructor
81
private DOMUtils()
82     {
83     }
84
85     /** Initialise the the DocumentBuilder
86      */

87     public static DocumentBuilder JavaDoc getDocumentBuilder()
88     {
89         DocumentBuilder JavaDoc builder = (DocumentBuilder JavaDoc)builderThreadLocal.get();
90         return builder;
91     }
92
93     /** Parse the given XML string and return the root Element
94      */

95     public static Element JavaDoc parse(String JavaDoc xmlString) throws IOException JavaDoc
96     {
97         try
98         {
99             return parse(new ByteArrayInputStream JavaDoc(xmlString.getBytes("UTF-8")));
100         }
101         catch (IOException JavaDoc e)
102         {
103             log.error("Cannot parse: " + xmlString);
104             throw e;
105         }
106     }
107
108     /** Parse the given XML stream and return the root Element
109      */

110     public static Element JavaDoc parse(InputStream JavaDoc xmlStream) throws IOException JavaDoc
111     {
112         try
113         {
114             Document JavaDoc doc = getDocumentBuilder().parse(xmlStream);
115             Element JavaDoc root = doc.getDocumentElement();
116             return root;
117         }
118         catch (SAXException JavaDoc e)
119         {
120             throw new IOException JavaDoc(e.toString());
121         }
122     }
123
124     /** Parse the given input source and return the root Element
125      */

126     public static Element JavaDoc parse(InputSource JavaDoc source) throws IOException JavaDoc
127     {
128         try
129         {
130             Document JavaDoc doc = getDocumentBuilder().parse(source);
131             Element JavaDoc root = doc.getDocumentElement();
132             return root;
133         }
134         catch (SAXException JavaDoc e)
135         {
136             throw new IOException JavaDoc(e.toString());
137         }
138     }
139
140     /** Create an Element for a given name
141      */

142     public static Element JavaDoc createElement(String JavaDoc localPart)
143     {
144         Document JavaDoc doc = getOwnerDocument();
145         log.trace("createElement {}" + localPart);
146         return doc.createElement(localPart);
147     }
148
149     /** Create an Element for a given name and prefix
150      */

151     public static Element JavaDoc createElement(String JavaDoc localPart, String JavaDoc prefix)
152     {
153         Document JavaDoc doc = getOwnerDocument();
154         log.trace("createElement {}" + prefix + ":" + localPart);
155         return doc.createElement(prefix + ":" + localPart);
156     }
157
158     /** Create an Element for a given name, prefix and uri
159      */

160     public static Element JavaDoc createElement(String JavaDoc localPart, String JavaDoc prefix, String JavaDoc uri)
161     {
162         Document JavaDoc doc = getOwnerDocument();
163         if (prefix == null || prefix.length() == 0)
164         {
165             log.trace("createElement {" + uri + "}" + localPart);
166             return doc.createElementNS(uri, localPart);
167         }
168         else
169         {
170             log.trace("createElement {" + uri + "}" + prefix + ":" + localPart);
171             return doc.createElementNS(uri, prefix + ":" + localPart);
172         }
173     }
174
175     /** Create an Element for a given QName
176      */

177     public static Element JavaDoc createElement(QName JavaDoc qname)
178     {
179         return createElement(qname.getLocalPart(), qname.getPrefix(), qname.getNamespaceURI());
180     }
181
182     /** Create a org.w3c.dom.Text node
183      */

184     public static Text JavaDoc createTextNode(String JavaDoc value)
185     {
186         Document JavaDoc doc = getOwnerDocument();
187         return doc.createTextNode(value);
188     }
189
190     /** Get the qname of the given node.
191      */

192     public static QName JavaDoc getElementQName(Element JavaDoc el)
193     {
194         String JavaDoc qualifiedName = el.getNodeName();
195         return resolveQName(el, qualifiedName);
196     }
197
198     /** Transform the giveen qualified name into a QName
199      */

200     public static QName JavaDoc resolveQName(Element JavaDoc el, String JavaDoc qualifiedName)
201     {
202         QName JavaDoc qname;
203         String JavaDoc prefix = "";
204         String JavaDoc namespaceURI = "";
205         String JavaDoc localPart = qualifiedName;
206
207         int colIndex = qualifiedName.indexOf(":");
208         if (colIndex > 0)
209         {
210             prefix = qualifiedName.substring(0, colIndex);
211             localPart = qualifiedName.substring(colIndex + 1);
212
213             if ("xmlns".equals(prefix))
214             {
215                 namespaceURI = "URI:XML_PREDEFINED_NAMESPACE";
216             }
217             else
218             {
219                 Element JavaDoc nsElement = el;
220                 while (namespaceURI.equals("") && nsElement != null)
221                 {
222                     namespaceURI = nsElement.getAttribute("xmlns:" + prefix);
223                     if (namespaceURI.equals(""))
224                         nsElement = getParentElement(nsElement);
225                 }
226             }
227
228             if (namespaceURI.equals(""))
229                 throw new IllegalArgumentException JavaDoc("Cannot find namespace uri for: " + qualifiedName);
230         }
231
232         qname = new QName JavaDoc(namespaceURI, localPart, prefix);
233         return qname;
234     }
235
236     /** Get the value from the given attribute
237      *
238      * @return null if the attribute value is empty or the attribute is not present
239      */

240     public static String JavaDoc getAttributeValue(Element JavaDoc el, String JavaDoc attrName)
241     {
242         return getAttributeValue(el, new QName JavaDoc(attrName));
243     }
244
245     /** Get the value from the given attribute
246      *
247      * @return null if the attribute value is empty or the attribute is not present
248      */

249     public static String JavaDoc getAttributeValue(Element JavaDoc el, QName JavaDoc attrName)
250     {
251         String JavaDoc attr = null;
252         if ("".equals(attrName.getNamespaceURI()))
253             attr = el.getAttribute(attrName.getLocalPart());
254         else attr = el.getAttributeNS(attrName.getNamespaceURI(), attrName.getLocalPart());
255
256         if ("".equals(attr))
257             attr = null;
258
259         return attr;
260     }
261
262     /** Get the qname value from the given attribute
263      */

264     public static QName JavaDoc getAttributeValueAsQName(Element JavaDoc el, String JavaDoc attrName)
265     {
266         return getAttributeValueAsQName(el, new QName JavaDoc(attrName));
267
268     }
269
270     /** Get the qname value from the given attribute
271      */

272     public static QName JavaDoc getAttributeValueAsQName(Element JavaDoc el, QName JavaDoc attrName)
273     {
274         QName JavaDoc qname = null;
275
276         String JavaDoc qualifiedName = getAttributeValue(el, attrName);
277         if (qualifiedName != null)
278         {
279             qname = resolveQName(el, qualifiedName);
280         }
281
282         return qname;
283     }
284
285     /** Get the boolean value from the given attribute
286      */

287     public static boolean getAttributeValueAsBoolean(Element JavaDoc el, String JavaDoc attrName)
288     {
289         return getAttributeValueAsBoolean(el, new QName JavaDoc(attrName));
290     }
291
292     /** Get the boolean value from the given attribute
293      */

294     public static boolean getAttributeValueAsBoolean(Element JavaDoc el, QName JavaDoc attrName)
295     {
296         String JavaDoc attrVal = getAttributeValue(el, attrName);
297         boolean ret = "true".equalsIgnoreCase(attrVal) || "1".equalsIgnoreCase(attrVal);
298         return ret;
299     }
300
301     /** Get the integer value from the given attribute
302      */

303     public static Integer JavaDoc getAttributeValueAsInteger(Element JavaDoc el, String JavaDoc attrName)
304     {
305         return getAttributeValueAsInteger(el, new QName JavaDoc(attrName));
306     }
307
308     /** Get the integer value from the given attribute
309      */

310     public static Integer JavaDoc getAttributeValueAsInteger(Element JavaDoc el, QName JavaDoc attrName)
311     {
312         String JavaDoc attrVal = getAttributeValue(el, attrName);
313         return (attrVal != null ? new Integer JavaDoc(attrVal) : null);
314     }
315
316     /** Get the attributes as Map<QName, String>
317      */

318     public static Map JavaDoc getAttributes(Element JavaDoc el)
319     {
320         Map JavaDoc attmap = new HashMap JavaDoc();
321         NamedNodeMap JavaDoc attribs = el.getAttributes();
322         for (int i = 0; i < attribs.getLength(); i++)
323         {
324             Attr JavaDoc attr = (Attr JavaDoc)attribs.item(i);
325             String JavaDoc name = attr.getName();
326             QName JavaDoc qname = resolveQName(el, name);
327             String JavaDoc value = attr.getNodeValue();
328             attmap.put(qname, value);
329         }
330         return attmap;
331     }
332
333     /** Copy attributes between elements
334      */

335     public static void copyAttributes(Element JavaDoc destElement, Element JavaDoc srcElement)
336     {
337         NamedNodeMap JavaDoc attribs = srcElement.getAttributes();
338         for (int i = 0; i < attribs.getLength(); i++)
339         {
340             Attr JavaDoc attr = (Attr JavaDoc)attribs.item(i);
341             String JavaDoc uri = attr.getNamespaceURI();
342             String JavaDoc qname = attr.getName();
343             String JavaDoc value = attr.getNodeValue();
344             
345             // Prevent DOMException: NAMESPACE_ERR: An attempt is made to create or
346
// change an object in a way which is incorrect with regard to namespaces.
347
if (uri == null && qname.startsWith("xmlns"))
348             {
349                log.trace("Ignore attribute: [uri=" + uri + ",qname=" + qname + ",value=" + value + "]");
350             }
351             else
352             {
353                destElement.setAttributeNS(uri, qname, value);
354             }
355         }
356     }
357
358     /** True if the node has child elements
359      */

360     public static boolean hasChildElements(Node JavaDoc node)
361     {
362         NodeList JavaDoc nlist = node.getChildNodes();
363         for (int i = 0; i < nlist.getLength(); i++)
364         {
365             Node JavaDoc child = nlist.item(i);
366             if (child.getNodeType() == Node.ELEMENT_NODE)
367                 return true;
368         }
369         return false;
370     }
371
372     /** Gets child elements
373      */

374     public static Iterator JavaDoc getChildElements(Node JavaDoc node)
375     {
376         ArrayList JavaDoc list = new ArrayList JavaDoc();
377         NodeList JavaDoc nlist = node.getChildNodes();
378         for (int i = 0; i < nlist.getLength(); i++)
379         {
380             Node JavaDoc child = nlist.item(i);
381             if (child.getNodeType() == Node.ELEMENT_NODE)
382                 list.add(child);
383         }
384         return list.iterator();
385     }
386
387     /** Get the concatenated text content, or null.
388      */

389     public static String JavaDoc getTextContent(Node JavaDoc node)
390     {
391         boolean hasTextContent = false;
392         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
393         NodeList JavaDoc nlist = node.getChildNodes();
394         for (int i = 0; i < nlist.getLength(); i++)
395         {
396             Node JavaDoc child = nlist.item(i);
397             if (child.getNodeType() == Node.TEXT_NODE)
398             {
399                 buffer.append(child.getNodeValue());
400                 hasTextContent = true;
401             }
402         }
403         return (hasTextContent ? buffer.toString() : null);
404     }
405
406     /** Gets the first child element
407      */

408     public static Element JavaDoc getFirstChildElement(Node JavaDoc node)
409     {
410         return getFirstChildElementIntern(node, null);
411     }
412
413     /** Gets the first child element for a given local name without namespace
414      */

415     public static Element JavaDoc getFirstChildElement(Node JavaDoc node, String JavaDoc nodeName)
416     {
417         return getFirstChildElementIntern(node, new QName JavaDoc(nodeName));
418     }
419
420     /** Gets the first child element for a given qname
421      */

422     public static Element JavaDoc getFirstChildElement(Node JavaDoc node, QName JavaDoc nodeName)
423     {
424         return getFirstChildElementIntern(node, nodeName);
425     }
426
427     private static Element JavaDoc getFirstChildElementIntern(Node JavaDoc node, QName JavaDoc nodeName)
428     {
429         Element JavaDoc childElement = null;
430         Iterator JavaDoc it = getChildElementsIntern(node, nodeName);
431         if (it.hasNext())
432         {
433             childElement = (Element JavaDoc)it.next();
434         }
435         return childElement;
436     }
437
438     /** Gets the child elements for a given local name without namespace
439      */

440     public static Iterator JavaDoc getChildElements(Node JavaDoc node, String JavaDoc nodeName)
441     {
442         return getChildElementsIntern(node, new QName JavaDoc(nodeName));
443     }
444
445     /** Gets the child element for a given qname
446      */

447     public static Iterator JavaDoc getChildElements(Node JavaDoc node, QName JavaDoc nodeName)
448     {
449         return getChildElementsIntern(node, nodeName);
450     }
451
452     private static Iterator JavaDoc getChildElementsIntern(Node JavaDoc node, QName JavaDoc nodeName)
453     {
454         ArrayList JavaDoc list = new ArrayList JavaDoc();
455         NodeList JavaDoc nlist = node.getChildNodes();
456         for (int i = 0; i < nlist.getLength(); i++)
457         {
458             Node JavaDoc child = nlist.item(i);
459             if (child.getNodeType() == Node.ELEMENT_NODE)
460             {
461                 if (nodeName == null)
462                 {
463                     list.add(child);
464                 }
465                 else
466                 {
467                     QName JavaDoc qname;
468                     if (nodeName.getNamespaceURI().length() > 0)
469                     {
470                         qname = new QName JavaDoc(child.getNamespaceURI(), child.getLocalName());
471                     }
472                     else
473                     {
474                         qname = new QName JavaDoc(child.getLocalName());
475                     }
476                     if (qname.equals(nodeName))
477                     {
478                         list.add(child);
479                     }
480                 }
481             }
482         }
483         return list.iterator();
484     }
485
486     /** Gets parent element or null if there is none
487      */

488     public static Element JavaDoc getParentElement(Node JavaDoc node)
489     {
490         Node JavaDoc parent = node.getParentNode();
491         return (parent instanceof Element JavaDoc ? (Element JavaDoc)parent : null);
492     }
493
494     /** Get the owner document that is associated with the current thread */
495     public static Document JavaDoc getOwnerDocument()
496     {
497         Document JavaDoc doc = (Document JavaDoc)documentThreadLocal.get();
498         if (doc == null)
499         {
500             doc = getDocumentBuilder().newDocument();
501             documentThreadLocal.set(doc);
502         }
503         return doc;
504     }
505 }
506
Popular Tags