KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > samples > sax > FastInfosetParser


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.sax;
40 import java.io.*;
41
42 import org.xml.sax.*;
43 import org.xml.sax.helpers.DefaultHandler JavaDoc;
44 import com.sun.xml.fastinfoset.sax.SAXDocumentParser;
45
46 /** <p>Parses a FI document using SAXDocumentParser.</p>
47  * The sample parses data/inv1a.finf as specified in the build.xml and handles SAX events
48  * to display corresponding content in XML format. The sample class entends DefaultHandler
49  * interface making itself a ContentHandler. Since the FastInfoset SAX package does not
50  * implement factory, a document parser is instantiated directly. The sample class implements
51  * some major event-handling methods as defined in the ContentHandler, such as startDocument,
52  * endDocument, startElement,
53  * endElement, and characters. In this sample, these methods simply write out the content
54  * to System.out.
55  */

56 public class FastInfosetParser extends DefaultHandler JavaDoc {
57     static private Writer out;
58
59     StringBuffer JavaDoc textBuffer;
60     
61     /** Starts the sample. The sample takes a FI document and parses it using SAXDocumentParser in
62      * the fastinfoset package
63      *
64      * @param argv FI document filename
65      */

66     public static void main(String JavaDoc argv[])
67     {
68         if (argv.length != 1) {
69             System.err.println("Usage: FastInfosetParser filename");
70             System.exit(1);
71         }
72         
73         // instantiate event handler
74
DefaultHandler JavaDoc handler = new FastInfosetParser();
75       
76         try {
77             // Set up output stream
78
out = new OutputStreamWriter(System.out, "UTF8");
79
80             // Create an inputstream
81
InputStream in = new BufferedInputStream(new FileInputStream(argv[0]));
82             
83             // Instantiate a FI parser
84
SAXDocumentParser parser = new SAXDocumentParser();
85             parser.setContentHandler(handler);
86             // Start parsing
87
parser.parse(in);
88
89         } catch (Throwable JavaDoc t) {
90             t.printStackTrace();
91         }
92         System.exit(0);
93     }
94     
95     private static void displayUsageAndExit() {
96         System.err.println("Usage: ant FISAXParser or samples.sax.FIParser FI_input_file>");
97         System.exit(1);
98     }
99
100     /** Creates a new instance of FIParser */
101     public FastInfosetParser() {
102     }
103
104     //===========================================================
105
// SAX DocumentHandler methods
106
//===========================================================
107
/** Handles startDocument event and prints out file header.
108      *
109      */

110     public void startDocument() throws SAXException {
111         display("<?xml version='1.0' encoding='UTF-8'?>");
112         displayNewLine();
113     }
114
115     /** Handles endDocument event
116      *
117      */

118     public void endDocument() throws SAXException {
119         try {
120             displayNewLine();
121             out.flush();
122         } catch (IOException e) {
123             throw new SAXException("I/O error", e);
124         }
125     }
126
127     /** Handles startElement event. Prints out any text accumulated
128      * from the characters event before the element, the element name, and
129      * attributes if any.
130      *
131      * @param namespaceURI namespace URI
132      * @param localName The local name (without prefix), or the empty string if Namespace processing is not being performed.
133      * @param qName The qualified name (with prefix), or the empty string if qualified names are not available.
134      * @param attributes The specified or defaulted attributes.
135      */

136     public void startElement(String JavaDoc namespaceURI, String JavaDoc localName,
137         String JavaDoc qName, Attributes attributes) throws SAXException {
138         
139         // Print out text accumulated from the characters event
140
flushText();
141
142         String JavaDoc name = null;
143         
144         if (localName.equals("")) {
145             name = qName;
146         } else {
147             name = localName;
148         }
149
150         // Print out element name and attributes if any
151
display("<" + name);
152
153         if (attributes != null) {
154             for (int i = 0; i < attributes.getLength(); i++) {
155                 String JavaDoc aName = attributes.getLocalName(i);
156
157                 if ("".equals(aName)) {
158                     aName = attributes.getQName(i);
159                 }
160
161                 display(" " + aName + "=\"" + attributes.getValue(i) + "\"");
162             }
163         }
164
165         display(">");
166     }
167
168     /** Handles endElement event. Prints out any text accumulated
169      * from the characters event within the element, and then the end element name.
170      *
171      * @param namespaceURI namespace URI
172      * @param localName The local name (without prefix), or the empty string if Namespace processing is not being performed.
173      * @param qName The qualified name (with prefix), or the empty string if qualified names are not available.
174      */

175     public void endElement(String JavaDoc namespaceURI, String JavaDoc localName, String JavaDoc qName )
176         throws SAXException {
177         
178         // Print out text accumulated from the characters event
179
flushText();
180
181         String JavaDoc name = localName;
182
183         if ("".equals(name)) {
184             name = qName;
185         }
186
187         // Print out end element
188
display("</" + name + ">");
189     }
190
191     /** Handles characters event. Save the text in a buffer for print-out in start/end element.
192      *
193      * @param ch The characters
194      * @param start The start position in the character array.
195      * @param length The number of characters to use from the character array.
196      */

197     public void characters(char[] ch, int start, int length)
198         throws SAXException {
199         String JavaDoc s = new String JavaDoc(ch, start, length);
200
201         if (textBuffer == null) {
202             textBuffer = new StringBuffer JavaDoc(s);
203         } else {
204             textBuffer.append(s);
205         }
206     }
207
208     //===========================================================
209
// Utility Methods ...
210
//===========================================================
211
// Display text accumulated in the character buffer
212
private void flushText() throws SAXException {
213         if (textBuffer == null) {
214             return;
215         }
216
217         display(textBuffer.toString());
218         textBuffer = null;
219     }
220
221     // Wrap I/O exceptions in SAX exceptions, to
222
// suit handler signature requirements
223
private void display(String JavaDoc s) throws SAXException {
224         try {
225             out.write(s);
226             out.flush();
227         } catch (IOException e) {
228             throw new SAXException("I/O error", e);
229         }
230     }
231
232     // Displays a new line
233
private void displayNewLine() throws SAXException {
234         try {
235             out.write(System.getProperty("line.separator"));
236         } catch (IOException e) {
237             throw new SAXException("I/O error", e);
238         }
239     }
240 }
241
Popular Tags