KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SAXTest


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

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

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

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

36     public static void main (String JavaDoc args[])
37     {
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 JavaDoc driverName =
51         System.getProperty("org.xml.sax.driver",
52                    "org.apache.xerces.parsers.SAXParser");
53     System.out.println("SAX driver class: " +
54                driverName +
55                "\n (you can specify a different one using the " +
56                "org.xml.sax.driver property)");
57     System.out.print("\n");
58
59
60     //
61
// Create the XML reader
62
//
63

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

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

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

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