KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sax > SAX2Writer


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 1999 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Xerces" and "Apache Software Foundation" must
28  * 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 and was
52  * originally based on software copyright (c) 1999, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package sax;
59
60 import java.io.OutputStreamWriter JavaDoc;
61 import java.io.PrintWriter JavaDoc;
62 import java.io.UnsupportedEncodingException JavaDoc;
63
64 import org.xml.sax.Attributes JavaDoc;
65 import org.xml.sax.SAXException JavaDoc;
66 import org.xml.sax.SAXParseException JavaDoc;
67 import org.xml.sax.XMLReader JavaDoc;
68 import org.xml.sax.helpers.DefaultHandler JavaDoc;
69
70 import sax.helpers.AttributesImpl;
71 import util.Arguments;
72
73 /**
74  * A sample SAX2 writer. This sample program illustrates how to
75  * register a SAX2 ContentHandler and receive the callbacks in
76  * order to print a document that is parsed.
77  *
78  * @version $Id: SAX2Writer.java,v 1.2 2005/01/26 08:28:44 jkjome Exp $
79  */

80 public class SAX2Writer
81     extends DefaultHandler JavaDoc {
82
83     //
84
// Constants
85
//
86

87     /** Default parser name. */
88     private static final String JavaDoc
89         DEFAULT_PARSER_NAME = "org.enhydra.apache.xerces.parsers.SAXParser";
90
91
92     private static boolean setValidation = false; //defaults
93
private static boolean setNameSpaces = true;
94     private static boolean setSchemaSupport = true;
95     private static boolean setSchemaFullSupport = false;
96
97
98     //
99
// Data
100
//
101

102     /** Print writer. */
103     protected PrintWriter JavaDoc out;
104
105     /** Canonical output. */
106     protected boolean canonical;
107
108     //
109
// Constructors
110
//
111

112     /** Default constructor. */
113     public SAX2Writer(boolean canonical) throws UnsupportedEncodingException JavaDoc {
114         this(null, canonical);
115     }
116
117     protected SAX2Writer(String JavaDoc encoding, boolean canonical) throws UnsupportedEncodingException JavaDoc {
118
119         if (encoding == null) {
120             encoding = "UTF8";
121         }
122
123         out = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(System.out, encoding));
124         this.canonical = canonical;
125
126     } // <init>(String,boolean)
127

128     //
129
// Public static methods
130
//
131

132     /** Prints the output from the SAX callbacks. */
133     public static void print(String JavaDoc parserName, String JavaDoc uri, boolean canonical) {
134
135         try {
136             DefaultHandler JavaDoc handler = new SAX2Writer(canonical);
137
138             XMLReader JavaDoc parser = (XMLReader JavaDoc)Class.forName(parserName).newInstance();
139
140             parser.setFeature( "http://xml.org/sax/features/validation",
141                                                 setValidation);
142             parser.setFeature( "http://xml.org/sax/features/namespaces",
143                                                 setNameSpaces );
144             parser.setFeature( "http://apache.org/xml/features/validation/schema",
145                                                 setSchemaSupport );
146             parser.setFeature( "http://apache.org/xml/features/validation/schema-full-checking",
147                                                 setSchemaFullSupport );
148
149
150             parser.setContentHandler(handler);
151             parser.setErrorHandler(handler);
152             parser.parse(uri);
153         }
154         catch (Exception JavaDoc e) {
155             e.printStackTrace(System.err);
156         }
157
158     } // print(String,String,boolean)
159

160     //
161
// DocumentHandler methods
162
//
163

164     /** Processing instruction. */
165     public void processingInstruction(String JavaDoc target, String JavaDoc data) {
166
167         out.print("<?");
168         out.print(target);
169         if (data != null && data.length() > 0) {
170             out.print(' ');
171             out.print(data);
172         }
173         out.print("?>");
174         out.flush();
175
176     } // processingInstruction(String,String)
177

178     /** Start document. */
179     public void startDocument() {
180
181         if (!canonical) {
182             out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
183             out.flush();
184         }
185
186     } // startDocument()
187

188     /** Start element. */
189     public void startElement(String JavaDoc uri, String JavaDoc local, String JavaDoc raw,
190                              Attributes JavaDoc attrs) {
191
192         out.print('<');
193         out.print(raw);
194         if (attrs != null) {
195             attrs = sortAttributes(attrs);
196             int len = attrs.getLength();
197             for (int i = 0; i < len; i++) {
198                 out.print(' ');
199                 out.print(attrs.getQName(i));
200                 out.print("=\"");
201                 out.print(normalize(attrs.getValue(i)));
202                 out.print('"');
203             }
204         }
205         out.print('>');
206         out.flush();
207
208     } // startElement(String,String,String,Attributes)
209

210     /** Characters. */
211     public void characters(char ch[], int start, int length) {
212
213         out.print(normalize(new String JavaDoc(ch, start, length)));
214         out.flush();
215
216     } // characters(char[],int,int);
217

218     /** Ignorable whitespace. */
219     public void ignorableWhitespace(char ch[], int start, int length) {
220
221         characters(ch, start, length);
222         out.flush();
223
224     } // ignorableWhitespace(char[],int,int);
225

226     /** End element. */
227     public void endElement(String JavaDoc uri, String JavaDoc local, String JavaDoc raw) {
228
229         out.print("</");
230         out.print(raw);
231         out.print('>');
232         out.flush();
233
234     } // endElement(String)
235

236     //
237
// ErrorHandler methods
238
//
239

240     /** Warning. */
241     public void warning(SAXParseException JavaDoc ex) {
242         System.err.println("[Warning] "+
243                            getLocationString(ex)+": "+
244                            ex.getMessage());
245     }
246
247     /** Error. */
248     public void error(SAXParseException JavaDoc ex) {
249         System.err.println("[Error] "+
250                            getLocationString(ex)+": "+
251                            ex.getMessage());
252     }
253
254     /** Fatal error. */
255     public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
256         System.err.println("[Fatal Error] "+
257                            getLocationString(ex)+": "+
258                            ex.getMessage());
259         throw ex;
260     }
261
262     /** Returns a string of the location. */
263     private String JavaDoc getLocationString(SAXParseException JavaDoc ex) {
264         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
265
266         String JavaDoc systemId = ex.getSystemId();
267         if (systemId != null) {
268             int index = systemId.lastIndexOf('/');
269             if (index != -1)
270                 systemId = systemId.substring(index + 1);
271             str.append(systemId);
272         }
273         str.append(':');
274         str.append(ex.getLineNumber());
275         str.append(':');
276         str.append(ex.getColumnNumber());
277
278         return str.toString();
279
280     } // getLocationString(SAXParseException):String
281

282     //
283
// Protected static methods
284
//
285

286     /** Normalizes the given string. */
287     protected String JavaDoc normalize(String JavaDoc s) {
288         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
289
290         int len = (s != null) ? s.length() : 0;
291         for (int i = 0; i < len; i++) {
292             char ch = s.charAt(i);
293             switch (ch) {
294                 case '<': {
295                     str.append("&lt;");
296                     break;
297                 }
298                 case '>': {
299                     str.append("&gt;");
300                     break;
301                 }
302                 case '&': {
303                     str.append("&amp;");
304                     break;
305                 }
306                 case '"': {
307                     str.append("&quot;");
308                     break;
309                 }
310                 case '\r':
311                 case '\n': {
312                     if (canonical) {
313                         str.append("&#");
314                         str.append(Integer.toString(ch));
315                         str.append(';');
316                         break;
317                     }
318                     // else, default append char
319
}
320                 default: {
321                     str.append(ch);
322                 }
323             }
324         }
325
326         return str.toString();
327
328     } // normalize(String):String
329

330     /** Returns a sorted list of attributes. */
331     protected Attributes JavaDoc sortAttributes(Attributes JavaDoc attrs) {
332
333         AttributesImpl attributes = new AttributesImpl();
334
335         int len = (attrs != null) ? attrs.getLength() : 0;
336         for (int i = 0; i < len; i++) {
337             String JavaDoc name = attrs.getQName(i);
338             int count = attributes.getLength();
339             int j = 0;
340             while (j < count) {
341                 if (name.compareTo(attributes.getQName(j)) < 0) {
342                     break;
343                 }
344                 j++;
345             }
346             attributes.insertAttributeAt(j, name, attrs.getType(i),
347                                          attrs.getValue(i));
348         }
349
350         return attributes;
351
352     } // sortAttributes(AttributeList):AttributeList
353

354     //
355
// Main
356
//
357

358       /** Main program entry point. */
359     public static void main(String JavaDoc argv[]) {
360         ///
361
Arguments argopt = new Arguments();
362
363         argopt.setUsage( new String JavaDoc[] {
364                              "usage: java sax.SAX2Writer (options) uri ...","",
365                              "options:",
366                              " -n | -N Turn on/off namespace [default=on]",
367                              " -v | -V Turn on/off validation [default=on]",
368                              " -s | -S Turn on/off Schema support [default=on]",
369                              " -f | -F Turn on/off Schema full consraint checking [default=off]",
370                              " -c Canonical XML output.",
371                              " -h This help screen."} );
372
373
374
375
376         // is there anything to do?
377
if (argv.length == 0) {
378             argopt.printUsage();
379             System.exit(1);
380         }
381
382         // vars
383
boolean canonical = false;
384         String JavaDoc parserName = DEFAULT_PARSER_NAME;
385
386
387         argopt.parseArgumentTokens(argv, new char[] { 'p'} );
388
389         int c;
390         String JavaDoc arg = null;
391         while ( ( arg = argopt.getlistFiles() ) != null ) {
392
393             outer:
394             while ( (c = argopt.getArguments()) != -1 ){
395                 switch (c) {
396                 case 'c':
397                     canonical = true;
398                     break;
399                 case 'C':
400                     canonical = false;
401                     break;
402                 case 'v':
403                     setValidation = true;
404                     break;
405                 case 'V':
406                     setValidation = false;
407                     break;
408                 case 'N':
409                     setNameSpaces = false;
410                     break;
411                 case 'n':
412                     setNameSpaces = true;
413                     break;
414                 case 'p':
415                     parserName = argopt.getStringParameter();
416                     break;
417                 case 's':
418                     setSchemaSupport = true;
419                     break;
420                 case 'S':
421                     setSchemaSupport = false;
422                     break;
423                 case 'f':
424                     setSchemaFullSupport = true;
425                     break;
426                 case 'F':
427                     setSchemaFullSupport = false;
428                     break;
429                 case '?':
430                 case 'h':
431                 case '-':
432                     argopt.printUsage();
433                     System.exit(1);
434                     break;
435                 case -1:
436                     break outer;
437                 default:
438                     break;
439                 }
440             }
441             // print
442
System.err.println(arg+':');
443             print(parserName, arg, canonical);
444         }
445     } // main(String[])
446

447 } // class SAX2Writer
448
Popular Tags