KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jaxp > ParserAPIUsage


1 /*
2  * Copyright 2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package jaxp;
18
19 import java.util.Vector JavaDoc;
20
21 import javax.xml.XMLConstants JavaDoc;
22 import javax.xml.parsers.DocumentBuilder JavaDoc;
23 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
24 import javax.xml.parsers.SAXParser JavaDoc;
25 import javax.xml.parsers.SAXParserFactory JavaDoc;
26 import javax.xml.transform.stream.StreamSource JavaDoc;
27 import javax.xml.validation.Schema JavaDoc;
28 import javax.xml.validation.SchemaFactory JavaDoc;
29
30 import org.xml.sax.SAXException JavaDoc;
31 import org.xml.sax.SAXParseException JavaDoc;
32 import org.xml.sax.helpers.DefaultHandler JavaDoc;
33
34 /**
35  * <p>A sample which demonstrates usage of the JAXP 1.3 Parser API.</p>
36  *
37  * @author Michael Glavassevich, IBM
38  * @author Ankit Pasricha, IBM
39  *
40  * @version $Id: ParserAPIUsage.java,v 1.2 2005/06/10 03:43:46 mrglavas Exp $
41  */

42 public class ParserAPIUsage extends DefaultHandler JavaDoc {
43     
44     // default settings
45

46     /** Default API to use. */
47     protected static final String JavaDoc DEFAULT_API_TO_USE = "sax";
48     
49     /** Default XInclude processing support (false). */
50     protected static final boolean DEFAULT_XINCLUDE = false;
51     
52     /** Default secure processing support (false). */
53     protected static final boolean DEFAULT_SECURE_PROCESSING = false;
54     
55     //
56
// Constructors
57
//
58

59     /** Default constructor. */
60     public ParserAPIUsage() {
61     } // <init>()
62

63     //
64
// ErrorHandler methods
65
//
66

67     /** Warning. */
68     public void warning(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
69         printError("Warning", ex);
70     } // warning(SAXParseException)
71

72     /** Error. */
73     public void error(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
74         printError("Error", ex);
75     } // error(SAXParseException)
76

77     /** Fatal error. */
78     public void fatalError(SAXParseException JavaDoc ex) throws SAXException JavaDoc {
79         printError("Fatal Error", ex);
80         throw ex;
81     } // fatalError(SAXParseException)
82

83     //
84
// Protected methods
85
//
86

87     /** Prints the error message. */
88     protected void printError(String JavaDoc type, SAXParseException JavaDoc ex) {
89
90         System.err.print("[");
91         System.err.print(type);
92         System.err.print("] ");
93         String JavaDoc systemId = ex.getSystemId();
94         if (systemId != null) {
95             int index = systemId.lastIndexOf('/');
96             if (index != -1)
97                 systemId = systemId.substring(index + 1);
98             System.err.print(systemId);
99         }
100         System.err.print(':');
101         System.err.print(ex.getLineNumber());
102         System.err.print(':');
103         System.err.print(ex.getColumnNumber());
104         System.err.print(": ");
105         System.err.print(ex.getMessage());
106         System.err.println();
107         System.err.flush();
108
109     } // printError(String,SAXParseException)
110

111     public static void main(String JavaDoc[] argv) {
112         
113         // is there anything to do?
114
if (argv.length == 0) {
115             printUsage();
116             System.exit(1);
117         }
118         
119         // variables
120
ParserAPIUsage parserAPIUsage = new ParserAPIUsage();
121         Vector JavaDoc schemas = null;
122         String JavaDoc docURI = argv[argv.length - 1];
123         String JavaDoc apiToUse = DEFAULT_API_TO_USE;
124         boolean xincludeProcessing = DEFAULT_XINCLUDE;
125         boolean secureProcessing = DEFAULT_SECURE_PROCESSING;
126         
127         // process arguments
128
for (int i = 0; i < argv.length - 1; ++i) {
129             String JavaDoc arg = argv[i];
130             if (arg.startsWith("-")) {
131                 String JavaDoc option = arg.substring(1);
132                 if (arg.equals("-a")) {
133                     // process -a: schema documents
134
if (schemas == null) {
135                         schemas = new Vector JavaDoc();
136                     }
137                     while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
138                         schemas.add(arg);
139                         ++i;
140                     }
141                     continue;
142                 }
143                 if (arg.equals("-api")) {
144                     if (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
145                         if (arg.equals("sax") || arg.equals("dom")) {
146                             apiToUse = arg;
147                         }
148                         else {
149                             System.err.println("error: unknown source type ("+arg+").");
150                         }
151                     }
152                     continue;
153                 }
154                 if (option.equalsIgnoreCase("xi")) {
155                     xincludeProcessing = option.equals("xi");
156                     continue;
157                 }
158                 if (option.equalsIgnoreCase("sp")) {
159                     secureProcessing = option.equals("sp");
160                     continue;
161                 }
162                 if (option.equals("h")) {
163                     printUsage();
164                     continue;
165                 }
166                 System.err.println("error: unknown option ("+option+").");
167                 continue;
168             }
169         }
170         
171         try {
172             // Build Schema from sources if there are any
173
Schema JavaDoc schema = null;
174             if (schemas != null && schemas.size() > 0) {
175                 SchemaFactory JavaDoc factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
176                 factory.setErrorHandler(parserAPIUsage);
177                 final int length = schemas.size();
178                 StreamSource JavaDoc[] sources = new StreamSource JavaDoc[length];
179                 for (int j = 0; j < length; ++j) {
180                     sources[j] = new StreamSource JavaDoc((String JavaDoc) schemas.elementAt(j));
181                 }
182                 schema = factory.newSchema(sources);
183             }
184             
185             if ("dom".equals(apiToUse)) {
186                 // Create a DocumentBuilderFactory
187
DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
188                 dbf.setNamespaceAware(true);
189                 dbf.setXIncludeAware(xincludeProcessing);
190                 dbf.setSchema(schema);
191                 dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, secureProcessing);
192                 
193                 // Create a DocumentBuilder
194
DocumentBuilder JavaDoc db = dbf.newDocumentBuilder();
195                 
196                 // Parse, reset the parser and then parse again.
197
db.setErrorHandler(parserAPIUsage);
198                 db.parse(docURI);
199                 db.reset();
200                 db.setErrorHandler(parserAPIUsage);
201                 db.parse(docURI);
202             }
203             // "sax".equals(apiToUse)
204
else {
205                 // Create a SAXParserFactory
206
SAXParserFactory JavaDoc spf = SAXParserFactory.newInstance();
207                 spf.setNamespaceAware(true);
208                 spf.setXIncludeAware(xincludeProcessing);
209                 spf.setSchema(schema);
210                 spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, secureProcessing);
211                 
212                 // Create a SAXParser
213
SAXParser JavaDoc sp = spf.newSAXParser();
214                 
215                 // Parse, reset the parser and then parse again.
216
sp.parse(docURI, parserAPIUsage);
217                 sp.reset();
218                 sp.parse(docURI, parserAPIUsage);
219             }
220         }
221         catch (SAXParseException JavaDoc e) {
222             // ignore
223
}
224         catch (Exception JavaDoc e) {
225             System.err.println("error: Parse error occurred - "+e.getMessage());
226             if (e instanceof SAXException JavaDoc) {
227                 Exception JavaDoc nested = ((SAXException JavaDoc)e).getException();
228                 if (nested != null) {
229                     e = nested;
230                 }
231             }
232             e.printStackTrace(System.err);
233         }
234         
235     } // main(String[])
236

237     //
238
// Private static methods
239
//
240

241     private static void printUsage() {
242
243         System.err.println("usage: java jaxp.ParserAPIUsage (options) uri");
244         System.err.println();
245         
246         System.err.println("options:");
247         System.err.println(" -a uri ... Provide a list of schema documents.");
248         System.err.println(" -api (sax|dom) Select API to use (sax|dom).");
249         System.err.println(" -xi | -XI Turn on/off XInclude processing.");
250         System.err.println(" -sp | -SP Turn on/off secure processing.");
251         System.err.println(" -h This help screen.");
252         
253         System.err.println();
254         System.err.println("defaults:");
255         System.err.println(" API to use: " + DEFAULT_API_TO_USE);
256         System.err.print(" XInclude: ");
257         System.err.println(DEFAULT_XINCLUDE ? "on" : "off");
258         System.err.print(" Secure processing: ");
259         System.err.println(DEFAULT_SECURE_PROCESSING ? "on" : "off");
260         
261     } // printUsage()
262

263 } // ParserAPIUsage
264
Popular Tags