001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036:
037: /* $Id: StAXEventConnector.java,v 1.6.2.1 2007/05/31 21:59:56 ofung Exp $
038: *
039: * Copyright (c) 2004, Sun Microsystems, Inc.
040: * All rights reserved.
041: *
042: * Redistribution and use in source and binary forms, with or without
043: * modification, are permitted provided that the following conditions are
044: * met:
045: *
046: * * Redistributions of source code must retain the above copyright
047: * notice, this list of conditions and the following disclaimer.
048: *
049: * * Redistributions in binary form must reproduce the above
050: * copyright notice, this list of conditions and the following
051: * disclaimer in the documentation and/or other materials provided
052: * with the distribution.
053: *
054: * * Neither the name of Sun Microsystems, Inc. nor the names of its
055: * contributors may be used to endorse or promote products derived
056: * from this software without specific prior written permission.
057: *
058: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
059: * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
060: * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
061: * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
062: * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
063: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
064: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
065: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
066: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
067: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
068: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
069: */
070: package com.sun.xml.bind.v2.runtime.unmarshaller;
071:
072: import java.util.Iterator;
073:
074: import javax.xml.namespace.QName;
075: import javax.xml.stream.Location;
076: import javax.xml.stream.XMLEventReader;
077: import javax.xml.stream.XMLStreamConstants;
078: import javax.xml.stream.XMLStreamException;
079: import javax.xml.stream.events.Attribute;
080: import javax.xml.stream.events.Characters;
081: import javax.xml.stream.events.EndElement;
082: import javax.xml.stream.events.Namespace;
083: import javax.xml.stream.events.StartElement;
084: import javax.xml.stream.events.XMLEvent;
085:
086: import org.xml.sax.Attributes;
087: import org.xml.sax.SAXException;
088: import org.xml.sax.helpers.AttributesImpl;
089:
090: /**
091: * This is a simple utility class that adapts StAX events from an
092: * {@link XMLEventReader} to unmarshaller events on a
093: * {@link XmlVisitor}, bridging between the two
094: * parser technologies.
095: *
096: * @author Ryan.Shoemaker@Sun.COM
097: * @version 1.0
098: */
099: final class StAXEventConnector extends StAXConnector {
100:
101: // StAX event source
102: private final XMLEventReader staxEventReader;
103:
104: /** Current event. */
105: private XMLEvent event;
106:
107: /**
108: * Shared and reused {@link Attributes}.
109: */
110: private final AttributesImpl attrs = new AttributesImpl();
111:
112: /**
113: * SAX may fire consective characters event, but we don't allow it.
114: * so use this buffer to perform buffering.
115: */
116: private final StringBuilder buffer = new StringBuilder();
117:
118: private boolean seenText;
119:
120: /**
121: * Construct a new StAX to SAX adapter that will convert a StAX event
122: * stream into a SAX event stream.
123: *
124: * @param staxCore
125: * StAX event source
126: * @param visitor
127: * sink
128: */
129: public StAXEventConnector(XMLEventReader staxCore,
130: XmlVisitor visitor) {
131: super (visitor);
132: staxEventReader = staxCore;
133: }
134:
135: public void bridge() throws XMLStreamException {
136:
137: try {
138: // remembers the nest level of elements to know when we are done.
139: int depth = 0;
140:
141: event = staxEventReader.peek();
142:
143: if (!event.isStartDocument() && !event.isStartElement())
144: throw new IllegalStateException();
145:
146: // if the parser is on START_DOCUMENT, skip ahead to the first element
147: do {
148: event = staxEventReader.nextEvent();
149: } while (!event.isStartElement());
150:
151: handleStartDocument(event.asStartElement()
152: .getNamespaceContext());
153:
154: OUTER: while (true) {
155: // These are all of the events listed in the javadoc for
156: // XMLEvent.
157: // The spec only really describes 11 of them.
158: switch (event.getEventType()) {
159: case XMLStreamConstants.START_ELEMENT:
160: handleStartElement(event.asStartElement());
161: depth++;
162: break;
163: case XMLStreamConstants.END_ELEMENT:
164: depth--;
165: handleEndElement(event.asEndElement());
166: if (depth == 0)
167: break OUTER;
168: break;
169: case XMLStreamConstants.CHARACTERS:
170: case XMLStreamConstants.CDATA:
171: case XMLStreamConstants.SPACE:
172: handleCharacters(event.asCharacters());
173: break;
174: }
175:
176: event = staxEventReader.nextEvent();
177: }
178:
179: handleEndDocument();
180: event = null; // avoid keeping a stale reference
181: } catch (SAXException e) {
182: throw new XMLStreamException(e);
183: }
184: }
185:
186: protected Location getCurrentLocation() {
187: return event.getLocation();
188: }
189:
190: protected String getCurrentQName() {
191: QName qName;
192: if (event.isEndElement())
193: qName = event.asEndElement().getName();
194: else
195: qName = event.asStartElement().getName();
196: return getQName(qName.getPrefix(), qName.getLocalPart());
197: }
198:
199: private void handleCharacters(Characters event)
200: throws SAXException, XMLStreamException {
201: if (!predictor.expectText())
202: return; // text isn't expected. simply skip
203:
204: seenText = true;
205:
206: // check the next event
207: XMLEvent next;
208: while (true) {
209: next = staxEventReader.peek();
210: if (!isIgnorable(next))
211: break;
212: staxEventReader.nextEvent();
213: }
214:
215: if (isTag(next)) {
216: // this is by far the common case --- you have <foo>abc</foo> or <foo>abc<bar/>...</foo>
217: visitor.text(event.getData());
218: return;
219: }
220:
221: // otherwise we have things like "abc<!-- test -->def".
222: // concatenate all text
223: buffer.append(event.getData());
224:
225: while (true) {
226: while (true) {
227: next = staxEventReader.peek();
228: if (!isIgnorable(next))
229: break;
230: staxEventReader.nextEvent();
231: }
232:
233: if (isTag(next)) {
234: // found all adjacent text
235: visitor.text(buffer);
236: buffer.setLength(0);
237: return;
238: }
239:
240: buffer.append(next.asCharacters().getData());
241: staxEventReader.nextEvent(); // consume
242: }
243: }
244:
245: private boolean isTag(XMLEvent event) {
246: int eventType = event.getEventType();
247: return eventType == XMLEvent.START_ELEMENT
248: || eventType == XMLEvent.END_ELEMENT;
249: }
250:
251: private boolean isIgnorable(XMLEvent event) {
252: int eventType = event.getEventType();
253: return eventType == XMLEvent.COMMENT
254: || eventType == XMLEvent.PROCESSING_INSTRUCTION;
255: }
256:
257: private void handleEndElement(EndElement event) throws SAXException {
258: if (!seenText && predictor.expectText()) {
259: visitor.text("");
260: }
261:
262: // fire endElement
263: QName qName = event.getName();
264: tagName.uri = fixNull(qName.getNamespaceURI());
265: tagName.local = qName.getLocalPart();
266: visitor.endElement(tagName);
267:
268: // end namespace bindings
269: for (Iterator<Namespace> i = event.getNamespaces(); i.hasNext();) {
270: String prefix = fixNull(i.next().getPrefix()); // be defensive
271: visitor.endPrefixMapping(prefix);
272: }
273:
274: seenText = false;
275: }
276:
277: private void handleStartElement(StartElement event)
278: throws SAXException {
279: // start namespace bindings
280: for (Iterator i = event.getNamespaces(); i.hasNext();) {
281: Namespace ns = (Namespace) i.next();
282: visitor.startPrefixMapping(fixNull(ns.getPrefix()),
283: fixNull(ns.getNamespaceURI()));
284: }
285:
286: // fire startElement
287: QName qName = event.getName();
288: tagName.uri = fixNull(qName.getNamespaceURI());
289: String localName = qName.getLocalPart();
290: tagName.uri = fixNull(qName.getNamespaceURI());
291: tagName.local = localName;
292: tagName.atts = getAttributes(event);
293: visitor.startElement(tagName);
294:
295: seenText = false;
296: }
297:
298: /**
299: * Get the attributes associated with the given START_ELEMENT StAXevent.
300: *
301: * @return the StAX attributes converted to an org.xml.sax.Attributes
302: */
303: private Attributes getAttributes(StartElement event) {
304: attrs.clear();
305:
306: // in SAX, namespace declarations are not part of attributes by default.
307: // (there's a property to control that, but as far as we are concerned
308: // we don't use it.) So don't add xmlns:* to attributes.
309:
310: // gather non-namespace attrs
311: for (Iterator i = event.getAttributes(); i.hasNext();) {
312: Attribute staxAttr = (Attribute) i.next();
313:
314: QName name = staxAttr.getName();
315: String uri = fixNull(name.getNamespaceURI());
316: String localName = name.getLocalPart();
317: String prefix = name.getPrefix();
318: String qName;
319: if (prefix == null || prefix.length() == 0)
320: qName = localName;
321: else
322: qName = prefix + ':' + localName;
323: String type = staxAttr.getDTDType();
324: String value = staxAttr.getValue();
325:
326: attrs.addAttribute(uri, localName, qName, type, value);
327: }
328:
329: return attrs;
330: }
331: }
|