KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sax > SAXCount


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 org.xml.sax.AttributeList JavaDoc;
61 import org.xml.sax.HandlerBase JavaDoc;
62 import org.xml.sax.Parser JavaDoc;
63 import org.xml.sax.SAXException JavaDoc;
64 import org.xml.sax.SAXParseException JavaDoc;
65 import org.xml.sax.XMLReader JavaDoc;
66 import org.xml.sax.helpers.ParserFactory JavaDoc;
67
68 import util.Arguments;
69
70 /**
71  * A sample SAX counter. This sample program illustrates how to
72  * register a SAX DocumentHandler and receive the callbacks in
73  * order to print information about the document.
74  *
75  * @version
76  */

77 public class SAXCount
78 extends HandlerBase JavaDoc {
79
80     //
81
// Constants
82
//
83

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

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

118     /** Prints the output from the SAX callbacks. */
119     public static void print(String JavaDoc parserName, String JavaDoc uri, boolean validate) {
120
121         try {
122             SAXCount counter = new SAXCount();
123
124             Parser JavaDoc parser = ParserFactory.makeParser(parserName);
125             parser.setDocumentHandler(counter);
126             parser.setErrorHandler(counter);
127             try {
128                 //if (validate && parser instanceof XMLReader)
129
if ( parser instanceof XMLReader JavaDoc ){
130                     ((XMLReader JavaDoc)parser).setFeature( "http://xml.org/sax/features/validation",
131                                                     validate);
132                     ((XMLReader JavaDoc)parser).setFeature( "http://xml.org/sax/features/namespaces",
133                                                     setNameSpaces );
134                     ((XMLReader JavaDoc)parser).setFeature( "http://apache.org/xml/features/validation/schema",
135                                                     setSchemaSupport );
136                     ((XMLReader JavaDoc)parser).setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd",
137                                                     setLoadExternalDTD );
138                     ((XMLReader JavaDoc)parser).setFeature( "http://apache.org/xml/features/validation/schema-full-checking",
139                                                     setSchemaFullSupport );
140
141                 }
142             } catch (Exception JavaDoc ex) {
143             }
144
145             if (warmup) {
146                 if (parser instanceof XMLReader JavaDoc)
147                     ((XMLReader JavaDoc)parser).setFeature("http://apache.org/xml/features/continue-after-fatal-error", true);
148
149                 parser.parse(uri);
150                 warmup = false;
151             }
152             long before = System.currentTimeMillis();
153             parser.parse(uri);
154             long after = System.currentTimeMillis();
155             counter.printResults(uri, after - before);
156         } catch (org.xml.sax.SAXParseException JavaDoc spe) {
157             spe.printStackTrace(System.err);
158         } catch (org.xml.sax.SAXException JavaDoc se) {
159             if (se.getException() != null)
160                 se.getException().printStackTrace(System.err);
161             else
162                 se.printStackTrace(System.err);
163         } catch (Exception JavaDoc e) {
164             e.printStackTrace(System.err);
165         }
166
167     } // print(String,String)
168

169     //
170
// DocumentHandler methods
171
//
172

173     /** Start document. */
174     public void startDocument() {
175
176         if (warmup)
177             return;
178
179         elements = 0;
180         attributes = 0;
181         characters = 0;
182         ignorableWhitespace = 0;
183
184     } // startDocument()
185

186     /** Start element. */
187     public void startElement(String JavaDoc name, AttributeList JavaDoc attrs) {
188
189         if (warmup)
190             return;
191
192         elements++;
193         if (attrs != null) {
194             attributes += attrs.getLength();
195         }
196
197     } // startElement(String,AttributeList)
198

199     /** Characters. */
200     public void characters(char ch[], int start, int length) {
201
202         if (warmup)
203             return;
204
205         characters += length;
206
207     } // characters(char[],int,int);
208

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

219     //
220
// ErrorHandler methods
221
//
222

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

274     //
275
// Public methods
276
//
277

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

297     //
298
// Main
299
//
300

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

392 } // class SAXCount
393
Popular Tags