001: /*
002: * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
003: *
004: * This file is part of Resin(R) Open Source
005: *
006: * Each copy or derived work must preserve the copyright notice and this
007: * notice unmodified.
008: *
009: * Resin Open Source is free software; you can redistribute it and/or modify
010: * it under the terms of the GNU General Public License as published by
011: * the Free Software Foundation; either version 2 of the License, or
012: * (at your option) any later version.
013: *
014: * Resin Open Source is distributed in the hope that it will be useful,
015: * but WITHOUT ANY WARRANTY; without even the implied warranty of
016: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
017: * of NON-INFRINGEMENT. See the GNU General Public License for more
018: * details.
019: *
020: * You should have received a copy of the GNU General Public License
021: * along with Resin Open Source; if not, write to the
022: * Free SoftwareFoundation, Inc.
023: * 59 Temple Place, Suite 330
024: * Boston, MA 02111-1307 USA
025: *
026: * @author Scott Ferguson
027: */
028:
029: package com.caucho.xml;
030:
031: import com.caucho.log.Log;
032: import com.caucho.util.CharBuffer;
033: import com.caucho.util.L10N;
034:
035: import org.w3c.dom.*;
036: import org.xml.sax.Attributes;
037: import org.xml.sax.ContentHandler;
038: import org.xml.sax.ErrorHandler;
039: import org.xml.sax.Locator;
040: import org.xml.sax.SAXException;
041: import org.xml.sax.SAXParseException;
042:
043: import java.io.IOException;
044: import java.util.ArrayList;
045: import java.util.logging.Level;
046: import java.util.logging.Logger;
047:
048: /**
049: * XMLWriter to create a DOM document.
050: */
051: public class DOMBuilder implements XMLWriter, ContentHandler,
052: ErrorHandler {
053: static final Logger log = Log.open(DOMBuilder.class);
054: static final L10N L = new L10N(DOMBuilder.class);
055: static final String XMLNS = XmlParser.XMLNS;
056:
057: private QDocument _doc;
058: private Node _top;
059: private Node _node;
060:
061: private String _singleText;
062: private CharBuffer _text = new CharBuffer();
063:
064: private boolean _escapeText;
065: private boolean _strictXml;
066:
067: // If true, text and cdata sections should be combined.
068: private boolean _isCoalescing = true;
069: // If true, ignorable whitespace is skipped
070: private boolean _skipWhitespace = false;
071:
072: private ArrayList<QName> _prefixNames = new ArrayList<QName>();
073: private ArrayList<String> _prefixValues = new ArrayList<String>();
074:
075: private Locator _locator;
076: private ExtendedLocator _extLocator;
077: private String _systemId;
078:
079: public DOMBuilder() {
080: }
081:
082: public void init(Node top) {
083: if (top instanceof QDocument)
084: _doc = (QDocument) top;
085: else
086: _doc = (QDocument) top.getOwnerDocument();
087: _top = top;
088: _node = top;
089:
090: _singleText = null;
091:
092: _prefixNames.clear();
093: _prefixValues.clear();
094: }
095:
096: public void setSystemId(String systemId) {
097: _systemId = systemId;
098:
099: if (systemId != null && _top instanceof Document) {
100: Document tdoc = (Document) _top;
101: DocumentType dtd = tdoc.getDoctype();
102: if (tdoc instanceof QDocument && dtd == null) {
103: dtd = new QDocumentType(null);
104: ((QDocument) tdoc).setDoctype(dtd);
105: }
106:
107: if (dtd instanceof QDocumentType
108: && dtd.getSystemId() == null)
109: ((QDocumentType) dtd).setSystemId(systemId);
110: }
111:
112: if (_doc != null)
113: _doc.setSystemId(systemId);
114: }
115:
116: public String getSystemId() {
117: return _systemId;
118: }
119:
120: public void setFilename(String filename) {
121: if (filename != null && _top instanceof QDocument) {
122: _doc.setRootFilename(filename);
123: }
124: }
125:
126: /**
127: * Set true if we're only handling strict xml.
128: */
129: public void setStrictXML(boolean isStrictXml) {
130: _strictXml = isStrictXml;
131: }
132:
133: /**
134: * Set true if text and cdata nodes should be combined.
135: */
136: public void setCoalescing(boolean isCoalescing) {
137: _isCoalescing = isCoalescing;
138: }
139:
140: /**
141: * Set true if ignorable whitespace should be skipped.
142: */
143: public void setSkipWhitespace(boolean skipWhitespace) {
144: _skipWhitespace = skipWhitespace;
145: }
146:
147: public void setDocumentLocator(Locator loc) {
148: if (_doc == null) {
149: _doc = new QDocument();
150: _node = _doc;
151: _top = _doc;
152: }
153:
154: _locator = loc;
155:
156: if (loc instanceof ExtendedLocator)
157: _extLocator = (ExtendedLocator) loc;
158:
159: if (_extLocator != null && _doc.getSystemId() == null)
160: _doc.setLocation(_extLocator.getSystemId(), _extLocator
161: .getFilename(), _extLocator.getLineNumber(),
162: _extLocator.getColumnNumber());
163: }
164:
165: public void startPrefixMapping(String prefix, String url) {
166: if (_node == null || _node == _top)
167: _doc.addNamespace(prefix, url);
168:
169: if (prefix == null || prefix.equals("")) {
170: _prefixNames.add(new QName(null, "xmlns", XmlParser.XMLNS));
171: _prefixValues.add(url);
172: } else {
173: _prefixNames
174: .add(new QName("xmlns", prefix, XmlParser.XMLNS));
175: _prefixValues.add(url);
176: }
177: }
178:
179: public void endPrefixMapping(String prefix) {
180: }
181:
182: public Node getNode() {
183: return _top;
184: }
185:
186: public void startDocument() {
187: if (_doc == null) {
188: _doc = new QDocument();
189: _node = _doc;
190: _top = _doc;
191: }
192: }
193:
194: public void endDocument() throws SAXException {
195: popText();
196: }
197:
198: public void setLocation(String filename, int line, int column) {
199: }
200:
201: public void startElement(String uri, String localName, String qName)
202: throws IOException {
203: popText();
204:
205: Element elt;
206:
207: if (uri != null && !uri.equals(""))
208: elt = _doc.createElementNS(uri, qName);
209: else if (!qName.equals(""))
210: elt = _doc.createElement(qName);
211: else
212: elt = _doc.createElement(localName);
213:
214: if (_node == _doc) {
215: if (_doc.getDocumentElement() == null)
216: ((QDocument) _doc).setDocumentElement(elt);
217: }
218:
219: _node.appendChild(elt);
220: _node = elt;
221:
222: if (_extLocator != null && elt instanceof QElement) {
223: ((QElement) elt).setLocation(_extLocator.getSystemId(),
224: _extLocator.getFilename(), _extLocator
225: .getLineNumber(), _extLocator
226: .getColumnNumber());
227: }
228: }
229:
230: public void startElement(QName name, QAttributes attributes)
231: throws SAXException {
232: popText();
233:
234: QElement elt = (QElement) _doc.createElementByName(name);
235: _node.appendChild(elt);
236: _node = elt;
237:
238: if (_node == _doc) {
239: if (_doc.getDocumentElement() == null)
240: ((QDocument) _doc).setDocumentElement(elt);
241: }
242:
243: for (int i = 0; i < _prefixNames.size(); i++) {
244: QName attrName = _prefixNames.get(i);
245: String value = _prefixValues.get(i);
246:
247: elt.setAttribute(attrName, value);
248: }
249:
250: _prefixNames.clear();
251: _prefixValues.clear();
252:
253: int length = attributes.getLength();
254: for (int i = 0; i < length; i++) {
255: QName attrName = attributes.getName(i);
256: String value = attributes.getValue(i);
257:
258: elt.setAttribute(attrName, value);
259: }
260:
261: if (_extLocator != null) {
262: elt.setLocation(_extLocator.getSystemId(), _extLocator
263: .getFilename(), _extLocator.getLineNumber(),
264: _extLocator.getColumnNumber());
265: }
266:
267: QDocumentType dtd = (QDocumentType) _doc.getDoctype();
268: if (dtd != null)
269: dtd.fillDefaults(elt);
270: }
271:
272: public void startElement(String uri, String localName,
273: String qName, Attributes attributes) throws SAXException {
274: popText();
275:
276: Element elt;
277:
278: if (uri != null && !uri.equals(""))
279: elt = _doc.createElementNS(uri, qName);
280: else if (!qName.equals(""))
281: elt = _doc.createElement(qName);
282: else
283: elt = _doc.createElement(localName);
284:
285: if (_node == _doc) {
286: if (_doc.getDocumentElement() == null)
287: ((QDocument) _doc).setDocumentElement(elt);
288: else if (_strictXml)
289: throw error(L.l(
290: "expected a single top-level element at `{0}'",
291: qName));
292: }
293:
294: _node.appendChild(elt);
295: _node = elt;
296:
297: int length = attributes.getLength();
298: for (int i = 0; i < length; i++) {
299: String attrUri = attributes.getURI(i);
300: String attrQname = attributes.getQName(i);
301: String value = attributes.getValue(i);
302:
303: Attr attr;
304:
305: if (attrUri != null && !attrUri.equals(""))
306: attr = _doc.createAttributeNS(attrUri, attrQname);
307: else if (!attrQname.equals(""))
308: attr = _doc.createAttribute(attrQname);
309: else
310: attr = _doc.createAttribute(attributes.getLocalName(i));
311:
312: attr.setNodeValue(value);
313:
314: ((Element) _node).setAttributeNode(attr);
315: }
316:
317: if (_extLocator != null)
318: ((QElement) elt).setLocation(_extLocator.getSystemId(),
319: _extLocator.getFilename(), _extLocator
320: .getLineNumber(), _extLocator
321: .getColumnNumber());
322:
323: QDocumentType dtd = (QDocumentType) _doc.getDoctype();
324: if (dtd != null) {
325: dtd.fillDefaults((QElement) elt);
326: }
327: }
328:
329: public void dtd(QDocumentType dtd) {
330: ((QDocument) _doc).setDoctype(dtd);
331:
332: ((QDocument) _doc).appendChild(dtd);
333: }
334:
335: public void attribute(String uri, String localName, String qName,
336: String value) throws IOException {
337: if (_node instanceof Element) {
338: Attr attr = _doc.createAttributeNS(uri, qName);
339: attr.setNodeValue(value);
340:
341: ((Element) _node).setAttributeNode(attr);
342: } else
343: ((QDocument) _node).setAttribute(qName, value);
344: }
345:
346: public void endElement(String uri, String localName, String qName) {
347: popText();
348:
349: if (_node != null) // XXX:
350: _node = _node.getParentNode();
351: if (_node == null)
352: _node = _doc;
353: }
354:
355: public void processingInstruction(String name, String data) {
356: popText();
357:
358: ProcessingInstruction pi = _doc.createProcessingInstruction(
359: name, data);
360:
361: _node.appendChild(pi);
362: }
363:
364: /**
365: * Handles the callback for a comment.
366: *
367: * @param data the content of the comment.
368: */
369: public void comment(char[] buf, int offset, int length)
370: throws SAXException {
371: try {
372: comment(new String(buf, offset, length));
373: } catch (IOException e) {
374: throw new SAXException(e);
375: }
376: }
377:
378: /**
379: * Handles the callback for a comment.
380: *
381: * @param data the content of the comment.
382: */
383: public void comment(String data) throws IOException {
384: popText();
385:
386: Comment comment = _doc.createComment(data);
387:
388: _node.appendChild(comment);
389: }
390:
391: public boolean getEscapeText() {
392: return _escapeText;
393: }
394:
395: public void setEscapeText(boolean isEscaped) {
396: _escapeText = isEscaped;
397: }
398:
399: public void text(String text) throws IOException {
400: if (_singleText == null && _text.length() == 0) {
401: if (!text.equals(""))
402: _singleText = text;
403: } else if (_singleText != null) {
404: _text.append(_singleText);
405: _text.append(text);
406: } else
407: _text.append(text);
408:
409: if (!_isCoalescing)
410: popText();
411: }
412:
413: public void text(char[] buffer, int offset, int length)
414: throws IOException {
415: if (length == 0)
416: return;
417:
418: if (_singleText != null) {
419: _singleText = null;
420: _text.append(_singleText);
421: }
422: _text.append(buffer, offset, length);
423:
424: if (!_isCoalescing)
425: popText();
426: }
427:
428: /**
429: * Adds text characters to the current document.
430: */
431: public void characters(char[] buffer, int offset, int length)
432: throws SAXException {
433: if (length == 0)
434: return;
435:
436: if (_strictXml && _node == _doc) {
437: if (_doc.getDocumentElement() == null) {
438: while (length > 0
439: && XmlChar.isWhitespace(buffer[offset])) {
440: offset++;
441: length--;
442: }
443:
444: for (int i = 0; i < length; i++) {
445: if (buffer[offset + i] == '\n'
446: || buffer[offset + i] == '\r') {
447: length = i;
448: break;
449: }
450: }
451:
452: if (length > 16)
453: length = 16;
454:
455: if (length > 0)
456: throw error(L.l("expected top element at `{0}'",
457: new String(buffer, offset, length)));
458: }
459: }
460:
461: _text.append(buffer, offset, length);
462:
463: /*
464: if (! isCoalescing)
465: popText();
466: */
467: }
468:
469: /**
470: * Handles the callback for ignorable whitespace.
471: *
472: * @param buffer the character buffer containing the whitespace.
473: * @param offset starting offset into the character buffer.
474: * @param length number of characters in the buffer.
475: */
476: public void ignorableWhitespace(char[] buffer, int offset,
477: int length) throws SAXException {
478: if (!_skipWhitespace)
479: characters(buffer, offset, length);
480: }
481:
482: public void entityReference(String name) {
483: popText();
484:
485: QEntityReference er = new QEntityReference(name);
486: er._owner = (QDocument) _doc;
487:
488: _node.appendChild(er);
489: }
490:
491: public void skippedEntity(String s) {
492: _text.append(s);
493: }
494:
495: public void cdata(String text) throws IOException {
496: popText();
497:
498: _node.appendChild(_doc.createCDATASection(text));
499: }
500:
501: public void cdata(char[] buffer, int offset, int length)
502: throws IOException {
503: cdata(new String(buffer, offset, length));
504: }
505:
506: private void popText() {
507: if (_singleText != null) {
508: Node text = _doc.createTextNode(_singleText);
509: _node.appendChild(text);
510:
511: _singleText = null;
512: return;
513: }
514:
515: if (_text.length() == 0)
516: return;
517:
518: Node text = _doc.createTextNode(_text.toString());
519: _text.clear();
520:
521: _node.appendChild(text);
522: }
523:
524: public void fatalError(SAXParseException e) throws SAXException {
525: log.log(Level.FINE, e.toString(), e);
526:
527: throw error(e.getMessage());
528: }
529:
530: public void error(SAXParseException e) throws SAXException {
531: log.log(Level.FINER, e.toString(), e);
532:
533: throw error(e.getMessage());
534: }
535:
536: public void warning(SAXParseException e) throws SAXException {
537: log.log(Level.FINER, e.toString(), e);
538: }
539:
540: /**
541: * Throws an appropriate error.
542: */
543: public SAXException createError(Exception e) {
544: if (e instanceof SAXException)
545: return (SAXException) e;
546: else
547: return new SAXException(e);
548: }
549:
550: /**
551: * Returns a new parse exception with filename and line if available.
552: */
553: XmlParseException error(String text) {
554: String loc = "";
555:
556: if (_extLocator != null) {
557: return new XmlParseException(_extLocator.getFilename(),
558: _extLocator.getLineNumber(), text);
559: } else if (_locator != null) {
560: return new XmlParseException(_locator.getSystemId(),
561: _locator.getLineNumber(), text);
562: }
563:
564: return new XmlParseException(text);
565: }
566: }
|