KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > tools > xjc > runtime > MarshallerImpl


1 package com.sun.tools.xjc.runtime;
2
3 import java.io.BufferedWriter JavaDoc;
4 import java.io.FileOutputStream JavaDoc;
5 import java.io.IOException JavaDoc;
6 import java.io.OutputStream JavaDoc;
7 import java.io.OutputStreamWriter JavaDoc;
8 import java.io.UnsupportedEncodingException JavaDoc;
9 import java.io.Writer JavaDoc;
10
11 import javax.xml.bind.DatatypeConverter;
12 import javax.xml.bind.JAXBException;
13 import javax.xml.bind.MarshalException;
14 import javax.xml.bind.PropertyException;
15 import javax.xml.bind.helpers.AbstractMarshallerImpl;
16 import javax.xml.parsers.DocumentBuilder JavaDoc;
17 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
18 import javax.xml.parsers.ParserConfigurationException JavaDoc;
19 import javax.xml.transform.Result JavaDoc;
20 import javax.xml.transform.dom.DOMResult JavaDoc;
21 import javax.xml.transform.sax.SAXResult JavaDoc;
22 import javax.xml.transform.stream.StreamResult JavaDoc;
23
24 import org.w3c.dom.Document JavaDoc;
25 import org.w3c.dom.Node JavaDoc;
26 import org.xml.sax.ContentHandler JavaDoc;
27 import org.xml.sax.SAXException JavaDoc;
28 import org.xml.sax.helpers.LocatorImpl JavaDoc;
29
30 import com.sun.xml.bind.DatatypeConverterImpl;
31 import com.sun.xml.bind.JAXBAssertionError;
32 import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
33 import com.sun.xml.bind.marshaller.DataWriter;
34 import com.sun.xml.bind.marshaller.DumbEscapeHandler;
35 import com.sun.xml.bind.marshaller.Messages;
36 import com.sun.xml.bind.marshaller.MinimumEscapeHandler;
37 import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
38 import com.sun.xml.bind.marshaller.NioEscapeHandler;
39 import com.sun.xml.bind.marshaller.SAX2DOMEx;
40 import com.sun.xml.bind.marshaller.SchemaLocationFilter;
41 import com.sun.xml.bind.marshaller.XMLWriter;
42
43 /**
44  * Implementation of {@link Marshaller} interface for JAXB RI.
45  *
46  * @author Kohsuke Kawaguchi
47  * @author Vivek Pandey
48  */

49 public class MarshallerImpl extends AbstractMarshallerImpl
50 {
51     /** Indentation string. Default is four whitespaces. */
52     private String JavaDoc indent = " ";
53     
54     /** Used to assign prefixes to namespace URIs. */
55     private NamespacePrefixMapper prefixMapper = null;
56     
57     /** Object that handles character escaping. */
58     private CharacterEscapeHandler escapeHandler = null;
59     
60     /** Whether the xml declaration will be printed or not. */
61     private boolean printXmlDeclaration = true;
62     
63     /** XML BLOB written after the XML declaration. */
64     private String JavaDoc header=null;
65     
66     /** reference to the context that created this object */
67     final DefaultJAXBContextImpl context;
68     
69     public MarshallerImpl( DefaultJAXBContextImpl c ) {
70         // initialize datatype converter with ours
71
DatatypeConverter.setDatatypeConverter(DatatypeConverterImpl.theInstance);
72         
73         context = c;
74     }
75     
76     public void marshal(Object JavaDoc obj, Result JavaDoc result) throws JAXBException {
77         //XMLSerializable so = Util.toXMLSerializable(obj);
78
XMLSerializable so = context.getGrammarInfo().castToXMLSerializable(obj);
79
80         if(so==null)
81             throw new MarshalException(
82                 Messages.format( Messages.NOT_MARSHALLABLE ) );
83
84
85         if (result instanceof SAXResult JavaDoc) {
86             write(so, ((SAXResult JavaDoc) result).getHandler());
87             return;
88         }
89         if (result instanceof DOMResult JavaDoc) {
90             Node JavaDoc node = ((DOMResult JavaDoc) result).getNode();
91
92             if (node == null) {
93                 try {
94                     DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
95                     dbf.setNamespaceAware(true);
96                     DocumentBuilder JavaDoc db = dbf.newDocumentBuilder();
97                     Document JavaDoc doc = db.newDocument();
98                     ((DOMResult JavaDoc) result).setNode(doc);
99                     write(so, new SAX2DOMEx(doc));
100                 } catch (ParserConfigurationException JavaDoc pce) {
101                     throw new JAXBAssertionError(pce);
102                 }
103             } else {
104                 write(so, new SAX2DOMEx(node));
105             }
106
107             return;
108         }
109         if (result instanceof StreamResult JavaDoc) {
110             StreamResult JavaDoc sr = (StreamResult JavaDoc) result;
111             XMLWriter w = null;
112
113             if (sr.getWriter() != null)
114                 w = createWriter(sr.getWriter());
115             else if (sr.getOutputStream() != null)
116                 w = createWriter(sr.getOutputStream());
117             else if (sr.getSystemId() != null) {
118                 String JavaDoc fileURL = sr.getSystemId();
119
120                 if (fileURL.startsWith("file:///")) {
121                     if (fileURL.substring(8).indexOf(":") > 0)
122                         fileURL = fileURL.substring(8);
123                     else
124                         fileURL = fileURL.substring(7);
125                 } // otherwise assume that it's a file name
126

127                 try {
128                     w = createWriter(new FileOutputStream JavaDoc(fileURL));
129                 } catch (IOException JavaDoc e) {
130                     throw new MarshalException(e);
131                 }
132             }
133
134             if (w == null)
135                 throw new IllegalArgumentException JavaDoc();
136
137             write(so, w);
138             return;
139         }
140
141         // unsupported parameter type
142
throw new MarshalException(
143             Messages.format( Messages.UNSUPPORTED_RESULT ) );
144     }
145     
146     private void write( XMLSerializable obj, ContentHandler JavaDoc writer )
147         throws JAXBException {
148
149         try {
150             if( getSchemaLocation()!=null || getNoNSSchemaLocation()!=null ) {
151                 // if we need to add xsi:schemaLocation or its brother,
152
// throw in the component to do that.
153
writer = new SchemaLocationFilter(
154                     getSchemaLocation(),
155                     getNoNSSchemaLocation(),
156                     writer );
157             }
158             
159             SAXMarshaller serializer = new SAXMarshaller(writer,prefixMapper,this);
160         
161             // set a DocumentLocator that doesn't provide any information
162
writer.setDocumentLocator( new LocatorImpl JavaDoc() );
163             writer.startDocument();
164             serializer.childAsBody(obj,null);
165             writer.endDocument();
166             
167             serializer.reconcileID(); // extra check
168
} catch( SAXException JavaDoc e ) {
169             throw new MarshalException(e);
170         }
171     }
172     
173     
174     //
175
//
176
// create XMLWriter by specifing various type of output.
177
//
178
//
179

180     protected CharacterEscapeHandler createEscapeHandler( String JavaDoc encoding ) {
181         if( escapeHandler!=null )
182             // user-specified one takes precedence.
183
return escapeHandler;
184         
185         if( encoding.startsWith("UTF") )
186             // no need for character reference. Use the handler
187
// optimized for that pattern.
188
return MinimumEscapeHandler.theInstance;
189         
190         // otherwise try to find one from the encoding
191
try {
192             // try new JDK1.4 NIO
193
return new NioEscapeHandler( getJavaEncoding(encoding) );
194         } catch( Throwable JavaDoc e ) {
195             // if that fails, fall back to the dumb mode
196
return DumbEscapeHandler.theInstance;
197         }
198     }
199             
200     public XMLWriter createWriter( Writer JavaDoc w, String JavaDoc encoding ) throws JAXBException {
201         
202         // buffering improves the performance
203
w = new BufferedWriter JavaDoc(w);
204         
205         CharacterEscapeHandler ceh = createEscapeHandler(encoding);
206         XMLWriter xw;
207         
208         if(isFormattedOutput()) {
209             DataWriter d = new DataWriter(w,encoding,ceh);
210             d.setIndentStep(indent);
211             xw=d;
212         }
213         else
214             xw = new XMLWriter(w,encoding,ceh);
215             
216         xw.setXmlDecl(printXmlDeclaration);
217         xw.setHeader(header);
218         return xw;
219     }
220
221     public XMLWriter createWriter(Writer JavaDoc w) throws JAXBException{
222         return createWriter(w, getEncoding());
223     }
224     
225     public XMLWriter createWriter( OutputStream JavaDoc os ) throws JAXBException {
226         return createWriter(os, getEncoding());
227     }
228     
229     public XMLWriter createWriter( OutputStream JavaDoc os, String JavaDoc encoding ) throws JAXBException {
230         try {
231             return createWriter(
232                 new OutputStreamWriter JavaDoc(os,getJavaEncoding(encoding)),
233                 encoding );
234         } catch( UnsupportedEncodingException JavaDoc e ) {
235             throw new MarshalException(
236                 Messages.format( Messages.UNSUPPORTED_ENCODING, encoding ),
237                 e );
238         }
239     }
240     
241     
242     public Object JavaDoc getProperty(String JavaDoc name) throws PropertyException {
243         if( INDENT_STRING.equals(name) )
244             return indent;
245         if( ENCODING_HANDLER.equals(name) )
246             return escapeHandler;
247         if( PREFIX_MAPPER.equals(name) )
248             return prefixMapper;
249         if( XMLDECLARATION.equals(name) )
250             return printXmlDeclaration ? Boolean.TRUE : Boolean.FALSE;
251         if( XML_HEADERS.equals(name) )
252             return header;
253         
254         return super.getProperty(name);
255     }
256
257     public void setProperty(String JavaDoc name, Object JavaDoc value) throws PropertyException {
258         if( INDENT_STRING.equals(name) && value instanceof String JavaDoc ) {
259             indent = (String JavaDoc)value;
260             return;
261         }
262         if( ENCODING_HANDLER.equals(name) ) {
263             escapeHandler = (CharacterEscapeHandler)value;
264             return;
265         }
266         if( PREFIX_MAPPER.equals(name) ) {
267             prefixMapper = (NamespacePrefixMapper)value;
268             return;
269         }
270         if( XMLDECLARATION.equals(name) ) {
271             printXmlDeclaration = ((Boolean JavaDoc)value).booleanValue();
272             return;
273         }
274         if( XML_HEADERS.equals(name) ) {
275             header = (String JavaDoc)value;
276             return;
277         }
278             
279         super.setProperty(name, value);
280     }
281     
282     private static final String JavaDoc INDENT_STRING = "com.sun.xml.bind.indentString";
283     private static final String JavaDoc PREFIX_MAPPER = "com.sun.xml.bind.namespacePrefixMapper";
284     private static final String JavaDoc ENCODING_HANDLER = "com.sun.xml.bind.characterEscapeHandler";
285     private static final String JavaDoc XMLDECLARATION = "com.sun.xml.bind.xmlDeclaration";
286     private static final String JavaDoc XML_HEADERS = "com.sun.xml.bind.xmlHeaders";
287 }
288
Popular Tags