KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > htmlparser > tests > SAXTest


1 // SAXTest.java - test application for SAX2
2

3 package org.htmlparser.tests;
4
5 import java.io.IOException JavaDoc;
6
7 import java.net.MalformedURLException JavaDoc;
8 import java.net.URL JavaDoc;
9
10 import org.xml.sax.Attributes JavaDoc;
11 import org.xml.sax.ContentHandler JavaDoc;
12 import org.xml.sax.ErrorHandler JavaDoc;
13 import org.xml.sax.Locator JavaDoc;
14 import org.xml.sax.SAXException JavaDoc;
15 import org.xml.sax.SAXNotRecognizedException JavaDoc;
16 import org.xml.sax.SAXNotSupportedException JavaDoc;
17 import org.xml.sax.SAXParseException JavaDoc;
18 import org.xml.sax.XMLReader JavaDoc;
19
20 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
21
22
23 /**
24  * Test class for SAX2.
25  */

26 public class SAXTest implements ContentHandler JavaDoc, ErrorHandler JavaDoc
27 {
28
29     ////////////////////////////////////////////////////////////////////
30
// Main app.
31
////////////////////////////////////////////////////////////////////
32

33
34     /**
35      * Main application entry point.
36      */

37     public static void main (String JavaDoc args[])
38     {
39     System.out.println("************************************" +
40                "************************************");
41     System.out.println("* Testing SAX2");
42     System.out.println("************************************" +
43                "************************************");
44     System.out.print("\n");
45
46     //
47
// Figure out the XML reader
48
//
49

50 // String driverName =
51
// System.getProperty("org.xml.sax.driver",
52
// "org.apache.xerces.parsers.SAXParser");
53
String JavaDoc driverName = "org.htmlparser.sax.XMLReader";
54     System.out.println("SAX driver class: " +
55                driverName +
56                "\n (you can specify a different one using the " +
57                "org.xml.sax.driver property)");
58     System.out.print("\n");
59
60
61     //
62
// Create the XML reader
63
//
64

65     System.out.println("Now, we'll try to create an instance of the " +
66                "driver, using XMLReaderFactory");
67     XMLReader JavaDoc reader = null;
68     try {
69         reader = XMLReaderFactory.createXMLReader(driverName);
70     } catch (SAXException JavaDoc e) {
71         System.out.println("Failed to create XMLReader: " +
72                    e.getMessage() +
73                    "\nMake sure that the class actually " +
74                    "exists and is present on your CLASSPATH" +
75                    "\nor specify a different class using the " +
76                    "org.xml.sax.driver property");
77         System.exit(1);
78     }
79     System.out.println("XMLReader created successfully\n");
80
81
82     //
83
// Check features.
84
//
85
System.out.println("Checking defaults for some well-known features:");
86     checkFeature(reader, "http://xml.org/sax/features/namespaces");
87     checkFeature(reader, "http://xml.org/sax/features/namespace-prefixes");
88     checkFeature(reader, "http://xml.org/sax/features/string-interning");
89     checkFeature(reader, "http://xml.org/sax/features/validation");
90     checkFeature(reader,
91              "http://xml.org/sax/features/external-general-entities");
92     checkFeature(reader,
93              "http://xml.org/sax/features/external-parameter-entities");
94     System.out.print("\n");
95
96     
97     //
98
// Assign handlers.
99
//
100
System.out.println("Creating and assigning handlers\n");
101     SAXTest handler = new SAXTest();
102     reader.setContentHandler(handler);
103     reader.setErrorHandler(handler);
104
105     //
106
// Parse documents.
107
//
108
if (args.length > 0) {
109         for (int i = 0; i < args.length; i++) {
110         String JavaDoc systemId = makeAbsoluteURL(args[i]);
111         System.out.println("Trying file " + systemId);
112         try {
113             reader.parse(systemId);
114         } catch (SAXException JavaDoc e1) {
115             System.out.println(systemId +
116                        " failed with XML error: " +
117                        e1.getMessage());
118         } catch (IOException JavaDoc e2) {
119             System.out.println(systemId +
120                        " failed with I/O error: " +
121                        e2.getMessage());
122         }
123         System.out.print("\n");
124         }
125     } else {
126         System.out.println("No documents supplied on command line; " +
127                    "parsing skipped.");
128     }
129
130
131     //
132
// Done.
133
//
134
System.out.println("SAX2 test finished.");
135     }
136
137
138     /**
139      * Check and display the value of a feature.
140      */

141     private static void checkFeature (XMLReader JavaDoc reader, String JavaDoc name)
142     {
143     try {
144         System.out.println(" " +
145                    name +
146                    " = " +
147                    reader.getFeature(name));
148     } catch (SAXNotRecognizedException JavaDoc e) {
149         System.out.println("XMLReader does not recognize feature " +
150                    name);
151     } catch (SAXNotSupportedException JavaDoc e) {
152         System.out.println("XMLReader recognizes feature " +
153                    name +
154                    " but does not support checking its value");
155     }
156     }
157
158
159     /**
160      * Construct an absolute URL if necessary.
161      *
162      * This method is useful for relative file paths on a command
163      * line; it converts them to absolute file: URLs, using the
164      * correct path separator. This method is based on an
165      * original suggestion by James Clark.
166      *
167      * @param url The (possibly relative) URL.
168      * @return An absolute URL of some sort.
169      */

170     private static String JavaDoc makeAbsoluteURL (String JavaDoc url)
171     {
172     URL JavaDoc baseURL;
173     
174     String JavaDoc currentDirectory = System.getProperty("user.dir");
175     String JavaDoc fileSep = System.getProperty("file.separator");
176     String JavaDoc file = currentDirectory.replace(fileSep.charAt(0), '/') + '/';
177     
178     if (file.charAt(0) != '/') {
179         file = "/" + file;
180     }
181
182     try {
183         baseURL = new URL JavaDoc("file", null, file);
184         return new URL JavaDoc(baseURL, url).toString();
185     } catch (MalformedURLException JavaDoc e) {
186         System.err.println(url + ": " + e.getMessage());
187         return url;
188     }
189     }
190
191     private static String JavaDoc makeNSName (String JavaDoc uri, String JavaDoc localName,
192                       String JavaDoc qName)
193     {
194     if (uri.equals(""))
195         uri = "[none]";
196     if (localName.equals(""))
197         localName = "[none]";
198     if (qName.equals(""))
199         qName = "[none]";
200     return uri + '/' + localName + '/' + qName;
201     }
202
203     private static String JavaDoc escapeData (char ch[], int start, int length)
204     {
205     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
206     for (int i = start; i < start + length; i++) {
207         switch(ch[i]) {
208         case '\n':
209         buf.append("\\n");
210         break;
211         case '\t':
212         buf.append("\\t");
213         break;
214         case '\r':
215         buf.append("\\r");
216         break;
217         default:
218         buf.append(ch[i]);
219         break;
220         }
221     }
222     return buf.toString();
223     }
224
225
226     ////////////////////////////////////////////////////////////////////
227
// Implementation of org.xml.sax.ContentHandler.
228
////////////////////////////////////////////////////////////////////
229

230     public void setDocumentLocator (Locator JavaDoc locator)
231     {
232     System.out.println(" EVENT: setDocumentLocator");
233     }
234
235     public void startDocument ()
236     throws SAXException JavaDoc
237     {
238     System.out.println(" EVENT: startDocument");
239     }
240
241     public void endDocument ()
242     throws SAXException JavaDoc
243     {
244     System.out.println(" EVENT: endDocument");
245     }
246
247     public void startPrefixMapping (String JavaDoc prefix, String JavaDoc uri)
248     throws SAXException JavaDoc
249     {
250     System.out.println(" EVENT: startPrefixMapping " +
251                prefix + " = " + uri);
252     }
253
254     public void endPrefixMapping (String JavaDoc prefix)
255     throws SAXException JavaDoc
256     {
257     System.out.println(" EVENT: endPrefixMapping " + prefix);
258     }
259
260     public void startElement (String JavaDoc namespaceURI, String JavaDoc localName,
261                   String JavaDoc qName, Attributes JavaDoc atts)
262     throws SAXException JavaDoc
263     {
264     System.out.println(" EVENT: startElement " +
265                makeNSName(namespaceURI, localName, qName));
266     int attLen = atts.getLength();
267     for (int i = 0; i < attLen; i++) {
268         char ch[] = atts.getValue(i).toCharArray();
269         System.out.println(" Attribute " +
270                    makeNSName(atts.getURI(i),
271                       atts.getLocalName(i),
272                       atts.getQName(i)) +
273                    '=' +
274                    escapeData(ch, 0, ch.length));
275     }
276     }
277
278     public void endElement (String JavaDoc namespaceURI, String JavaDoc localName,
279                 String JavaDoc qName)
280     throws SAXException JavaDoc
281     {
282     System.out.println(" EVENT: endElement " +
283                makeNSName(namespaceURI, localName, qName));
284     }
285
286     public void characters (char ch[], int start, int length)
287     throws SAXException JavaDoc
288     {
289     System.out.println(" EVENT: characters " +
290                escapeData(ch, start, length));
291     }
292
293     public void ignorableWhitespace (char ch[], int start, int length)
294     throws SAXException JavaDoc
295     {
296     System.out.println(" EVENT: ignorableWhitespace " +
297                escapeData(ch, start, length));
298     }
299
300     public void processingInstruction (String JavaDoc target, String JavaDoc data)
301     throws SAXException JavaDoc
302     {
303     System.out.println(" EVENT: processingInstruction " +
304                target + ' ' + data);
305     }
306
307     public void skippedEntity (String JavaDoc name)
308     throws SAXException JavaDoc
309     {
310     System.out.println(" EVENT: skippedEntity " + name);
311     }
312
313
314     ////////////////////////////////////////////////////////////////////
315
// Implementation of org.xml.sax.ErrorHandler.
316
////////////////////////////////////////////////////////////////////
317

318     public void warning (SAXParseException JavaDoc e)
319     throws SAXException JavaDoc
320     {
321     System.out.println(" EVENT: warning " +
322                e.getMessage() + ' ' +
323                e.getSystemId() + ' ' +
324                e.getLineNumber() + ' ' +
325                e.getColumnNumber());
326     }
327
328     public void error (SAXParseException JavaDoc e)
329     throws SAXException JavaDoc
330     {
331     System.out.println(" EVENT: error " +
332                e.getMessage() + ' ' +
333                e.getSystemId() + ' ' +
334                e.getLineNumber() + ' ' +
335                e.getColumnNumber());
336     }
337
338     public void fatalError (SAXParseException JavaDoc e)
339     throws SAXException JavaDoc
340     {
341     System.out.println(" EVENT: fatal error " +
342                e.getMessage() + ' ' +
343                e.getSystemId() + ' ' +
344                e.getLineNumber() + ' ' +
345                e.getColumnNumber());
346     }
347
348 }
349
350 // end of SAXTest.java
351
Popular Tags