KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > riotfamily > common > xml > XmlUtils


1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1
3  * The contents of this file are subject to the Mozilla Public License Version
4  * 1.1 (the "License"); you may not use this file except in compliance with
5  * the License. You may obtain a copy of the License at
6  * http://www.mozilla.org/MPL/
7  *
8  * Software distributed under the License is distributed on an "AS IS" basis,
9  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10  * for the specific language governing rights and limitations under the
11  * License.
12  *
13  * The Original Code is Riot.
14  *
15  * The Initial Developer of the Original Code is
16  * Neteye GmbH.
17  * Portions created by the Initial Developer are Copyright (C) 2006
18  * the Initial Developer. All Rights Reserved.
19  *
20  * Contributor(s):
21  * Felix Gnass [fgnass at neteye dot de]
22  *
23  * ***** END LICENSE BLOCK ***** */

24 package org.riotfamily.common.xml;
25
26 import java.io.IOException JavaDoc;
27 import java.io.StringReader JavaDoc;
28 import java.io.StringWriter JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.LinkedList JavaDoc;
31 import java.util.List JavaDoc;
32
33 import javax.xml.parsers.DocumentBuilder JavaDoc;
34 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
35 import javax.xml.parsers.ParserConfigurationException JavaDoc;
36 import javax.xml.transform.OutputKeys JavaDoc;
37 import javax.xml.transform.Result JavaDoc;
38 import javax.xml.transform.Source JavaDoc;
39 import javax.xml.transform.Transformer JavaDoc;
40 import javax.xml.transform.TransformerException JavaDoc;
41 import javax.xml.transform.TransformerFactory JavaDoc;
42 import javax.xml.transform.dom.DOMSource JavaDoc;
43 import javax.xml.transform.stream.StreamResult JavaDoc;
44
45 import org.riotfamily.common.util.FormatUtils;
46 import org.springframework.beans.BeanWrapper;
47 import org.springframework.beans.BeanWrapperImpl;
48 import org.springframework.beans.MutablePropertyValues;
49 import org.springframework.beans.PropertyValue;
50 import org.springframework.beans.PropertyValues;
51 import org.springframework.beans.factory.BeanFactory;
52 import org.springframework.util.Assert;
53 import org.springframework.util.StringUtils;
54 import org.w3c.dom.Attr JavaDoc;
55 import org.w3c.dom.Document JavaDoc;
56 import org.w3c.dom.Element JavaDoc;
57 import org.w3c.dom.NamedNodeMap JavaDoc;
58 import org.w3c.dom.Node JavaDoc;
59 import org.w3c.dom.NodeList JavaDoc;
60 import org.xml.sax.InputSource JavaDoc;
61 import org.xml.sax.SAXException JavaDoc;
62
63 /**
64  * Utility class that provides methods to create and populate beans from
65  * DOM elements.
66  */

67 public class XmlUtils {
68
69     private static final String JavaDoc PROPERTY_NAME = "name";
70
71     private static final String JavaDoc PROPERTY_VALUE = "value";
72
73     private static final String JavaDoc PROPERTY_REF = "ref";
74
75     public static String JavaDoc getLocalName(Node JavaDoc node) {
76         String JavaDoc name = node.getLocalName();
77         return name != null ? name : node.getNodeName();
78     }
79
80     public static List JavaDoc getChildElements(Element JavaDoc ele) {
81         NodeList JavaDoc nl = ele.getChildNodes();
82         List JavaDoc childEles = new LinkedList JavaDoc();
83         for (int i = 0; i < nl.getLength(); i++) {
84             Node JavaDoc node = nl.item(i);
85             if (node instanceof Element JavaDoc) {
86                 childEles.add(node);
87             }
88         }
89         return childEles;
90     }
91
92     public static List JavaDoc getChildElementsByRegex(Element JavaDoc ele, String JavaDoc pattern) {
93         NodeList JavaDoc nl = ele.getChildNodes();
94         List JavaDoc childEles = new LinkedList JavaDoc();
95         for (int i = 0; i < nl.getLength(); i++) {
96             Node JavaDoc node = nl.item(i);
97             if (node instanceof Element JavaDoc && getLocalName(node).matches(pattern)) {
98                 childEles.add(node);
99             }
100         }
101         return childEles;
102     }
103
104     public static Element JavaDoc getFirstChildElement(Element JavaDoc parent) {
105         Node JavaDoc child = parent.getFirstChild();
106         while (child != null) {
107             if (child instanceof Element JavaDoc) {
108                 return (Element JavaDoc) child;
109             }
110             child = child.getNextSibling();
111         }
112         return null;
113     }
114
115     public static Element JavaDoc getFirstChildByTagName(Element JavaDoc ele, String JavaDoc tagName) {
116         NodeList JavaDoc nl = ele.getChildNodes();
117         for (int i = 0; i < nl.getLength(); i++) {
118             Node JavaDoc node = nl.item(i);
119             if (tagName.equals(getLocalName(node))) {
120                 return (Element JavaDoc) node;
121             }
122         }
123         return null;
124     }
125
126     public static Element JavaDoc getFirstChildByRegex(Element JavaDoc ele, String JavaDoc pattern) {
127         NodeList JavaDoc nl = ele.getChildNodes();
128         for (int i = 0; i < nl.getLength(); i++) {
129             Node JavaDoc node = nl.item(i);
130             if (node instanceof Element JavaDoc && getLocalName(node).matches(pattern)) {
131                 return (Element JavaDoc) node;
132             }
133         }
134         return null;
135     }
136     
137     public static Element JavaDoc getNextSiblingElement(Node JavaDoc node) {
138         node = node.getNextSibling();
139         while (node != null) {
140             if (node.getNodeType() == Node.ELEMENT_NODE) {
141                 return (Element JavaDoc) node;
142             }
143             node = node.getNextSibling();
144         }
145         return null;
146     }
147
148     public static String JavaDoc getAttribute(Element JavaDoc ele, String JavaDoc name) {
149         Assert.hasText(name, "An attribute name must be specified");
150         Attr JavaDoc attr = ele.getAttributeNode(name);
151         return attr != null ? attr.getNodeValue() : null;
152     }
153
154     public static Integer JavaDoc getIntegerAttribute(Element JavaDoc ele, String JavaDoc name) {
155         String JavaDoc s = getAttribute(ele, name);
156         if (s != null) {
157             try {
158                 return new Integer JavaDoc(s);
159             }
160             catch (NumberFormatException JavaDoc e) {
161             }
162         }
163         return null;
164     }
165
166     public static int getIntAttribute(Element JavaDoc ele, String JavaDoc name,
167             int defaultValue) {
168
169         String JavaDoc s = getAttribute(ele, name);
170         if (s != null) {
171             try {
172                 return Integer.parseInt(s);
173             }
174             catch (NumberFormatException JavaDoc e) {
175             }
176         }
177         return defaultValue;
178     }
179
180     public static boolean getBooleanAttribute(Element JavaDoc ele, String JavaDoc name) {
181         String JavaDoc s = getAttribute(ele, name);
182         return Boolean.valueOf(s).booleanValue();
183     }
184
185     public static void populate(Object JavaDoc bean, NamedNodeMap JavaDoc attributes) {
186         BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
187         beanWrapper.setPropertyValues(getPropertyValues(attributes));
188     }
189     
190     public static PropertyValues getPropertyValues(NamedNodeMap JavaDoc attributes) {
191         MutablePropertyValues pvs = new MutablePropertyValues();
192         if (attributes != null) {
193             int length = attributes.getLength();
194             for (int i = 0; i < length; i++) {
195                 Attr JavaDoc attr = (Attr JavaDoc) attributes.item(i);
196                 String JavaDoc property = FormatUtils.xmlToCamelCase(attr.getName());
197                 pvs.addPropertyValue(property, attr.getValue());
198             }
199         }
200         return pvs;
201     }
202
203     public static void populate(Object JavaDoc bean, Element JavaDoc element,
204             String JavaDoc[] attributeNames) {
205
206         populate(bean, element, attributeNames, null);
207     }
208
209     public static void populate(Object JavaDoc bean, Element JavaDoc element,
210             String JavaDoc[] attributeNames, BeanFactory beanFactory) {
211
212         BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
213         beanWrapper.setPropertyValues(getPropertyValues(
214                 element, attributeNames, beanFactory));
215     }
216     
217     public static PropertyValues getPropertyValues(Element JavaDoc element,
218             String JavaDoc[] attributeNames, BeanFactory beanFactory) {
219
220         MutablePropertyValues pvs = new MutablePropertyValues();
221         for (int i = 0; i < attributeNames.length; i++) {
222             PropertyValue pv = getPropertyValue(element,
223                     attributeNames[i], beanFactory);
224             
225             if (pv != null) {
226                 pvs.addPropertyValue(pv);
227             }
228         }
229         return pvs;
230     }
231     
232     public static PropertyValue getPropertyValue(Element JavaDoc element, String JavaDoc attr,
233             BeanFactory beanFactory) {
234
235         String JavaDoc property = null;
236         int i = attr.indexOf('=');
237         if (i != -1) {
238             property = attr.substring(0, i);
239             attr = attr.substring(i + 1);
240         }
241
242         boolean beanRef = attr.charAt(0) == '@';
243         if (beanRef) {
244             Assert.notNull(beanFactory, "A BeanFactory must be passed in " +
245                     "order to resolve references");
246             
247             attr = attr.substring(1);
248         }
249
250         if (property == null) {
251             property = FormatUtils.xmlToCamelCase(attr);
252         }
253
254         String JavaDoc value = element.getAttribute(attr);
255         if (StringUtils.hasLength(value)) {
256             if (beanRef) {
257                 return new PropertyValue(property, beanFactory.getBean(value));
258             }
259             return new PropertyValue(property, value);
260         }
261         return null;
262     }
263
264     public static void populate(Object JavaDoc bean, List JavaDoc elements,
265             BeanFactory beanFactory) {
266
267         BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
268         Iterator JavaDoc it = elements.iterator();
269         while (it.hasNext()) {
270             Element JavaDoc ele = (Element JavaDoc) it.next();
271             String JavaDoc name = getAttribute(ele, PROPERTY_NAME);
272             Object JavaDoc value = getAttribute(ele, PROPERTY_VALUE);
273             if (value == null) {
274                 String JavaDoc beanId = getAttribute(ele, PROPERTY_REF);
275                 if (beanId != null) {
276                     Assert.notNull(beanFactory,
277                             "A BeanFactory must be supplied in order to set " +
278                             "properties by reference.");
279
280                     value = beanFactory.getBean(beanId);
281                 }
282             }
283             beanWrapper.setPropertyValue(name, value);
284         }
285     }
286
287     public static Document JavaDoc createDocument() {
288         DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
289         try {
290             return dbf.newDocumentBuilder().newDocument();
291         }
292         catch (ParserConfigurationException JavaDoc e) {
293             throw new RuntimeException JavaDoc(e);
294         }
295     }
296
297     public static void removeNode(Node JavaDoc node) {
298         if (node != null) {
299             Node JavaDoc parent = node.getParentNode();
300             if (parent != null) {
301                 parent.removeChild(node);
302             }
303         }
304     }
305
306     public static void importAndAppend(Node JavaDoc node, Node JavaDoc parent) {
307         parent.appendChild(parent.getOwnerDocument().importNode(node, true));
308     }
309
310     public static void removeAllChildNodes(Node JavaDoc node) {
311         while (node.hasChildNodes()) {
312             node.removeChild(node.getLastChild());
313         }
314     }
315
316     public static void setTextValue(Element JavaDoc element, String JavaDoc value) {
317         removeAllChildNodes(element);
318         if (value != null) {
319             Node JavaDoc text = element.getOwnerDocument().createTextNode(value);
320             element.appendChild(text);
321         }
322     }
323
324     public static Document JavaDoc parse(String JavaDoc xml) {
325         try {
326             DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
327             dbf.setNamespaceAware(true);
328             DocumentBuilder JavaDoc parser = dbf.newDocumentBuilder();
329             return parser.parse(new InputSource JavaDoc(new StringReader JavaDoc(xml)));
330         }
331         catch (ParserConfigurationException JavaDoc e) {
332             throw new RuntimeException JavaDoc(e);
333         }
334         catch (IOException JavaDoc e) {
335             throw new RuntimeException JavaDoc(e);
336         }
337         catch (SAXException JavaDoc e) {
338             throw new RuntimeException JavaDoc(e);
339         }
340     }
341
342     public static String JavaDoc serialize(Node JavaDoc node) {
343         try {
344             TransformerFactory JavaDoc tf = TransformerFactory.newInstance();
345             Transformer JavaDoc transformer = tf.newTransformer();
346             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
347             Source JavaDoc source = new DOMSource JavaDoc(node);
348             StringWriter JavaDoc sw = new StringWriter JavaDoc();
349             Result JavaDoc result = new StreamResult JavaDoc(sw);
350             transformer.transform(source, result);
351             return sw.toString();
352         }
353         catch (TransformerException JavaDoc e) {
354             throw new RuntimeException JavaDoc(e);
355         }
356     }
357
358 }
359
Popular Tags