KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > samples > transform > XMLToFastInfosetStAXSerializer


1 /*
2  * Fast Infoset ver. 0.1 software ("Software")
3  *
4  * Copyright, 2004-2005 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Software is licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License. You may
8  * obtain a copy of the License at:
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15  * License for the specific language governing permissions and limitations.
16  *
17  * Sun supports and benefits from the global community of open source
18  * developers, and thanks the community for its important contributions and
19  * open standards-based technology, which Sun has adopted into many of its
20  * products.
21  *
22  * Please note that portions of Software may be provided with notices and
23  * open source licenses from such communities and third parties that govern the
24  * use of those portions, and any licenses granted hereunder do not alter any
25  * rights and obligations you may have under such open source licenses,
26  * however, the disclaimer of warranty and limitation of liability provisions
27  * in this License will apply to all Software in this distribution.
28  *
29  * You acknowledge that the Software is not designed, licensed or intended
30  * for use in the design, construction, operation or maintenance of any nuclear
31  * facility.
32  *
33  * Apache License
34  * Version 2.0, January 2004
35  * http://www.apache.org/licenses/
36  *
37  */

38
39 package samples.transform;
40
41 import java.io.File JavaDoc;
42 import java.io.InputStream JavaDoc;
43 import java.io.FileInputStream JavaDoc;
44 import java.io.FileOutputStream JavaDoc;
45 import java.io.BufferedInputStream JavaDoc;
46 import java.io.BufferedOutputStream JavaDoc;
47 import java.io.FileNotFoundException JavaDoc;
48 import java.io.ByteArrayOutputStream JavaDoc;
49
50 import javax.xml.transform.*;
51 import javax.xml.transform.dom.*;
52 import javax.xml.transform.stream.*;
53 import javax.xml.parsers.*;
54 import org.w3c.dom.*;
55 import javax.xml.transform.sax.SAXResult JavaDoc;
56
57 import javax.xml.stream.XMLStreamWriter;
58 import javax.xml.stream.XMLStreamException;
59 import com.sun.xml.fastinfoset.stax.StAXDocumentSerializer;
60 import com.sun.xml.fastinfoset.stax.SAX2StAXWriter;
61
62 /** <p>Serializes an XML input stream into FI document using
63  * StAX document serializer defined in the fastinfoset.stax package.</p>
64  * The sample demonstrates how to use StAXDocumentSerializer as a SAX handler and JAXP
65  * transformer to convert an XML file into a FI document. As shown in the sample,
66  * transforming a DOM source to SAX Result involves very little coding. However, the process
67  * may not be efficient due to the construction of DOM source.
68  *
69  * In the sample, a DOMSource is constructed out of an XML file input (see method getDOMSource)
70  * and a SAXResult is instantiated using an instance of SAX2StAXWriter as handlers (see method
71  * getSAXResult). Utility class
72  * SAX2StAXWriter extends DefaultHandler and implements LexicalHandler, which allows it
73  * to be used to handle SAX events. The source and result are then used by the JAXP transformer
74  * to transform the XML file to FI document which was passed in as OutputStream for the StAX
75  * serializer object. The XML inputstream is first transformed into a ByteArrayOutputStream
76  * that may be used for other processing. In this sample, we simply write it out into a file.<br>
77  *
78  */

79
80 public class XMLToFastInfosetStAXSerializer {
81     String JavaDoc _xmlFile;
82     Transformer _transformer;
83     DocumentBuilder _docBuilder;
84     DOMSource _source = null;
85     SAXResult JavaDoc _result = null;
86     ByteArrayOutputStream JavaDoc _baos;
87     
88     /** Creates a new instance of DocumentSerializer */
89     public XMLToFastInfosetStAXSerializer() {
90         try {
91             _transformer = TransformerFactory.newInstance().newTransformer();
92             _docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
93         } catch (Exception JavaDoc e) {
94             e.printStackTrace();
95         }
96     }
97     
98      /** Construct a DOMSource with a file.
99      *
100      * @param input the XML file input
101      */

102     void getDOMSource(File JavaDoc input) {
103         try {
104             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(input);
105             Document document = _docBuilder.parse(fis);
106             fis.close();
107             _source = new DOMSource(document);
108         }
109         catch (Exception JavaDoc e) {
110             e.printStackTrace();
111         }
112         
113     }
114     
115     /** Initialize a SAXResult and set its handers.
116      *
117      * @param output FI document output
118      */

119     void getSAXResult(File JavaDoc output) {
120         try {
121             _baos = new ByteArrayOutputStream JavaDoc();
122             XMLStreamWriter serializer = new StAXDocumentSerializer(_baos);
123             SAX2StAXWriter saxTostax = new SAX2StAXWriter(serializer);
124             
125             _result = new SAXResult JavaDoc();
126             _result.setHandler(saxTostax);
127             _result.setLexicalHandler(saxTostax);
128             
129         }
130         catch (Exception JavaDoc e) {
131             e.printStackTrace();
132         }
133     }
134
135     /** Transform an XML file into a FI document.
136      *
137      * @param input an XML file input
138      * @param output the FI document output
139      */

140     public void write(File JavaDoc input, File JavaDoc output) {
141         getDOMSource(input);
142         getSAXResult(output);
143         if (_source != null && _result != null) {
144             try {
145                 System.out.println("Transforming "+input.getName()+ " into " + output.getName());
146                 //Transform the XML inputstream into ByteArrayOutputStream
147
_transformer.transform(_source, _result);
148
149                 //the ByteArrayOutputStream may be used for other processing
150
//in this sample, we simply write it out to a file
151
BufferedOutputStream JavaDoc fos = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(output));
152                 _baos.writeTo(fos);
153             } catch (Exception JavaDoc e) {
154                 e.printStackTrace();
155             }
156             System.out.println("\ndone.");
157         } else {
158                 System.out.println("Source or Result could not be null.");
159         }
160         try {
161         } catch (Exception JavaDoc e) {
162             e.printStackTrace();
163         }
164     }
165     /** Starts the sample.
166      *
167      * @param args XML input file name and FI output file name
168      */

169     public static void main(String JavaDoc[] args) {
170         if (args.length < 1 || args.length > 2) {
171             displayUsageAndExit();
172         }
173         File JavaDoc input = new File JavaDoc(args[0]);
174         File JavaDoc ouput = new File JavaDoc(args[1]);
175         XMLToFastInfosetStAXSerializer docSerializer = new XMLToFastInfosetStAXSerializer();
176         docSerializer.write(input, ouput);
177     }
178
179     private static void displayUsageAndExit() {
180         System.err.println("Usage: ant FIStAXSerializer or samples.stax.FISerializer XML_input_file> FI_output_file");
181         System.exit(1);
182     }
183         
184 }
185
Popular Tags