KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sax > SAXWriter


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.AttributeList JavaDoc;
65 import org.xml.sax.HandlerBase JavaDoc;
66 import org.xml.sax.Parser JavaDoc;
67 import org.xml.sax.SAXException JavaDoc;
68 import org.xml.sax.SAXParseException JavaDoc;
69 import org.xml.sax.XMLReader JavaDoc;
70 import org.xml.sax.helpers.ParserFactory JavaDoc;
71
72 import sax.helpers.AttributeListImpl;
73 import util.Arguments;
74
75
76
77 /**
78  * A sample SAX writer. This sample program illustrates how to
79  * register a SAX DocumentHandler and receive the callbacks in
80  * order to print a document that is parsed.
81  *
82  * @version
83  */

84 public class SAXWriter
85 extends HandlerBase JavaDoc {
86
87     //
88
// Constants
89
//
90

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

107     /** Print writer. */
108     protected PrintWriter JavaDoc out;
109
110     /** Canonical output. */
111     protected boolean canonical;
112
113     //
114
// Constructors
115
//
116

117     /** Default constructor. */
118     public SAXWriter(boolean canonical) throws UnsupportedEncodingException JavaDoc {
119         this(null, canonical);
120     }
121
122     protected SAXWriter(String JavaDoc encoding, boolean canonical) throws UnsupportedEncodingException JavaDoc {
123
124         if (encoding == null) {
125             encoding = "UTF8";
126         }
127
128         out = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(System.out, encoding));
129         this.canonical = canonical;
130
131     } // <init>(String,boolean)
132

133     //
134
// Public static methods
135
//
136

137     /** Prints the output from the SAX callbacks. */
138     public static void print(String JavaDoc parserName, String JavaDoc uri, boolean canonical) {
139
140         try {
141             HandlerBase JavaDoc handler = new SAXWriter(canonical);
142
143             Parser JavaDoc parser = ParserFactory.makeParser(parserName);
144
145
146             if ( parser instanceof XMLReader JavaDoc ){
147                 ((XMLReader JavaDoc)parser).setFeature( "http://xml.org/sax/features/validation",
148                                                 setValidation);
149                 ((XMLReader JavaDoc)parser).setFeature( "http://xml.org/sax/features/namespaces",
150                                                 setNameSpaces );
151                 ((XMLReader JavaDoc)parser).setFeature( "http://apache.org/xml/features/validation/schema",
152                                                 setSchemaSupport );
153                 ((XMLReader JavaDoc)parser).setFeature( "http://apache.org/xml/features/validation/schema-full-checking",
154                                                 setSchemaFullSupport );
155
156             }
157
158
159
160
161             parser.setDocumentHandler(handler);
162             parser.setErrorHandler(handler);
163             parser.parse(uri);
164         } catch (Exception JavaDoc e) {
165             e.printStackTrace(System.err);
166         }
167
168     } // print(String,String,boolean)
169

170     //
171
// DocumentHandler methods
172
//
173

174     /** Processing instruction. */
175     public void processingInstruction(String JavaDoc target, String JavaDoc data) {
176
177         out.print("<?");
178         out.print(target);
179         if (data != null && data.length() > 0) {
180             out.print(' ');
181             out.print(data);
182         }
183         out.print("?>");
184
185     } // processingInstruction(String,String)
186

187     /** Start document. */
188     public void startDocument() {
189
190         if (!canonical) {
191             out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
192         }
193
194     } // startDocument()
195

196     /** Start element. */
197     public void startElement(String JavaDoc name, AttributeList JavaDoc attrs) {
198
199         out.print('<');
200         out.print(name);
201         if (attrs != null) {
202             attrs = sortAttributes(attrs);
203             int len = attrs.getLength();
204             for (int i = 0; i < len; i++) {
205                 out.print(' ');
206                 out.print(attrs.getName(i));
207                 out.print("=\"");
208                 out.print(normalize(attrs.getValue(i)));
209                 out.print('"');
210             }
211         }
212         out.print('>');
213
214     } // startElement(String,AttributeList)
215

216     /** Characters. */
217     public void characters(char ch[], int start, int length) {
218
219         out.print(normalize(new String JavaDoc(ch, start, length)));
220
221     } // characters(char[],int,int);
222

223     /** Ignorable whitespace. */
224     public void ignorableWhitespace(char ch[], int start, int length) {
225
226         characters(ch, start, length);
227
228     } // ignorableWhitespace(char[],int,int);
229

230     /** End element. */
231     public void endElement(String JavaDoc name) {
232
233         out.print("</");
234         out.print(name);
235         out.print('>');
236
237     } // endElement(String)
238

239     /** End document. */
240     public void endDocument() {
241
242         out.flush();
243
244     } // endDocument()
245

246     //
247
// ErrorHandler methods
248
//
249

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

292     //
293
// Protected static methods
294
//
295

296     /** Normalizes the given string. */
297     protected String JavaDoc normalize(String JavaDoc s) {
298         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
299
300         int len = (s != null) ? s.length() : 0;
301         for (int i = 0; i < len; i++) {
302             char ch = s.charAt(i);
303             switch (ch) {
304             case '<': {
305                     str.append("&lt;");
306                     break;
307                 }
308             case '>': {
309                     str.append("&gt;");
310                     break;
311                 }
312             case '&': {
313                     str.append("&amp;");
314                     break;
315                 }
316             case '"': {
317                     str.append("&quot;");
318                     break;
319                 }
320             case '\'': {
321                     str.append("&apos;");
322                     break;
323                 }
324             case '\r':
325             case '\n': {
326                     if (canonical) {
327                         str.append("&#");
328                         str.append(Integer.toString(ch));
329                         str.append(';');
330                         break;
331                     }
332                     // else, default append char
333
}
334             default: {
335                     str.append(ch);
336                 }
337             }
338         }
339
340         return str.toString();
341
342     } // normalize(String):String
343

344     /** Returns a sorted list of attributes. */
345     protected AttributeList JavaDoc sortAttributes(AttributeList JavaDoc attrs) {
346
347         AttributeListImpl attributes = new AttributeListImpl();
348         int len = (attrs != null) ? attrs.getLength() : 0;
349         for (int i = 0; i < len; i++) {
350             String JavaDoc name = attrs.getName(i);
351             int count = attributes.getLength();
352             int j = 0;
353             while (j < count) {
354                 if (name.compareTo(attributes.getName(j)) < 0) {
355                     break;
356                 }
357                 j++;
358             }
359             attributes.insertAttributeAt(j, name, attrs.getType(i),
360                                          attrs.getValue(i));
361         }
362
363         return attributes;
364
365     } // sortAttributes(AttributeList):AttributeList
366

367     //
368
// Main
369
//
370

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

460 } // class SAXWriter
461
Popular Tags