KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > framework > configuration > DefaultConfigurationSerializer


1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 1997-2003 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  * if any, must include the following acknowledgment:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowledgment may appear in the software
24  * itself, if and wherever such third-party acknowledgments
25  * normally appear.
26  *
27  * 4. The names "Jakarta", "Avalon", and "Apache Software Foundation"
28  * must not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55 package org.apache.avalon.framework.configuration;
56
57 import java.io.File JavaDoc;
58 import java.io.FileOutputStream JavaDoc;
59 import java.io.IOException JavaDoc;
60 import java.io.OutputStream JavaDoc;
61 import java.io.StringWriter JavaDoc;
62 import java.net.URL JavaDoc;
63 import java.util.Properties JavaDoc;
64 import javax.xml.transform.OutputKeys JavaDoc;
65 import javax.xml.transform.Result JavaDoc;
66 import javax.xml.transform.TransformerFactory JavaDoc;
67 import javax.xml.transform.sax.SAXTransformerFactory JavaDoc;
68 import javax.xml.transform.sax.TransformerHandler JavaDoc;
69 import javax.xml.transform.stream.StreamResult JavaDoc;
70 import org.xml.sax.ContentHandler JavaDoc;
71 import org.xml.sax.SAXException JavaDoc;
72 import org.xml.sax.helpers.AttributesImpl JavaDoc;
73 import org.xml.sax.helpers.NamespaceSupport JavaDoc;
74
75 /**
76  * A ConfigurationSerializer serializes configurations via SAX2 compliant parser.
77  *
78  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
79  * @version CVS $Revision: 1.24 $ $Date: 2003/02/11 15:58:39 $
80  */

81 public class DefaultConfigurationSerializer
82 {
83     private SAXTransformerFactory JavaDoc m_tfactory;
84     private Properties JavaDoc m_format = new Properties JavaDoc();
85
86     /**
87      * Sets the Serializer's use of indentation. This will cause linefeeds to be added
88      * after each element, but it does not add any indentation via spaces.
89      * @param indent a <code>boolean</code> value
90      */

91     public void setIndent( boolean indent )
92     {
93         if( indent )
94         {
95             m_format.put( OutputKeys.INDENT, "yes" );
96         }
97         else
98         {
99             m_format.put( OutputKeys.INDENT, "no" );
100         }
101     }
102
103     /**
104      * Create a ContentHandler for an OutputStream
105      * @param result the result
106      * @return contenthandler that goes to specified OutputStream
107      */

108     protected ContentHandler JavaDoc createContentHandler( final Result JavaDoc result )
109     {
110         try
111         {
112             TransformerHandler JavaDoc handler = getTransformerFactory().newTransformerHandler();
113
114             m_format.put( OutputKeys.METHOD, "xml" );
115             handler.setResult( result );
116             handler.getTransformer().setOutputProperties( m_format );
117
118             return handler;
119         }
120         catch( final Exception JavaDoc e )
121         {
122             throw new RuntimeException JavaDoc( e.toString() );
123         }
124     }
125
126     /**
127      * Get the SAXTransformerFactory so we can get a serializer without being
128      * tied to one vendor.
129      * @return a <code>SAXTransformerFactory</code> value
130      */

131     protected SAXTransformerFactory JavaDoc getTransformerFactory()
132     {
133         if( m_tfactory == null )
134         {
135             m_tfactory = (SAXTransformerFactory JavaDoc)TransformerFactory.newInstance();
136         }
137
138         return m_tfactory;
139     }
140
141     /**
142      * Serialize the configuration to a ContentHandler
143      * @param handler a <code>ContentHandler</code> to serialize to
144      * @param source a <code>Configuration</code> value
145      * @throws SAXException if an error occurs
146      * @throws ConfigurationException if an error occurs
147      */

148     public void serialize( final ContentHandler JavaDoc handler, final Configuration source )
149         throws SAXException JavaDoc, ConfigurationException
150     {
151         handler.startDocument();
152         serializeElement( handler, new NamespaceSupport JavaDoc(), source );
153         handler.endDocument();
154     }
155
156     /**
157      * Serialize each Configuration element. This method is called recursively.
158      * @param handler a <code>ContentHandler</code> to use
159      * @param namespaceSupport a <code>NamespaceSupport</code> to use
160      * @param element a <code>Configuration</code> value
161      * @throws SAXException if an error occurs
162      * @throws ConfigurationException if an error occurs
163      */

164     protected void serializeElement( final ContentHandler JavaDoc handler,
165                                      final NamespaceSupport JavaDoc namespaceSupport,
166                                      final Configuration element )
167         throws SAXException JavaDoc, ConfigurationException
168     {
169         namespaceSupport.pushContext();
170
171         AttributesImpl JavaDoc attr = new AttributesImpl JavaDoc();
172         String JavaDoc[] attrNames = element.getAttributeNames();
173
174         if( null != attrNames )
175         {
176             for( int i = 0; i < attrNames.length; i++ )
177             {
178                 attr.addAttribute( "", // namespace URI
179
attrNames[ i ], // local name
180
attrNames[ i ], // qName
181
"CDATA", // type
182
element.getAttribute( attrNames[ i ], "" ) // value
183
);
184             }
185         }
186
187         final String JavaDoc nsURI = element.getNamespace();
188         String JavaDoc nsPrefix = "";
189
190         if( element instanceof AbstractConfiguration )
191         {
192             nsPrefix = ( (AbstractConfiguration)element ).getPrefix();
193         }
194         // nsPrefix is guaranteed to be non-null at this point.
195

196         boolean nsWasDeclared = false;
197
198         final String JavaDoc existingURI = namespaceSupport.getURI( nsPrefix );
199
200         // ie, there is no existing URI declared for this prefix or we're
201
// remapping the prefix to a different URI
202
if( existingURI == null || !existingURI.equals( nsURI ) )
203         {
204             nsWasDeclared = true;
205             if( nsPrefix.equals( "" ) && nsURI.equals( "" ) )
206             {
207                 // implicit mapping; don't need to declare
208
}
209             else if( nsPrefix.equals( "" ) )
210             {
211                 // (re)declare the default namespace
212
attr.addAttribute( "", "xmlns", "xmlns", "CDATA", nsURI );
213             }
214             else
215             {
216                 // (re)declare a mapping from nsPrefix to nsURI
217
attr.addAttribute( "", "xmlns:" + nsPrefix, "xmlns:" + nsPrefix, "CDATA", nsURI );
218             }
219             handler.startPrefixMapping( nsPrefix, nsURI );
220             namespaceSupport.declarePrefix( nsPrefix, nsURI );
221         }
222
223         String JavaDoc localName = element.getName();
224         String JavaDoc qName = element.getName();
225         if( nsPrefix == null || nsPrefix.length() == 0 )
226         {
227             qName = localName;
228         }
229         else
230         {
231             qName = nsPrefix + ":" + localName;
232         }
233
234         handler.startElement( nsURI, localName, qName, attr );
235
236         String JavaDoc value = element.getValue( null );
237
238         if( null == value )
239         {
240             Configuration[] children = element.getChildren();
241
242             for( int i = 0; i < children.length; i++ )
243             {
244                 serializeElement( handler, namespaceSupport, children[ i ] );
245             }
246         }
247         else
248         {
249             handler.characters( value.toCharArray(), 0, value.length() );
250         }
251
252         handler.endElement( nsURI, localName, qName );
253
254         if( nsWasDeclared )
255         {
256             handler.endPrefixMapping( nsPrefix );
257         }
258
259         namespaceSupport.popContext();
260     }
261
262     /**
263      * Serialize the configuration object to a file using a filename.
264      * @param filename a <code>String</code> value
265      * @param source a <code>Configuration</code> value
266      * @throws SAXException if an error occurs
267      * @throws IOException if an error occurs
268      * @throws ConfigurationException if an error occurs
269      */

270     public void serializeToFile( final String JavaDoc filename, final Configuration source )
271         throws SAXException JavaDoc, IOException JavaDoc, ConfigurationException
272     {
273         serializeToFile( new File JavaDoc( filename ), source );
274     }
275
276     /**
277      * Serialize the configuration object to a file using a File object.
278      * @param file a <code>File</code> value
279      * @param source a <code>Configuration</code> value
280      * @throws SAXException if an error occurs
281      * @throws IOException if an error occurs
282      * @throws ConfigurationException if an error occurs
283      */

284     public void serializeToFile( final File JavaDoc file, final Configuration source )
285         throws SAXException JavaDoc, IOException JavaDoc, ConfigurationException
286     {
287         OutputStream JavaDoc outputStream = null;
288         try
289         {
290             outputStream = new FileOutputStream JavaDoc( file );
291             serialize( outputStream, source );
292         }
293         finally
294         {
295             if( outputStream != null )
296             {
297                 outputStream.close();
298             }
299         }
300     }
301
302     /**
303      * Serialize the configuration object to an output stream.
304      * @param outputStream an <code>OutputStream</code> value
305      * @param source a <code>Configuration</code> value
306      * @throws SAXException if an error occurs
307      * @throws IOException if an error occurs
308      * @throws ConfigurationException if an error occurs
309      */

310     public void serialize( final OutputStream JavaDoc outputStream, final Configuration source )
311         throws SAXException JavaDoc, IOException JavaDoc, ConfigurationException
312     {
313         serialize( createContentHandler( new StreamResult JavaDoc( outputStream ) ), source );
314     }
315
316     /**
317      * Serialize the configuration object to an output stream derived from an
318      * URI. The URI must be resolveable by the <code>java.net.URL</code> object.
319      * @param uri a <code>String</code> value
320      * @param source a <code>Configuration</code> value
321      * @throws SAXException if an error occurs
322      * @throws IOException if an error occurs
323      * @throws ConfigurationException if an error occurs
324      */

325     public void serialize( final String JavaDoc uri, final Configuration source )
326         throws SAXException JavaDoc, IOException JavaDoc, ConfigurationException
327     {
328         OutputStream JavaDoc outputStream = null;
329         try
330         {
331             outputStream = new URL JavaDoc( uri ).openConnection().getOutputStream();
332             serialize( outputStream, source );
333         }
334         finally
335         {
336             if( outputStream != null )
337             {
338                 outputStream.close();
339             }
340         }
341     }
342
343     /**
344      * Serialize the configuration object to a string
345      * @param source a <code>Configuration</code> value
346      * @return configuration serialized as a string.
347      * @throws SAXException if an error occurs
348      * @throws ConfigurationException if an error occurs
349      */

350     public String JavaDoc serialize( final Configuration source )
351         throws SAXException JavaDoc, ConfigurationException
352     {
353         final StringWriter JavaDoc writer = new StringWriter JavaDoc();
354
355         serialize( createContentHandler( new StreamResult JavaDoc( writer ) ), source );
356
357         return writer.toString();
358     }
359 }
360
Popular Tags