KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > petals > tools > jbicommon > util > XMLUtil


1 /**
2  * PETALS - PETALS Services Platform.
3  * Copyright (c) 2006 EBM Websourcing
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * -------------------------------------------------------------------------
19  * $Id: XMLUtil.java 98 2006-02-24 16:18:48Z alouis $
20  * -------------------------------------------------------------------------
21  */

22
23 package org.objectweb.petals.tools.jbicommon.util;
24
25 import java.io.ByteArrayInputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.StringWriter JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.logging.Level JavaDoc;
32 import java.util.logging.Logger 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 import javax.xml.transform.OutputKeys JavaDoc;
39 import javax.xml.transform.Result JavaDoc;
40 import javax.xml.transform.Source JavaDoc;
41 import javax.xml.transform.Transformer JavaDoc;
42 import javax.xml.transform.TransformerException JavaDoc;
43 import javax.xml.transform.TransformerFactory JavaDoc;
44 import javax.xml.transform.dom.DOMSource JavaDoc;
45 import javax.xml.transform.stream.StreamResult JavaDoc;
46
47 import org.objectweb.petals.tools.jbicommon.descriptor.JBIDescriptorException;
48 import org.w3c.dom.Document JavaDoc;
49 import org.w3c.dom.NamedNodeMap JavaDoc;
50 import org.w3c.dom.Node JavaDoc;
51 import org.w3c.dom.NodeList JavaDoc;
52 import org.xml.sax.InputSource JavaDoc;
53 import org.xml.sax.SAXException JavaDoc;
54
55 import com.sun.org.apache.xpath.internal.XPathAPI;
56
57 /**
58  * Contains utilities methods for XML operations.
59  *
60  * @version $Rev: 98 $ $Date: 2006-02-24 17:18:48 +0100 (ven., 24 f??vr. 2006) $
61  * @since Petals 1.0
62  * @author Adrien LOUIS
63  * @author ddesjardins - eBMWebsourcing
64  * @author gblondelle - eBMWebsourcing
65  */

66 public final class XMLUtil {
67
68     private static final Logger JavaDoc LOGGER = Logger.getLogger(XMLUtil.class
69             .getName());
70
71     private XMLUtil() {
72         // Do nothing
73
}
74
75     /**
76      * Create an attribute node with the specified value
77      *
78      * @param document
79      * XML document
80      * @param att
81      * attribute name
82      * @param value
83      * attribute value
84      * @return an attribute, null if the document is null
85      */

86     public static Node JavaDoc createAttribute(final Document JavaDoc document,
87             final String JavaDoc att, final String JavaDoc value) {
88         Node JavaDoc element = null;
89         if (document != null) {
90             element = document.createAttribute(att);
91             element.setNodeValue(value);
92         }
93         return element;
94     }
95
96     /**
97      * Create a node with the specified name, attributes and values. attVal is a
98      * suite : att1,val1,att2,val2,...
99      *
100      * @param document
101      * xlm document
102      * @param nodeName
103      * node name
104      * @param attVal
105      * attribute values
106      * @return the node with its attribute, null if the array is not correct or
107      * the document is null.
108      */

109     public static Node JavaDoc createNode(final Document JavaDoc document,
110             final String JavaDoc nodeName, final String JavaDoc... attVal) {
111         Node JavaDoc element = null;
112         if (document != null && attVal.length % 2 == 0) {
113             element = document.createElement(nodeName);
114             for (int i = 0; i < attVal.length; i = i + 2) {
115                 element.getAttributes().setNamedItem(
116                         createAttribute(document, attVal[i], attVal[i + 1]));
117             }
118         }
119         return element;
120     }
121
122     /**
123      * Search for a child with the given nodeName. If recursive, search in all
124      * the child of first level, then if not found, search in the 2nd level of
125      * the first child, ...
126      *
127      * @param node
128      * parent node
129      * @param nodeName
130      * node name
131      * @param recursive
132      * boolean to know if we got through the xml tree
133      * @return a node
134      */

135     public static Node JavaDoc findChild(final Node JavaDoc node, final String JavaDoc nodeName,
136             final boolean recursive) {
137         node.normalize();
138         Node JavaDoc result = null;
139         NodeList JavaDoc nl = node.getChildNodes();
140         if (node != null && nodeName != null) {
141             result = lookupNodeInNodeList(nodeName, nl);
142             // now, search recursively if required
143
if (result == null && recursive) {
144                 for (int i = 0; i < nl.getLength() && result == null; i++) {
145                     result = findChild(nl.item(i), nodeName, true);
146                 }
147             }
148         }
149         return result;
150     }
151
152     private static Node JavaDoc lookupNodeInNodeList(final String JavaDoc nodeName,
153             final NodeList JavaDoc nl) {
154         Node JavaDoc result = null;
155         for (int i = 0; i < nl.getLength() && result == null; i++) {
156             if (nodeName.equals(nl.item(i).getNodeName())) {
157                 result = nl.item(i);
158             }
159         }
160         return result;
161     }
162
163     /**
164      * Search for a child with the given nodeName. If recursive, search in all
165      * the child of firdt level, then if not found, search in the 2nd level of
166      * the first child, ...
167      *
168      * @param node
169      * parent node
170      * @param namespaceURI
171      * The namespaceURI of the node
172      * @param nodeName
173      * node name
174      * @param recursive
175      * boolean to know if we got through the xml tree
176      * @return a node
177      */

178     public static Node JavaDoc findChild(final Node JavaDoc node, final String JavaDoc namespaceURI,
179             final String JavaDoc nodeName, final boolean recursive) {
180         node.normalize();
181         String JavaDoc prefix = node.lookupPrefix(namespaceURI);
182         return findChild(node, prefix + nodeName, recursive);
183     }
184
185     /**
186      * Transform an XML {@link Node} into a String
187      *
188      * @param node
189      * the XML {@link Node} to parse
190      * @return the resulting String, null if node is null
191      * @throws TransformerException
192      * if errors occured during transformation
193      */

194     public static String JavaDoc parseToString(final Node JavaDoc node)
195             throws TransformerException JavaDoc {
196         String JavaDoc result = null;
197         if (node != null) {
198             node.normalize();
199             Transformer JavaDoc transformer = TransformerFactory.newInstance()
200                     .newTransformer();
201             StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
202             transformer.transform(new DOMSource JavaDoc(node), new StreamResult JavaDoc(
203                     stringWriter));
204             StringBuffer JavaDoc buffer = stringWriter.getBuffer();
205             result = buffer.toString();
206         }
207         return result;
208     }
209
210     /**
211      * Return the value of the attribute in the node
212      *
213      * @param n
214      * the node
215      * @param attName
216      * the name of the attribute
217      * @return the value of the attribute (can be empty), null if not found
218      */

219     public static String JavaDoc getAttributeValue(final Node JavaDoc n, final String JavaDoc attName) {
220         String JavaDoc ret = null;
221         if (n != null) {
222             NamedNodeMap JavaDoc atts = n.getAttributes();
223             Node JavaDoc att = atts.getNamedItem(attName);
224             if (att != null) {
225                 ret = att.getNodeValue();
226             }
227         }
228         return ret;
229     }
230
231     /**
232      * Return the value of the attribute in the node. Throws an exception if
233      * missing attribute.
234      *
235      * @param n
236      * the node
237      * @param attName
238      * the name of the attribute
239      * @return the value of the attribute (can be empty).
240      * @throws JBIDescriptorException
241      * if missing the required attribute
242      */

243     public static String JavaDoc getRequiredAttributeValue(final Node JavaDoc n,
244             final String JavaDoc attName) throws JBIDescriptorException {
245         String JavaDoc ret = null;
246         if (n != null) {
247             NamedNodeMap JavaDoc atts = n.getAttributes();
248             Node JavaDoc att = atts.getNamedItem(attName);
249             if (att != null) {
250                 String JavaDoc attValue = att.getNodeValue();
251                 if (!StringHelper.isNullOrEmpty(attName)) {
252                     ret = attValue;
253                 } else {
254                     throw new JBIDescriptorException(
255                             "Required attribute can't be empty: " + attName);
256                 }
257             } else {
258                 throw new JBIDescriptorException(
259                         "Missing a required attribute: " + attName);
260             }
261         }
262         return ret;
263     }
264
265     /**
266      * Return the first child of a node, regardless <i>text</i> node
267      *
268      * @param node
269      * @return
270      */

271     public static Node JavaDoc getFirstChild(final Node JavaDoc node) {
272         Node JavaDoc result = node.getFirstChild();
273         while (result != null && result.getNodeType() == Node.TEXT_NODE) {
274             result = result.getNextSibling();
275         }
276         return result;
277     }
278
279     /**
280      * Return the next sibling of a node, regardless <i>text</i> node
281      *
282      * @param node
283      * @return
284      */

285     public static Node JavaDoc getNextSibling(final Node JavaDoc node) {
286         Node JavaDoc result = node.getNextSibling();
287         if (result != null) {
288             while (result.getNodeType() == Node.TEXT_NODE) {
289                 result = result.getNextSibling();
290             }
291         }
292         return result;
293     }
294
295     // /**
296
// * return the node corresponding to the given path for the Document.
297
// *
298
// * @param path
299
// * @param document
300
// * @return the first matching node, null otherwise, or if document/path is
301
// * null
302
// */
303
// public static Node getNode(final Document document, final String path) {
304
// Node result = null;
305
// if (document != null && path != null) {
306
// try {
307
// result = XPathAPI.selectSingleNode(document, path);
308
// } catch (TransformerException e) {
309
// LOGGER.log(Level.SEVERE, "Unexpected XPATH problem", e);
310
// }
311
// }
312
// return result;
313
// }
314

315     /**
316      * Return the <i>text</i> element of a node
317      *
318      * @param node
319      * @return
320      */

321     public static String JavaDoc getTextContent(final Node JavaDoc node) {
322         String JavaDoc result = null;
323         NodeList JavaDoc list = node.getChildNodes();
324         for (int i = 0; i < list.getLength(); i++) {
325             if (list.item(i).getNodeType() == Node.TEXT_NODE) {
326                 result = list.item(i).getNodeValue();
327                 result = result.replace('\t', ' ').replace('\n', ' ').trim();
328                 break;
329             }
330         }
331         return result;
332     }
333
334     /**
335      * Create a String result from a DOM document
336      *
337      * @param document
338      * the DOM Document
339      * @return a String representation of the DOM Document
340      * @throws TransformerException
341      */

342     public static String JavaDoc createStringFromDOMDocument(final Node JavaDoc document)
343             throws TransformerException JavaDoc {
344         return createStringFromDOMNode(document, false);
345     }
346
347     /**
348      * Create a String result from a DOM Node
349      *
350      * @param node
351      * the DOM Node
352      * @return a String representation of the DOM Document
353      * @throws TransformerException
354      */

355     public static String JavaDoc createStringFromDOMNode(final Node JavaDoc node)
356             throws TransformerException JavaDoc {
357         return createStringFromDOMNode(node, true);
358     }
359
360     /**
361      * Create a String result from a DOM Node
362      *
363      * @param node
364      * the DOM Node
365      * @return a String representation of the DOM Document
366      * @throws TransformerException
367      */

368     public static String JavaDoc createStringFromDOMNode(final Node JavaDoc node,
369             final boolean omitDeclaration) throws TransformerException JavaDoc {
370         node.normalize();
371         Source JavaDoc source = new DOMSource JavaDoc(node);
372         StringWriter JavaDoc out = new StringWriter JavaDoc();
373         Result JavaDoc resultStream = new StreamResult JavaDoc(out);
374         TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
375         Transformer JavaDoc transformer;
376         transformer = tFactory.newTransformer();
377         if (omitDeclaration) {
378             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
379                     "yes");
380         }
381         transformer.transform(source, resultStream);
382         return out.toString();
383     }
384
385     /**
386      * Create a document from a String
387      *
388      * @param xml
389      * an xml string
390      * @return a {@link Document} representing the document, null if an error
391      * occured
392      */

393     public static Document JavaDoc createDocumentFromString(final String JavaDoc xml) {
394         Document JavaDoc doc = null;
395         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
396         factory.setNamespaceAware(true);
397         DocumentBuilder JavaDoc builder;
398         try {
399             builder = factory.newDocumentBuilder();
400             InputStream JavaDoc in = new ByteArrayInputStream JavaDoc(xml.getBytes());
401             InputSource JavaDoc inputSource = new InputSource JavaDoc(in);
402             doc = builder.parse(inputSource);
403             doc.normalize();
404         } catch (ParserConfigurationException JavaDoc e) {
405             LOGGER.log(Level.SEVERE, "Bad XML parser configuration", e);
406         } catch (SAXException JavaDoc e) {
407             LOGGER.log(Level.SEVERE,
408                     "Bad XML fragment can't be transformed to a DOM tree.", e);
409         } catch (IOException JavaDoc e) {
410             LOGGER.log(Level.SEVERE, "Unexpected Error", e);
411         }
412
413         return doc;
414     }
415
416     /**
417      * Return an array of String representing each Text element of the nodes
418      * which are in the list.
419      *
420      * @param list
421      * @return
422      */

423     public static List JavaDoc<String JavaDoc> getTextContents(final NodeList JavaDoc list) {
424         List JavaDoc<String JavaDoc> result = null;
425         if (list != null) {
426             result = new ArrayList JavaDoc<String JavaDoc>();
427             for (int i = 0; i < list.getLength(); i++) {
428                 Node JavaDoc pathElement = list.item(i);
429                 if (pathElement.getNodeType() != Node.TEXT_NODE) {
430                     result.add(getTextContent(pathElement));
431                 }
432             }
433         }
434         return result;
435     }
436
437     /**
438      * @param node
439      * @param attrName
440      * @return
441      */

442     public static QName JavaDoc extractXmlAttributeQName(final Node JavaDoc node,
443             final String JavaDoc attrName) {
444         String JavaDoc attr = XMLUtil.getAttributeValue(node, attrName);
445
446         QName JavaDoc qName = null;
447
448         // qname like "xmlns:name"
449
if ((attr.indexOf(':') > -1) && (attr.charAt(0) != '{')) {
450             String JavaDoc ns = attr.substring(0, attr.indexOf(':'));
451
452             String JavaDoc namespace = node.lookupNamespaceURI(ns);
453             /*
454              * String namespace = source.getDocumentElement().getAttribute(
455              * "xmlns:" + ns);
456              */

457
458             qName = new QName JavaDoc(namespace, attr.substring(attr.indexOf(':') + 1),
459                     ns);
460         } else {
461             // qname like "{ns}name" or "name"
462
qName = QName.valueOf(attr);
463         }
464         return qName;
465     }
466
467     /**
468      * @param node
469      * @param attrName
470      * @return
471      * @throws JBIDescriptorException
472      */

473     public static QName JavaDoc extractRequiredXmlAttributeQName(final Node JavaDoc node,
474             final String JavaDoc attrName) throws JBIDescriptorException {
475         String JavaDoc attr = XMLUtil.getRequiredAttributeValue(node, attrName);
476
477         QName JavaDoc qName = null;
478
479         // qname like "xmlns:name"
480
if ((attr.indexOf(':') > -1) && (attr.charAt(0) != '{')) {
481             String JavaDoc ns = attr.substring(0, attr.indexOf(':'));
482
483             String JavaDoc namespace = node.lookupNamespaceURI(ns);
484             /*
485              * String namespace = source.getDocumentElement().getAttribute(
486              * "xmlns:" + ns);
487              */

488
489             qName = new QName JavaDoc(namespace, attr.substring(attr.indexOf(':') + 1),
490                     ns);
491         } else {
492             // qname like "{ns}name" or "name"
493
qName = QName.valueOf(attr);
494         }
495         return qName;
496     }
497
498     /**
499      * A List of Node that contains all children of this node; nodes must be of
500      * type Node.ELEMENT_NODE to be returned. If there are no children, this is
501      * a NodeList containing no nodes.
502      *
503      * @param node
504      * the node from which children will be extracted
505      * @return a List of child Node of type Node.ELEMENT_NODE
506      */

507     public static List JavaDoc<Node JavaDoc> getNodeChildren(final Node JavaDoc node) {
508         List JavaDoc<Node JavaDoc> children = new ArrayList JavaDoc<Node JavaDoc>();
509         if (node != null) {
510             NodeList JavaDoc childrenList = node.getChildNodes();
511             for (int i = 0; i < childrenList.getLength(); i++) {
512                 Node JavaDoc child = childrenList.item(i);
513                 if (child.getNodeType() == Node.ELEMENT_NODE) {
514                     children.add(child);
515                 }
516             }
517         }
518
519         return children;
520     }
521
522     /**
523      * FIXME Change this method to use DOM instead of XPATH. return the node
524      * corresponding to the given path for the Document.
525      *
526      * @param path
527      * @param document
528      * @return the first matching node, null otherwise, or if document/path is
529      * null
530      */

531     public static Node JavaDoc getNode(Document JavaDoc document, String JavaDoc path) {
532         Node JavaDoc result = null;
533         if (document != null && path != null) {
534             try {
535                 result = XPathAPI.selectSingleNode(document, path);
536             } catch (TransformerException JavaDoc e) {
537                 return null;
538             }
539         }
540         return result;
541     }
542
543 }
544
Popular Tags