KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > misc > StringDOMParser


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.core.misc;
66
67 import com.jcorporate.expresso.kernel.util.FastStringBuffer;
68 import org.apache.log4j.Logger;
69 import org.w3c.dom.Document JavaDoc;
70 import org.w3c.dom.NamedNodeMap JavaDoc;
71 import org.w3c.dom.Node JavaDoc;
72 import org.w3c.dom.NodeList JavaDoc;
73 import org.xml.sax.ErrorHandler JavaDoc;
74 import org.xml.sax.InputSource JavaDoc;
75 import org.xml.sax.SAXException JavaDoc;
76 import org.xml.sax.SAXParseException JavaDoc;
77
78 import javax.xml.parsers.DocumentBuilder JavaDoc;
79 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
80 import java.io.CharArrayReader JavaDoc;
81
82
83 /**
84  * Helper class to parse an xml formatted string and return a document
85  * <p/>
86  * For high performance parsing, roll your own SAX-based parser instead.
87  *
88  * @author Michael Rimov
89  */

90 public class StringDOMParser
91         implements ErrorHandler JavaDoc {
92     static Logger log = Logger.getLogger("expresso.core.misc.StringDOMParser");
93
94     public StringDOMParser() {
95     }
96
97     /**
98      * Given an XML formatted string, return a DOM DOCUMENT based upon the
99      * data.
100      *
101      * @param data The string to parse
102      * @return The parsed Document or null if there was an error parsing the
103      * document. (Errors are logged)
104      */

105     public Document JavaDoc parseString(String JavaDoc data) {
106         return parseString(data.toCharArray());
107     }
108
109     /**
110      * Given an XML formatted character array, return a DOM DOCUMENT based upon the
111      * data.
112      *
113      * @param data The character array to parse
114      * @return The parsed Document or null if there was an error parsing the
115      * document. (Errors are logged)
116      */

117     public Document JavaDoc parseString(char[] data) {
118         try {
119             InputSource JavaDoc inputSource = new InputSource JavaDoc(new CharArrayReader JavaDoc(data));
120             DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
121             dbf.setNamespaceAware(true);
122             dbf.setValidating(false);
123
124             DocumentBuilder JavaDoc db = dbf.newDocumentBuilder();
125             db.setErrorHandler(this);
126
127             Document JavaDoc doc = db.parse(inputSource);
128
129             return doc;
130         } catch (Exception JavaDoc e) {
131             log.error("Error Parsing XML Document.", e);
132
133             return null;
134         }
135     }
136     //
137
// ErrorHandler methods
138
//
139
/**
140      * Issue a warning on parsing errors
141      *
142      * @param ex A Sax Parse Exception event
143      */

144     public void warning(SAXParseException JavaDoc ex) {
145
146         log.warn(getLocationString(ex) + ": " + ex.getMessage());
147     }
148
149     /**
150      * Issue an error
151      *
152      * @param ex A Sax Parse Exception event
153      */

154     public void error(SAXParseException JavaDoc ex) {
155         log.error(getLocationString(ex) + ": " + ex.getMessage());
156     }
157
158     /**
159      * Fatal error. Used Internally for parsing only
160      *
161      * @param ex A Sax Parse Exception event
162      * @throws SAXException after logging the Parsing Exception
163      */

164     public void fatalError(SAXParseException JavaDoc ex)
165             throws SAXException JavaDoc {
166         log.error(getLocationString(ex) + ": " + ex.getMessage());
167         throw ex;
168     }
169
170     /**
171      * Returns a string of the location. Used Internally For Parsing Only
172      *
173      * @param ex A Sax Parse Exception event
174      * @return java.lang.String
175      */

176     private String JavaDoc getLocationString(SAXParseException JavaDoc ex) {
177         FastStringBuffer str = new FastStringBuffer(128);
178         String JavaDoc systemId = ex.getSystemId();
179
180         if (systemId != null) {
181             int index = systemId.lastIndexOf('/');
182
183             if (index != -1) {
184                 systemId = systemId.substring(index + 1);
185             }
186
187             str.append(systemId);
188         }
189
190         str.append(':');
191         str.append(ex.getLineNumber());
192         str.append(':');
193         str.append(ex.getColumnNumber());
194
195         return str.toString();
196     } // getLocationString(SAXParseException):String
197

198     /**
199      * Dumps the DOM tree to the log. Info logging must be enabled for any output
200      * to appear.
201      *
202      * @param n The document node to dump.
203      */

204     public void dumpDOM(Node JavaDoc n) {
205         if (n == null) {
206             return;
207         }
208
209         FastStringBuffer fsb = new FastStringBuffer(512);
210         fsb.append('\n');
211         fsb = this.buildDOMString(n, fsb, 0);
212         log.info(fsb.toString());
213     }
214
215     /**
216      * Recursive helper function
217      *
218      * @param n The document node to dump
219      * @param buffer the fast String Buffer to append it to
220      * @param nestingLevel level the current nesting level in the tree
221      * @return appended FastStringBuffer
222      */

223     private FastStringBuffer buildDOMString(Node JavaDoc n, FastStringBuffer buffer,
224                                             int nestingLevel) {
225         if (n == null) {
226             return buffer;
227         }
228
229         //
230
//Log the current node.
231
//
232
buffer.append(this.padWithTabs(nestingLevel));
233         buffer.append("Node ");
234
235         if (n.getNodeName() != null) {
236             buffer.append("Name= ");
237             buffer.append(n.getNodeName());
238         }
239         if (n.getNodeValue() != null) {
240             buffer.append(" Value= ");
241             buffer.append(n.getNodeValue());
242         }
243
244         buffer.append('\n');
245         buffer.append(this.padWithTabs(nestingLevel));
246
247         //
248
//Log any attributes
249
//
250
NamedNodeMap JavaDoc nm = n.getAttributes();
251
252         if (nm != null) {
253             buffer.append("Attributes: ");
254
255             for (int i = 0; i < nm.getLength(); i++) {
256                 Node JavaDoc temp = nm.item(i);
257                 buffer.append(temp.getNodeName() + "=");
258                 buffer.append(temp.getNodeValue() + " ");
259             }
260         } else {
261             buffer.append("<No Attributes>");
262         }
263
264         buffer.append('\n');
265
266         //
267
//Recurse through all the children
268
//
269
NodeList JavaDoc nl = n.getChildNodes();
270
271         if (nl == null) {
272             return buffer;
273         }
274
275         buffer.append(this.padWithTabs(nestingLevel));
276
277         for (int i = 0; i < nl.getLength(); i++) {
278             buffer = buildDOMString(nl.item(i), buffer, nestingLevel + 1);
279         }
280
281         buffer.append('\n');
282
283         return buffer;
284     }
285
286     private String JavaDoc padWithTabs(int numTabs) {
287         FastStringBuffer fsb = new FastStringBuffer(numTabs);
288
289         for (int i = 0; i < numTabs; i++) {
290             fsb.append('\t');
291         }
292
293         return fsb.toString();
294     }
295 }
Popular Tags