001: /* ====================================================================
002: * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
003: *
004: * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
005: *
006: * Redistribution and use in source and binary forms, with or without
007: * modification, are permitted provided that the following conditions
008: * are met:
009: *
010: * 1. Redistributions of source code must retain the above copyright
011: * notice, this list of conditions and the following disclaimer.
012: *
013: * 2. Redistributions in binary form must reproduce the above copyright
014: * notice, this list of conditions and the following disclaimer in
015: * the documentation and/or other materials provided with the
016: * distribution.
017: *
018: * 3. The end-user documentation included with the redistribution,
019: * if any, must include the following acknowledgment:
020: * "This product includes software developed by Jcorporate Ltd.
021: * (http://www.jcorporate.com/)."
022: * Alternately, this acknowledgment may appear in the software itself,
023: * if and wherever such third-party acknowledgments normally appear.
024: *
025: * 4. "Jcorporate" and product names such as "Expresso" must
026: * not be used to endorse or promote products derived from this
027: * software without prior written permission. For written permission,
028: * please contact info@jcorporate.com.
029: *
030: * 5. Products derived from this software may not be called "Expresso",
031: * or other Jcorporate product names; nor may "Expresso" or other
032: * Jcorporate product names appear in their name, without prior
033: * written permission of Jcorporate Ltd.
034: *
035: * 6. No product derived from this software may compete in the same
036: * market space, i.e. framework, without prior written permission
037: * of Jcorporate Ltd. For written permission, please contact
038: * partners@jcorporate.com.
039: *
040: * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
041: * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
042: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
043: * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
044: * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
045: * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
046: * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
047: * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
048: * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
049: * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
050: * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
051: * SUCH DAMAGE.
052: * ====================================================================
053: *
054: * This software consists of voluntary contributions made by many
055: * individuals on behalf of the Jcorporate Ltd. Contributions back
056: * to the project(s) are encouraged when you make modifications.
057: * Please send them to support@jcorporate.com. For more information
058: * on Jcorporate Ltd. and its products, please see
059: * <http://www.jcorporate.com/>.
060: *
061: * Portions of this software are based upon other open source
062: * products and are subject to their respective licenses.
063: */
064:
065: package com.jcorporate.expresso.core.misc;
066:
067: import com.jcorporate.expresso.kernel.util.FastStringBuffer;
068: import org.apache.log4j.Logger;
069: import org.w3c.dom.Document;
070: import org.w3c.dom.NamedNodeMap;
071: import org.w3c.dom.Node;
072: import org.w3c.dom.NodeList;
073: import org.xml.sax.ErrorHandler;
074: import org.xml.sax.InputSource;
075: import org.xml.sax.SAXException;
076: import org.xml.sax.SAXParseException;
077:
078: import javax.xml.parsers.DocumentBuilder;
079: import javax.xml.parsers.DocumentBuilderFactory;
080: import java.io.CharArrayReader;
081:
082: /**
083: * Helper class to parse an xml formatted string and return a document
084: * <p/>
085: * For high performance parsing, roll your own SAX-based parser instead.
086: *
087: * @author Michael Rimov
088: */
089: public class StringDOMParser implements ErrorHandler {
090: static Logger log = Logger
091: .getLogger("expresso.core.misc.StringDOMParser");
092:
093: public StringDOMParser() {
094: }
095:
096: /**
097: * Given an XML formatted string, return a DOM DOCUMENT based upon the
098: * data.
099: *
100: * @param data The string to parse
101: * @return The parsed Document or null if there was an error parsing the
102: * document. (Errors are logged)
103: */
104: public Document parseString(String data) {
105: return parseString(data.toCharArray());
106: }
107:
108: /**
109: * Given an XML formatted character array, return a DOM DOCUMENT based upon the
110: * data.
111: *
112: * @param data The character array to parse
113: * @return The parsed Document or null if there was an error parsing the
114: * document. (Errors are logged)
115: */
116: public Document parseString(char[] data) {
117: try {
118: InputSource inputSource = new InputSource(
119: new CharArrayReader(data));
120: DocumentBuilderFactory dbf = DocumentBuilderFactory
121: .newInstance();
122: dbf.setNamespaceAware(true);
123: dbf.setValidating(false);
124:
125: DocumentBuilder db = dbf.newDocumentBuilder();
126: db.setErrorHandler(this );
127:
128: Document doc = db.parse(inputSource);
129:
130: return doc;
131: } catch (Exception e) {
132: log.error("Error Parsing XML Document.", e);
133:
134: return null;
135: }
136: }
137:
138: //
139: // ErrorHandler methods
140: //
141: /**
142: * Issue a warning on parsing errors
143: *
144: * @param ex A Sax Parse Exception event
145: */
146: public void warning(SAXParseException ex) {
147:
148: log.warn(getLocationString(ex) + ": " + ex.getMessage());
149: }
150:
151: /**
152: * Issue an error
153: *
154: * @param ex A Sax Parse Exception event
155: */
156: public void error(SAXParseException ex) {
157: log.error(getLocationString(ex) + ": " + ex.getMessage());
158: }
159:
160: /**
161: * Fatal error. Used Internally for parsing only
162: *
163: * @param ex A Sax Parse Exception event
164: * @throws SAXException after logging the Parsing Exception
165: */
166: public void fatalError(SAXParseException ex) throws SAXException {
167: log.error(getLocationString(ex) + ": " + ex.getMessage());
168: throw ex;
169: }
170:
171: /**
172: * Returns a string of the location. Used Internally For Parsing Only
173: *
174: * @param ex A Sax Parse Exception event
175: * @return java.lang.String
176: */
177: private String getLocationString(SAXParseException ex) {
178: FastStringBuffer str = new FastStringBuffer(128);
179: String systemId = ex.getSystemId();
180:
181: if (systemId != null) {
182: int index = systemId.lastIndexOf('/');
183:
184: if (index != -1) {
185: systemId = systemId.substring(index + 1);
186: }
187:
188: str.append(systemId);
189: }
190:
191: str.append(':');
192: str.append(ex.getLineNumber());
193: str.append(':');
194: str.append(ex.getColumnNumber());
195:
196: return str.toString();
197: } // getLocationString(SAXParseException):String
198:
199: /**
200: * Dumps the DOM tree to the log. Info logging must be enabled for any output
201: * to appear.
202: *
203: * @param n The document node to dump.
204: */
205: public void dumpDOM(Node n) {
206: if (n == null) {
207: return;
208: }
209:
210: FastStringBuffer fsb = new FastStringBuffer(512);
211: fsb.append('\n');
212: fsb = this .buildDOMString(n, fsb, 0);
213: log.info(fsb.toString());
214: }
215:
216: /**
217: * Recursive helper function
218: *
219: * @param n The document node to dump
220: * @param buffer the fast String Buffer to append it to
221: * @param nestingLevel level the current nesting level in the tree
222: * @return appended FastStringBuffer
223: */
224: private FastStringBuffer buildDOMString(Node n,
225: FastStringBuffer buffer, int nestingLevel) {
226: if (n == null) {
227: return buffer;
228: }
229:
230: //
231: //Log the current node.
232: //
233: buffer.append(this .padWithTabs(nestingLevel));
234: buffer.append("Node ");
235:
236: if (n.getNodeName() != null) {
237: buffer.append("Name= ");
238: buffer.append(n.getNodeName());
239: }
240: if (n.getNodeValue() != null) {
241: buffer.append(" Value= ");
242: buffer.append(n.getNodeValue());
243: }
244:
245: buffer.append('\n');
246: buffer.append(this .padWithTabs(nestingLevel));
247:
248: //
249: //Log any attributes
250: //
251: NamedNodeMap nm = n.getAttributes();
252:
253: if (nm != null) {
254: buffer.append("Attributes: ");
255:
256: for (int i = 0; i < nm.getLength(); i++) {
257: Node temp = nm.item(i);
258: buffer.append(temp.getNodeName() + "=");
259: buffer.append(temp.getNodeValue() + " ");
260: }
261: } else {
262: buffer.append("<No Attributes>");
263: }
264:
265: buffer.append('\n');
266:
267: //
268: //Recurse through all the children
269: //
270: NodeList nl = n.getChildNodes();
271:
272: if (nl == null) {
273: return buffer;
274: }
275:
276: buffer.append(this .padWithTabs(nestingLevel));
277:
278: for (int i = 0; i < nl.getLength(); i++) {
279: buffer = buildDOMString(nl.item(i), buffer,
280: nestingLevel + 1);
281: }
282:
283: buffer.append('\n');
284:
285: return buffer;
286: }
287:
288: private String padWithTabs(int numTabs) {
289: FastStringBuffer fsb = new FastStringBuffer(numTabs);
290:
291: for (int i = 0; i < numTabs; i++) {
292: fsb.append('\t');
293: }
294:
295: return fsb.toString();
296: }
297: }
|