KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > xni > XMLGrammarBuilder


1 /*
2  * Copyright 1999-2004 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 xni;
18
19 import org.apache.xerces.parsers.XMLGrammarPreparser;
20 import org.apache.xerces.parsers.IntegratedParserConfiguration;
21 import org.apache.xerces.util.SymbolTable;
22 import org.apache.xerces.util.XMLGrammarPoolImpl;
23 import org.apache.xerces.impl.Constants;
24
25 import org.apache.xerces.xni.grammars.XMLGrammarDescription;
26 import org.apache.xerces.xni.grammars.Grammar;
27 import org.apache.xerces.xni.parser.XMLInputSource;
28 import org.apache.xerces.xni.parser.XMLParserConfiguration;
29
30 import java.util.Vector JavaDoc;
31
32 /**
33  * This sample program illustrates how to use Xerces2's grammar
34  * preparsing and caching functionality. It permits either DTD or
35  * Schema grammars to be parsed, and then allows instance documents to
36  * be validated with them.
37  * <p> Note that, for access to a grammar's contents (via Xerces's
38  * Schema Component model interfaces), slightly different methods need
39  * to be used. Nonetheless, this should go some way to indicating how
40  * grammar preparsing and caching can be coupled in Xerces to achieve
41  * better performance. It's also hoped this sample shows the way
42  * towards combining this functionality in a DOM or SAX context.
43  *
44  * @author Neil Graham, IBM
45  * @version $Id: XMLGrammarBuilder.java,v 1.9 2004/02/24 23:41:05 mrglavas Exp $
46  */

47 public class XMLGrammarBuilder {
48
49     //
50
// Constants
51
//
52

53     // property IDs:
54

55     /** Property identifier: symbol table. */
56     public static final String JavaDoc SYMBOL_TABLE =
57         Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
58
59     /** Property identifier: grammar pool. */
60     public static final String JavaDoc GRAMMAR_POOL =
61         Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
62
63     // feature ids
64

65     /** Namespaces feature id (http://xml.org/sax/features/namespaces). */
66     protected static final String JavaDoc NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";
67
68     /** Validation feature id (http://xml.org/sax/features/validation). */
69     protected static final String JavaDoc VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";
70
71     /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
72     protected static final String JavaDoc SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema";
73
74     /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */
75     protected static final String JavaDoc SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
76
77     // a larg(ish) prime to use for a symbol table to be shared
78
// among
79
// potentially man parsers. Start one as close to 2K (20
80
// times larger than normal) and see what happens...
81
public static final int BIG_PRIME = 2039;
82
83     // default settings
84

85     /** Default Schema full checking support (false). */
86     protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false;
87
88     //
89
// MAIN
90
//
91

92     /** Main program entry point. */
93     public static void main(String JavaDoc argv[]) {
94
95         // too few parameters
96
if (argv.length < 2) {
97             printUsage();
98             System.exit(1);
99         }
100
101         XMLParserConfiguration parserConfiguration = null;
102         String JavaDoc arg = null;
103         int i = 0;
104
105         arg = argv[i];
106         if (arg.equals("-p")) {
107             // get parser name
108
i++;
109             String JavaDoc parserName = argv[i];
110
111             // create parser
112
try {
113                 ClassLoader JavaDoc cl = ObjectFactory.findClassLoader();
114                 parserConfiguration = (XMLParserConfiguration)ObjectFactory.newInstance(parserName, cl, true);
115             }
116             catch (Exception JavaDoc e) {
117                 parserConfiguration = null;
118                 System.err.println("error: Unable to instantiate parser configuration ("+parserName+")");
119             }
120             i++;
121         }
122         arg = argv[i];
123         // process -d
124
Vector JavaDoc externalDTDs = null;
125         if (arg.equals("-d")) {
126             externalDTDs= new Vector JavaDoc();
127             i++;
128             while (i < argv.length && !(arg = argv[i]).startsWith("-")) {
129                 externalDTDs.addElement(arg);
130                 i++;
131             }
132             // has to be at least one dTD or schema , and there has to be other parameters
133
if (externalDTDs.size() == 0) {
134                 printUsage();
135                 System.exit(1);
136             }
137         }
138
139         // process -f/F
140
Vector JavaDoc schemas = null;
141         boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
142         if(i < argv.length) {
143             arg = argv[i];
144             if (arg.equals("-f")) {
145                 schemaFullChecking = true;
146                 i++;
147                 arg = argv[i];
148             } else if (arg.equals("-F")) {
149                 schemaFullChecking = false;
150                 i++;
151                 arg = argv[i];
152             }
153             if (arg.equals("-a")) {
154                 if(externalDTDs != null) {
155                     printUsage();
156                     System.exit(1);
157                 }
158
159                 // process -a: schema files
160

161                 schemas= new Vector JavaDoc();
162                 i++;
163                 while (i < argv.length && !(arg = argv[i]).startsWith("-")) {
164                     schemas.addElement(arg);
165                     i++;
166                 }
167
168                 // has to be at least one dTD or schema , and there has to be other parameters
169
if (schemas.size() == 0) {
170                     printUsage();
171                     System.exit(1);
172                 }
173             }
174
175         }
176         // process -i: instance files, if any
177
Vector JavaDoc ifiles = null;
178         if (i < argv.length) {
179             if (!arg.equals("-i")) {
180                 printUsage();
181                 System.exit(1);
182             }
183
184             i++;
185             ifiles = new Vector JavaDoc();
186             while (i < argv.length && !(arg = argv[i]).startsWith("-")) {
187                 ifiles.addElement(arg);
188                 i++;
189             }
190
191             // has to be at least one instance file, and there has to be no more
192
// parameters
193
if (ifiles.size() == 0 || i != argv.length) {
194                 printUsage();
195                 System.exit(1);
196             }
197         }
198
199         // now we have all our arguments. We only
200
// need to parse the DTD's/schemas, put them
201
// in a grammar pool, possibly instantiate an
202
// appropriate configuration, and we're on our way.
203

204         SymbolTable sym = new SymbolTable(BIG_PRIME);
205         XMLGrammarPreparser preparser = new XMLGrammarPreparser(sym);
206         XMLGrammarPoolImpl grammarPool = new XMLGrammarPoolImpl();
207         boolean isDTD = false;
208         if(externalDTDs != null) {
209             preparser.registerPreparser(XMLGrammarDescription.XML_DTD, null);
210             isDTD = true;
211         } else if(schemas != null) {
212             preparser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null);
213             isDTD = false;
214         } else {
215             System.err.println("No schema or DTD specified!");
216             System.exit(1);
217         }
218         preparser.setProperty(GRAMMAR_POOL, grammarPool);
219         preparser.setFeature(NAMESPACES_FEATURE_ID, true);
220         preparser.setFeature(VALIDATION_FEATURE_ID, true);
221         // note we can set schema features just in case...
222
preparser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true);
223         preparser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
224         // parse the grammar...
225

226         try {
227             if(isDTD) {
228                 for (i = 0; i < externalDTDs.size(); i++) {
229                     Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_DTD, stringToXIS((String JavaDoc)externalDTDs.elementAt(i)));
230                     // we don't really care about g; grammarPool will take care of everything.
231
}
232             } else { // must be schemas!
233
for (i = 0; i < schemas.size(); i++) {
234                     Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, stringToXIS((String JavaDoc)schemas.elementAt(i)));
235                     // we don't really care about g; grammarPool will take care of everything.
236
}
237             }
238         } catch (Exception JavaDoc e) {
239             e.printStackTrace();
240             System.exit(1);
241         }
242         // Now we have a grammar pool and a SymbolTable; just
243
// build a configuration and we're on our way!
244
if(parserConfiguration == null) {
245             parserConfiguration = new IntegratedParserConfiguration(sym, grammarPool);
246         } else {
247             // set GrammarPool and SymbolTable...
248
parserConfiguration.setProperty(SYMBOL_TABLE, sym);
249             parserConfiguration.setProperty(GRAMMAR_POOL, grammarPool);
250         }
251         // now must reset features, unfortunately:
252
try{
253             parserConfiguration.setFeature(NAMESPACES_FEATURE_ID, true);
254             parserConfiguration.setFeature(VALIDATION_FEATURE_ID, true);
255             // now we can still do schema features just in case,
256
// so long as it's our configuraiton......
257
parserConfiguration.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true);
258             parserConfiguration.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
259         } catch (Exception JavaDoc e) {
260             e.printStackTrace();
261             System.exit(1);
262         }
263         // then for each instance file, try to validate it
264
if (ifiles != null) {
265             try {
266                 for (i = 0; i < ifiles.size(); i++) {
267                     parserConfiguration.parse(stringToXIS((String JavaDoc)ifiles.elementAt(i)));
268                 }
269             } catch (Exception JavaDoc e) {
270                 e.printStackTrace();
271                 System.exit(1);
272             }
273         }
274
275     } // main(String[])
276

277     //
278
// Private static methods
279
//
280

281     /** Prints the usage. */
282     private static void printUsage() {
283
284         System.err.println("usage: java xni.XMLGrammarBuilder [-p config_file] -d uri ... | [-f|-F] -a uri ... [-i uri ...]");
285         System.err.println();
286
287         System.err.println("options:");
288         System.err.println(" -p config_file: configuration to use for instance validation");
289         System.err.println(" -d grammars to preparse are DTD external subsets");
290         System.err.println(" -f | -F Turn on/off Schema full checking (default "+
291                 (DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off)"));
292         System.err.println(" -a uri ... Provide a list of schema documents");
293         System.err.println(" -i uri ... Provide a list of instance documents to validate");
294         System.err.println();
295         System.err.println("NOTE: both -d and -a cannot be specified!");
296
297     } // printUsage()
298

299     private static XMLInputSource stringToXIS(String JavaDoc uri) {
300         return new XMLInputSource(null, uri, null);
301     }
302 } // class XMLGrammarBuilder
303

304
Popular Tags