KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > xml > bind > helpers > AbstractUnmarshallerImpl


1 /*
2  * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
3  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4  */

5 package javax.xml.bind.helpers;
6
7 import org.xml.sax.InputSource JavaDoc;
8 import org.xml.sax.SAXException JavaDoc;
9 import org.xml.sax.XMLReader JavaDoc;
10 import org.w3c.dom.Node JavaDoc;
11
12 import javax.xml.bind.JAXBException;
13 import javax.xml.bind.PropertyException;
14 import javax.xml.bind.UnmarshalException;
15 import javax.xml.bind.Unmarshaller;
16 import javax.xml.bind.ValidationEventHandler;
17 import javax.xml.bind.JAXBElement;
18 import javax.xml.bind.annotation.adapters.XmlAdapter;
19 import javax.xml.bind.attachment.AttachmentUnmarshaller;
20 import javax.xml.parsers.ParserConfigurationException JavaDoc;
21 import javax.xml.parsers.SAXParserFactory JavaDoc;
22 import javax.xml.stream.XMLEventReader;
23 import javax.xml.stream.XMLStreamReader;
24 import javax.xml.transform.Source JavaDoc;
25 import javax.xml.transform.dom.DOMSource JavaDoc;
26 import javax.xml.transform.sax.SAXSource JavaDoc;
27 import javax.xml.transform.stream.StreamSource JavaDoc;
28 import javax.xml.validation.Schema JavaDoc;
29 import java.io.File JavaDoc;
30 import java.io.Reader JavaDoc;
31 import java.net.MalformedURLException JavaDoc;
32 import java.net.URL JavaDoc;
33
34 /**
35  * Partial default <tt>Unmarshaller</tt> implementation.
36  *
37  * <p>
38  * This class provides a partial default implementation for the
39  * {@link javax.xml.bind.Unmarshaller}interface.
40  *
41  * <p>
42  * A JAXB Provider has to implement five methods (getUnmarshallerHandler,
43  * unmarshal(Node), unmarshal(XMLReader,InputSource),
44  * unmarshal(XMLStreamReader), and unmarshal(XMLEventReader).
45  *
46  * @author <ul>
47  * <li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li>
48  * </ul>
49  * @version $Revision: 1.13 $ $Date: 2005/07/28 22:18:12 $
50  * @see javax.xml.bind.Unmarshaller
51  * @since JAXB1.0
52  */

53 public abstract class AbstractUnmarshallerImpl implements Unmarshaller
54 {
55     /** handler that will be used to process errors and warnings during unmarshal */
56     private ValidationEventHandler eventHandler =
57         new DefaultValidationEventHandler();
58     
59     /** whether or not the unmarshaller will validate */
60     protected boolean validating = false;
61
62     /**
63      * XMLReader that will be used to parse a document.
64      */

65     private XMLReader JavaDoc reader = null;
66
67     /**
68      * Obtains a configured XMLReader.
69      *
70      * This method is used when the client-specified
71      * {@link SAXSource} object doesn't have XMLReader.
72      *
73      * {@link Unmarshaller} is not re-entrant, so we will
74      * only use one instance of XMLReader.
75      */

76     protected XMLReader JavaDoc getXMLReader() throws JAXBException {
77         if(reader==null) {
78             try {
79                 SAXParserFactory JavaDoc parserFactory;
80                 parserFactory = SAXParserFactory.newInstance();
81                 parserFactory.setNamespaceAware(true);
82                 // there is no point in asking a validation because
83
// there is no guarantee that the document will come with
84
// a proper schemaLocation.
85
parserFactory.setValidating(false);
86                 reader = parserFactory.newSAXParser().getXMLReader();
87             } catch( ParserConfigurationException JavaDoc e ) {
88                 throw new JAXBException(e);
89             } catch( SAXException JavaDoc e ) {
90                 throw new JAXBException(e);
91             }
92         }
93         return reader;
94     }
95     
96     public Object JavaDoc unmarshal( Source JavaDoc source ) throws JAXBException {
97         if( source == null ) {
98             throw new IllegalArgumentException JavaDoc(
99                 Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
100         }
101         
102         if(source instanceof SAXSource JavaDoc)
103             return unmarshal( (SAXSource JavaDoc)source );
104         if(source instanceof StreamSource JavaDoc)
105             return unmarshal( streamSourceToInputSource((StreamSource JavaDoc)source));
106         if(source instanceof DOMSource JavaDoc)
107             return unmarshal( ((DOMSource JavaDoc)source).getNode() );
108         
109         // we don't handle other types of Source
110
throw new IllegalArgumentException JavaDoc();
111     }
112
113     // use the client specified XMLReader contained in the SAXSource.
114
private Object JavaDoc unmarshal( SAXSource JavaDoc source ) throws JAXBException {
115         
116         XMLReader JavaDoc reader = source.getXMLReader();
117         if( reader == null )
118             reader = getXMLReader();
119         
120         return unmarshal( reader, source.getInputSource() );
121     }
122
123     /**
124      * Unmarshals an object by using the specified XMLReader and the InputSource.
125      *
126      * The callee should call the setErrorHandler method of the XMLReader
127      * so that errors are passed to the client-specified ValidationEventHandler.
128      */

129     protected abstract Object JavaDoc unmarshal( XMLReader JavaDoc reader, InputSource JavaDoc source ) throws JAXBException;
130     
131     public final Object JavaDoc unmarshal( InputSource JavaDoc source ) throws JAXBException {
132         if( source == null ) {
133             throw new IllegalArgumentException JavaDoc(
134                 Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
135         }
136
137         return unmarshal( getXMLReader(), source );
138     }
139         
140
141     private Object JavaDoc unmarshal( String JavaDoc url ) throws JAXBException {
142         return unmarshal( new InputSource JavaDoc(url) );
143     }
144     
145     public final Object JavaDoc unmarshal( URL JavaDoc url ) throws JAXBException {
146         if( url == null ) {
147             throw new IllegalArgumentException JavaDoc(
148                 Messages.format( Messages.MUST_NOT_BE_NULL, "url" ) );
149         }
150
151         return unmarshal( url.toExternalForm() );
152     }
153     
154     public final Object JavaDoc unmarshal( File JavaDoc f ) throws JAXBException {
155         if( f == null ) {
156             throw new IllegalArgumentException JavaDoc(
157                 Messages.format( Messages.MUST_NOT_BE_NULL, "file" ) );
158         }
159
160         try {
161             // copied from JAXP
162
String JavaDoc path = f.getAbsolutePath();
163         if (File.separatorChar != '/')
164             path = path.replace(File.separatorChar, '/');
165         if (!path.startsWith("/"))
166             path = "/" + path;
167         if (!path.endsWith("/") && f.isDirectory())
168             path = path + "/";
169         return unmarshal(new URL JavaDoc("file", "", path));
170         } catch( MalformedURLException JavaDoc e ) {
171             throw new IllegalArgumentException JavaDoc(e.getMessage());
172         }
173     }
174     
175     public final Object JavaDoc unmarshal( java.io.InputStream JavaDoc is )
176         throws JAXBException {
177             
178         if( is == null ) {
179             throw new IllegalArgumentException JavaDoc(
180                 Messages.format( Messages.MUST_NOT_BE_NULL, "is" ) );
181         }
182
183         InputSource JavaDoc isrc = new InputSource JavaDoc( is );
184         return unmarshal( isrc );
185     }
186
187     public final Object JavaDoc unmarshal( Reader JavaDoc reader ) throws JAXBException {
188         if( reader == null ) {
189             throw new IllegalArgumentException JavaDoc(
190                 Messages.format( Messages.MUST_NOT_BE_NULL, "reader" ) );
191         }
192
193         InputSource JavaDoc isrc = new InputSource JavaDoc( reader );
194         return unmarshal( isrc );
195     }
196
197
198     private static InputSource JavaDoc streamSourceToInputSource( StreamSource JavaDoc ss ) {
199         InputSource JavaDoc is = new InputSource JavaDoc();
200         is.setSystemId( ss.getSystemId() );
201         is.setByteStream( ss.getInputStream() );
202         is.setCharacterStream( ss.getReader() );
203         
204         return is;
205     }
206     
207     
208     /**
209      * Indicates whether or not the Unmarshaller is configured to validate
210      * during unmarshal operations.
211      * <p>
212      * <i><b>Note:</b> I named this method isValidating() to stay in-line
213      * with JAXP, as opposed to naming it getValidating(). </i>
214      *
215      * @return true if the Unmarshaller is configured to validate during
216      * unmarshal operations, false otherwise
217      * @throws JAXBException if an error occurs while retrieving the validating
218      * flag
219      */

220     public boolean isValidating() throws JAXBException {
221         return validating;
222     }
223     
224     /**
225      * Allow an application to register a validation event handler.
226      * <p>
227      * The validation event handler will be called by the JAXB Provider if any
228      * validation errors are encountered during calls to any of the
229      * <tt>unmarshal</tt> methods. If the client application does not register
230      * a validation event handler before invoking the unmarshal methods, then
231      * all validation events will be silently ignored and may result in
232      * unexpected behaviour.
233      *
234      * @param handler the validation event handler
235      * @throws JAXBException if an error was encountered while setting the
236      * event handler
237      */

238     public void setEventHandler(ValidationEventHandler handler)
239         throws JAXBException {
240         
241         if( handler == null ) {
242             eventHandler = new DefaultValidationEventHandler();
243         } else {
244             eventHandler = handler;
245         }
246     }
247     
248     /**
249      * Specifies whether or not the Unmarshaller should validate during
250      * unmarshal operations. By default, the <tt>Unmarshaller</tt> does
251      * not validate.
252      * <p>
253      * This method may only be invoked before or after calling one of the
254      * unmarshal methods.
255      *
256      * @param validating true if the Unmarshaller should validate during
257      * unmarshal, false otherwise
258      * @throws JAXBException if an error occurred while enabling or disabling
259      * validation at unmarshal time
260      */

261     public void setValidating(boolean validating) throws JAXBException {
262         this.validating = validating;
263     }
264     
265     /**
266      * Return the current event handler or the default event handler if one
267      * hasn't been set.
268      *
269      * @return the current ValidationEventHandler or the default event handler
270      * if it hasn't been set
271      * @throws JAXBException if an error was encountered while getting the
272      * current event handler
273      */

274     public ValidationEventHandler getEventHandler() throws JAXBException {
275         return eventHandler;
276     }
277     
278     
279     /**
280      * Creates an UnmarshalException from a SAXException.
281      *
282      * This is an utility method provided for the derived classes.
283      *
284      * <p>
285      * When a provider-implemented ContentHandler wants to throw a
286      * JAXBException, it needs to wrap the exception by a SAXException.
287      * If the unmarshaller implementation blindly wrap SAXException
288      * by JAXBException, such an exception will be a JAXBException
289      * wrapped by a SAXException wrapped by another JAXBException.
290      * This is silly.
291      *
292      * <p>
293      * This method checks the nested exception of SAXException
294      * and reduce those excessive wrapping.
295      *
296      * @return the resulting UnmarshalException
297      */

298     protected UnmarshalException createUnmarshalException( SAXException JavaDoc e ) {
299         // check the nested exception to see if it's an UnmarshalException
300
Exception JavaDoc nested = e.getException();
301         if(nested instanceof UnmarshalException)
302             return (UnmarshalException)nested;
303         
304         if(nested instanceof RuntimeException JavaDoc)
305             // typically this is an unexpected exception,
306
// just throw it rather than wrap it, so that the full stack
307
// trace can be displayed.
308
throw (RuntimeException JavaDoc)nested;
309                 
310         
311         // otherwise simply wrap it
312
if(nested!=null)
313             return new UnmarshalException(nested);
314         else
315             return new UnmarshalException(e);
316     }
317     
318     /**
319      * Default implementation of the setProperty method always
320      * throws PropertyException since there are no required
321      * properties. If a provider needs to handle additional
322      * properties, it should override this method in a derived class.
323      */

324     public void setProperty( String JavaDoc name, Object JavaDoc value )
325         throws PropertyException {
326
327         if( name == null ) {
328             throw new IllegalArgumentException JavaDoc(
329                 Messages.format( Messages.MUST_NOT_BE_NULL, "name" ) );
330         }
331
332         throw new PropertyException(name, value);
333     }
334     
335     /**
336      * Default implementation of the getProperty method always
337      * throws PropertyException since there are no required
338      * properties. If a provider needs to handle additional
339      * properties, it should override this method in a derived class.
340      */

341     public Object JavaDoc getProperty( String JavaDoc name )
342         throws PropertyException {
343             
344         if( name == null ) {
345             throw new IllegalArgumentException JavaDoc(
346                 Messages.format( Messages.MUST_NOT_BE_NULL, "name" ) );
347         }
348
349         throw new PropertyException(name);
350     }
351     
352     public Object JavaDoc unmarshal(XMLEventReader reader) throws JAXBException {
353         
354         throw new UnsupportedOperationException JavaDoc();
355     }
356
357     public Object JavaDoc unmarshal(XMLStreamReader reader) throws JAXBException {
358         
359         throw new UnsupportedOperationException JavaDoc();
360     }
361
362     public <T> JAXBElement<T> unmarshal(Node JavaDoc node, Class JavaDoc<T> expectedType) throws JAXBException {
363         throw new UnsupportedOperationException JavaDoc();
364     }
365
366     public <T> JAXBElement<T> unmarshal(Source JavaDoc source, Class JavaDoc<T> expectedType) throws JAXBException {
367         throw new UnsupportedOperationException JavaDoc();
368     }
369
370     public <T> JAXBElement<T> unmarshal(XMLStreamReader reader, Class JavaDoc<T> expectedType) throws JAXBException {
371         throw new UnsupportedOperationException JavaDoc();
372     }
373
374     public <T> JAXBElement<T> unmarshal(XMLEventReader reader, Class JavaDoc<T> expectedType) throws JAXBException {
375         throw new UnsupportedOperationException JavaDoc();
376     }
377
378     public void setSchema(Schema JavaDoc schema) {
379         throw new UnsupportedOperationException JavaDoc();
380     }
381
382     public Schema JavaDoc getSchema() {
383         throw new UnsupportedOperationException JavaDoc();
384     }
385
386     public void setAdapter(XmlAdapter adapter) {
387         if(adapter==null)
388             throw new IllegalArgumentException JavaDoc();
389         setAdapter((Class JavaDoc)adapter.getClass(),adapter);
390     }
391
392     public <A extends XmlAdapter> void setAdapter(Class JavaDoc<A> type, A adapter) {
393         throw new UnsupportedOperationException JavaDoc();
394     }
395
396     public <A extends XmlAdapter> A getAdapter(Class JavaDoc<A> type) {
397         throw new UnsupportedOperationException JavaDoc();
398     }
399
400     public void setAttachmentUnmarshaller(AttachmentUnmarshaller au) {
401         throw new UnsupportedOperationException JavaDoc();
402     }
403
404     public AttachmentUnmarshaller getAttachmentUnmarshaller() {
405         throw new UnsupportedOperationException JavaDoc();
406     }
407
408     public void setListener(Listener listener) {
409         throw new UnsupportedOperationException JavaDoc();
410     }
411
412     public Listener getListener() {
413         throw new UnsupportedOperationException JavaDoc();
414     }
415 }
416
Popular Tags