KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sax > SAX2Count


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 1999,2000 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 org.xml.sax.Attributes JavaDoc;
61 import org.xml.sax.SAXException JavaDoc;
62 import org.xml.sax.SAXParseException JavaDoc;
63 import org.xml.sax.XMLReader JavaDoc;
64 import org.xml.sax.helpers.DefaultHandler JavaDoc;
65
66 import util.Arguments;
67
68 /**
69  * A sample SAX2 counter. This sample program illustrates how to
70  * register a SAX2 ContentHandler and receive the callbacks in
71  * order to print information about the document.
72  *
73  * @version $Id: SAX2Count.java,v 1.2 2005/01/26 08:28:44 jkjome Exp $
74  */

75 public class SAX2Count
76 extends DefaultHandler JavaDoc {
77
78     //
79
// Constants
80
//
81

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

98     private static boolean warmup = false;
99
100     /** Elements. */
101     private long elements;
102
103     /** Attributes. */
104     private long attributes;
105
106     /** Characters. */
107     private long characters;
108
109     /** Ignorable whitespace. */
110     private long ignorableWhitespace;
111
112     //
113
// Public static methods
114
//
115

116     /** Prints the output from the SAX callbacks. */
117     public static void print(String JavaDoc parserName, String JavaDoc uri, boolean validate) {
118
119         try {
120             SAX2Count counter = new SAX2Count();
121
122             XMLReader JavaDoc parser = (XMLReader JavaDoc)Class.forName(parserName).newInstance();
123             parser.setContentHandler(counter);
124             parser.setErrorHandler(counter);
125
126
127
128             //if (validate)
129
// parser.setFeature("http://xml.org/sax/features/validation", true);
130

131             parser.setFeature( "http://xml.org/sax/features/validation",
132                                                validate);
133
134             parser.setFeature( "http://xml.org/sax/features/namespaces",
135                                                setNameSpaces );
136
137             parser.setFeature( "http://apache.org/xml/features/validation/schema",
138                                                setSchemaSupport );
139
140             parser.setFeature( "http://apache.org/xml/features/validation/schema-full-checking",
141                                                setSchemaFullSupport );
142
143             if (warmup) {
144                 parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true);
145                 parser.parse(uri);
146                 warmup = false;
147             }
148             long before = System.currentTimeMillis();
149             parser.parse(uri);
150             long after = System.currentTimeMillis();
151             counter.printResults(uri, after - before);
152         } catch (org.xml.sax.SAXParseException JavaDoc spe) {
153             spe.printStackTrace(System.err);
154         } catch (org.xml.sax.SAXException JavaDoc se) {
155             if (se.getException() != null)
156                 se.getException().printStackTrace(System.err);
157             else
158                 se.printStackTrace(System.err);
159         } catch (Exception JavaDoc e) {
160             e.printStackTrace(System.err);
161         }
162
163     } // print(String,String)
164

165     //
166
// DocumentHandler methods
167
//
168

169     /** Start document. */
170     public void startDocument() {
171
172         if (warmup)
173             return;
174
175         elements = 0;
176         attributes = 0;
177         characters = 0;
178         ignorableWhitespace = 0;
179
180     } // startDocument()
181

182     /** Start element. */
183     public void startElement(String JavaDoc uri, String JavaDoc local, String JavaDoc raw, Attributes JavaDoc attrs) {
184
185         if (warmup)
186             return;
187
188         elements++;
189         if (attrs != null) {
190             attributes += attrs.getLength();
191         }
192
193     } // startElement(String,AttributeList)
194

195     /** Characters. */
196     public void characters(char ch[], int start, int length) {
197
198         if (warmup)
199             return;
200
201         characters += length;
202
203     } // characters(char[],int,int);
204

205     /** Ignorable whitespace. */
206     public void ignorableWhitespace(char ch[], int start, int length) {
207
208         if (warmup)
209             return;
210
211         ignorableWhitespace += length;
212
213     } // ignorableWhitespace(char[],int,int);
214

215     //
216
// ErrorHandler methods
217
//
218

219     /** Warning. */
220     public void warning(SAXParseException JavaDoc ex) {
221         if (warmup)
222             return;
223
224         System.err.println("[Warning] "+
225                            getLocationString(ex)+": "+
226                            ex.getMessage());
227     }
228
229     /** Error. */
230     public void error(SAXParseException JavaDoc ex) {
231         if (warmup)
232             return;
233
234         System.err.println("[Error] "+
235                            getLocationString(ex)+": "+
236                            ex.getMessage());
237     }
238
239     /** Fatal error. */
240     public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
241         if (warmup)
242             return;
243
244         System.err.println("[Fatal Error] "+
245                            getLocationString(ex)+": "+
246                            ex.getMessage());
247 // throw ex;
248
}
249
250     /** Returns a string of the location. */
251     private String JavaDoc getLocationString(SAXParseException JavaDoc ex) {
252         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
253
254         String JavaDoc systemId = ex.getSystemId();
255         if (systemId != null) {
256             int index = systemId.lastIndexOf('/');
257             if (index != -1)
258                 systemId = systemId.substring(index + 1);
259             str.append(systemId);
260         }
261         str.append(':');
262         str.append(ex.getLineNumber());
263         str.append(':');
264         str.append(ex.getColumnNumber());
265
266         return str.toString();
267
268     } // getLocationString(SAXParseException):String
269

270     //
271
// Public methods
272
//
273

274     /** Prints the results. */
275     public void printResults(String JavaDoc uri, long time) {
276
277         // filename.xml: 631 ms (4 elems, 0 attrs, 78 spaces, 0 chars)
278
System.out.print(uri);
279         System.out.print(": ");
280         System.out.print(time);
281         System.out.print(" ms (");
282         System.out.print(elements);
283         System.out.print(" elems, ");
284         System.out.print(attributes);
285         System.out.print(" attrs, ");
286         System.out.print(ignorableWhitespace);
287         System.out.print(" spaces, ");
288         System.out.print(characters);
289         System.out.print(" chars)");
290         System.out.println();
291     } // printResults(String,long)
292

293     //
294
// Main
295
//
296

297     /** Main program entry point. */
298     public static void main(String JavaDoc argv[]) {
299
300         Arguments argopt = new Arguments();
301         argopt.setUsage( new String JavaDoc[]
302                          { "usage: java sax.SAX2Count (options) uri ...","",
303                              "options:",
304                              " -p name Specify SAX parser by name.",
305                              " -n | -N Turn on/off namespace [default=on]",
306                              " -v | -V Turn on/off validation [default=off]",
307                              " -s | -S Turn on/off Schema support [default=on]",
308                              " -f | -F Turn on/off Schema full consraint checking [default=off]",
309                              " -d | -D Turn on/off deferred DOM [default=on]",
310                              " -w Warmup the parser before timing.",
311                              " -h This help screen."} );
312
313
314         // is there anything to do?
315
if (argv.length == 0) {
316             argopt.printUsage();
317             System.exit(1);
318         }
319
320         // vars
321
String JavaDoc parserName = DEFAULT_PARSER_NAME;
322
323         argopt.parseArgumentTokens(argv, new char[] { 'p'} );
324
325         int c;
326         String JavaDoc arg = null;
327         while ( ( arg = argopt.getlistFiles() ) != null ) {
328             outer:
329
330             while ( (c = argopt.getArguments()) != -1 ){
331                 //System.out.println( "c =" + c );
332
switch (c) {
333                 case 'v':
334                     setValidation = true;
335                     break;
336                 case 'V':
337                     setValidation = false;
338                     break;
339                 case 'N':
340                     setNameSpaces = false;
341                     break;
342                 case 'n':
343                     setNameSpaces = true;
344                     break;
345                 case 'p':
346                     parserName = argopt.getStringParameter();
347                     break;
348                 case 's':
349                     setSchemaSupport = true;
350                     break;
351                 case 'S':
352                     setSchemaSupport = false;
353                     break;
354                 case 'f':
355                     setSchemaFullSupport = true;
356                     break;
357                 case 'F':
358                     setSchemaFullSupport = false;
359                     break;
360                 case '?':
361                 case 'h':
362                 case '-':
363                     argopt.printUsage();
364                     System.exit(1);
365                     break;
366                 case 'w':
367                     warmup = true;
368                     break;
369                 case -1:
370                     break outer;
371                 default:
372                     break;
373                 }
374
375             }
376
377             // print uri
378
print(parserName, arg, setValidation);
379             ///
380
}
381     } // main(String[])
382

383 } // class SAX2Count
384
Popular Tags