KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > tests > org > enhydra > xml > xhtml > dominfo > DTDInfo


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: DTDInfo.java,v 1.2 2005/01/26 08:29:24 jkjome Exp $
22  */

23
24 package tests.org.enhydra.xml.xhtml.dominfo;
25
26 import java.io.IOException JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.io.StringReader JavaDoc;
29 import java.util.HashSet JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Set JavaDoc;
33 import java.util.TreeMap JavaDoc;
34
35 import org.enhydra.apache.xerces.framework.XMLAttrList;
36 import org.enhydra.apache.xerces.framework.XMLContentSpec;
37 import org.enhydra.apache.xerces.framework.XMLDocumentHandler;
38 import org.enhydra.apache.xerces.framework.XMLParser;
39 import org.enhydra.apache.xerces.utils.QName;
40 import org.enhydra.error.FatalExceptionError;
41 import org.enhydra.xml.io.ErrorReporter;
42 import org.xml.sax.EntityResolver JavaDoc;
43 import org.xml.sax.InputSource JavaDoc;
44 import org.xml.sax.SAXException JavaDoc;
45
46 /**
47  * Parse a DTD using the Xerces parser. A subset of the DTD information is stored in this
48  * object.
49  */

50 class DTDInfo {
51     /**
52      * Element information.
53      */

54     public class ElementInfo {
55         /* Element properties */
56         private final String JavaDoc fRawName;
57         private Map JavaDoc fAttrs = new TreeMap JavaDoc();
58            
59
60         /** Constructor */
61         ElementInfo(String JavaDoc rawName) {
62             fRawName = rawName;
63         }
64
65         /** Add an attribute */
66         public void addAttr(AttrInfo attr) {
67             fAttrs.put(attr.getRawName(), attr);
68         }
69         
70         /* Get the element name */
71         public String JavaDoc getRawName() {
72             return fRawName;
73         }
74
75         /* Get the attribute names */
76         public Set JavaDoc getAttrNames() {
77             return fAttrs.keySet();
78         }
79
80         /* Get an attribute */
81         public AttrInfo getAttr(String JavaDoc name) {
82             AttrInfo attr = (AttrInfo)fAttrs.get(name);
83             if (attr == null) {
84                 throw new Error JavaDoc("Can't find attr \"" + attr + "\" of element \"" + fRawName + "\"");
85             }
86             return attr;
87         }
88
89         /* Dump the element */
90         public void dump(PrintWriter JavaDoc out,
91                          int level) {
92             PrintUtils.printIndent(out, level);
93             out.println(fRawName);
94             Iterator JavaDoc attrNames = getAttrNames().iterator();
95             while (attrNames.hasNext()) {
96                 getAttr((String JavaDoc)attrNames.next()).dump(out, level+1);
97             }
98         }
99
100         /** Get a string representation */
101         public String JavaDoc toString() {
102             return fRawName;
103         }
104     }
105
106     /**
107      * Attribute information.
108      */

109     public class AttrInfo {
110         /** Element we are associated with */
111         private ElementInfo fElement;
112         
113         /** Attribute properties */
114         private String JavaDoc fRawName;
115
116         /** Constructor */
117         AttrInfo(ElementInfo element,
118                  String JavaDoc rawName) {
119             fElement = element;
120             fRawName = rawName;
121         }
122
123         /* Get the element we are associated with */
124         public ElementInfo getElement() {
125             return fElement;
126         }
127
128         /* Get the raw attr name */
129         public String JavaDoc getRawName() {
130             return fRawName;
131         }
132
133         /* Dump the attribute */
134         public void dump(PrintWriter JavaDoc out,
135                          int level) {
136             PrintUtils.printIndent(out, level);
137             out.println(fRawName);
138         }
139
140         /** Get a string representation */
141         public String JavaDoc toString() {
142             return fRawName;
143         }
144     }
145
146     /**
147      * The DTD file that was parsed.
148      */

149     private String JavaDoc fDTDPath;
150     
151     /**
152      * Table of elements
153      */

154     private Map JavaDoc fElements = new TreeMap JavaDoc();
155
156     /**
157      * Xerces handlers to parse the DTD. Parse the DTD. Since there isn't a
158      * direct `DTD' parser in Xerces, we fake it by constructing a document to
159      * parse.
160      */

161     private class DTDParser extends XMLParser
162         implements EntityResolver JavaDoc, XMLDocumentHandler, XMLDocumentHandler.DTDHandler {
163
164         /**
165          * Constructor.
166          */

167         public DTDParser() throws IOException JavaDoc, SAXException JavaDoc {
168             ErrorReporter errorReporter = new ErrorReporter();
169
170             // Configure parser.
171
initHandlers(true, this, this);
172             setEntityResolver(this);
173             setErrorHandler(errorReporter);
174             setAllowJavaEncodings(true);
175             setNamespaces(true);
176             setValidation(true);
177         }
178
179         /**
180          * Parse a DTD.
181          */

182         public void parse(String JavaDoc dtdPath) throws IOException JavaDoc, SAXException JavaDoc {
183             String JavaDoc xmlDoc = "<?xml version=\"1.0\"?>"
184                 + "<!DOCTYPE html SYSTEM \"" +dtdPath + "\">"
185                 + "<html></html>";
186             StringReader JavaDoc reader = new StringReader JavaDoc(xmlDoc);
187
188             InputSource JavaDoc input = new InputSource JavaDoc();
189             input.setCharacterStream(reader);
190             input.setSystemId(dtdPath);
191             super.parse(input);
192         }
193
194         /**
195          * Get a string from the string pool.
196          */

197         private String JavaDoc getString(int index) {
198             return fStringPool.toString(index);
199         }
200
201         /**
202          * Resolve an entity.
203          * @see EntityResolver#resolveEntity
204          */

205         public InputSource JavaDoc resolveEntity(String JavaDoc publicId,
206                                          String JavaDoc systemId) throws SAXException JavaDoc, IOException JavaDoc {
207             return null;
208         }
209
210         /**
211          * Handle start of document.
212          * @see XMLDocumentHandler#startDocument
213          */

214         public void startDocument() throws Exception JavaDoc {
215         }
216
217         /**
218          * Handle end document.
219          * @see XMLDocumentHandler#endDocument
220          */

221         public void endDocument() throws Exception JavaDoc {
222         }
223
224         /**
225          * @see XMLDocumentHandler#xmlDecl
226          */

227         public void xmlDecl(int version, int encoding, int standalone) throws Exception JavaDoc {
228         }
229
230         /**
231          * @see XMLDocumentHandler#textDecl
232          * @see XMLDocumentHandler.DTDHandler#textDecl
233          */

234         public void textDecl(int version, int encoding) throws Exception JavaDoc {
235         }
236
237         /**
238          * Handle start of a namespace declaration scope.
239          *
240          * @see XMLDocumentHandler#startNamespaceDeclScope
241          */

242         public void startNamespaceDeclScope(int prefix,
243                                             int uri) throws Exception JavaDoc {
244         }
245
246         /**
247          * Handle end of a namespace declaration scope.
248          *
249          * @see XMLDocumentHandler#startNamespaceDeclScope
250          */

251         public void endNamespaceDeclScope(int prefix) throws Exception JavaDoc {
252         }
253
254         /**
255          * Handle start of element.
256          * @see XMLDocumentHandler#startElement
257          */

258         public void startElement(QName element,
259                                  XMLAttrList attrList,
260                                  int attrListHandle) throws Exception JavaDoc {
261         }
262
263         /**
264          * Handle end element.
265          * @see XMLDocumentHandler#endElement
266          */

267         public void endElement(QName element) throws Exception JavaDoc {
268         }
269
270         /**
271          * Handle the start of an entity reference. If it's is one of the
272          * standard character entity references, we don't push the create
273          * the node, we just let the child be appended directly in its place.
274          *
275          * @see XMLDocumentHandler#startEntityReference
276          */

277         public void startEntityReference(int entityName,
278                                          int entityType,
279                                          int entityContext) throws Exception JavaDoc {
280         }
281
282         /**
283          * Handle the end of an entity reference.
284          * @see XMLDocumentHandler#endEntityReference
285          */

286         public void endEntityReference(int entityName,
287                                        int entityType,
288                                        int entityContext) throws Exception JavaDoc {
289         }
290
291         /**
292          * Not used.
293          * @see XMLDocumentHandler#characters
294          */

295         public void characters(int data) throws Exception JavaDoc {
296             throw new Error JavaDoc("fatal error: method that should not be invoked called");
297         }
298
299         /**
300          * Not used.
301          * @see XMLDocumentHandler#ignorableWhitespace
302          */

303         public void ignorableWhitespace(int data) throws Exception JavaDoc {
304             throw new Error JavaDoc("fatal error: method that should not be invoked called");
305         }
306
307         /**
308          * Handle start of CDATA section.
309          * @see XMLDocumentHandler#startCDATA
310          */

311         public void startCDATA() {
312         }
313
314         /**
315          * Handle for end of CDATA section.
316          * @see XMLDocumentHandler#endCDATA
317          */

318         public void endCDATA() {
319         }
320
321         /**
322          * Handle processing instruction.
323          * @see XMLDocumentHandler#processingInstruction
324          * @see XMLDocumentHandler.DTDHandler#processingInstruction
325          */

326         public void processingInstruction(int target,
327                                           int data) throws Exception JavaDoc {
328         }
329
330         /**
331          * Handle a comment.
332          * @see XMLDocumentHandler#comment
333          */

334         public void comment(int comment) throws Exception JavaDoc {
335         }
336
337         /**
338          * Handle characters.
339          * @see XMLDocumentHandler#characters
340          */

341         public void characters(char ch[],
342                                int start,
343                                int length) throws Exception JavaDoc {
344         }
345
346         /**
347          * Handle ignorable whitespace.
348          * @see XMLDocumentHandler#ignorableWhitespace
349          */

350         public void ignorableWhitespace(char ch[],
351                                         int start,
352                                         int length) throws Exception JavaDoc {
353         }
354
355         /**
356          * @see XMLDocumentHandler.DTDHandler#startDTD
357          */

358         public void startDTD(QName rootElement,
359                              int publicId,
360                              int systemId) {
361         }
362
363         /**
364          * @see XMLDocumentHandler.DTDHandler#internalSubset
365          */

366         public void internalSubset(int internalSubset) {
367         }
368
369         /**
370          * @see XMLDocumentHandler.DTDHandler#endDTD
371          */

372         public void endDTD() {
373         }
374
375         /**
376          * <!ELEMENT Name contentspec>
377          *
378          * @see XMLDocumentHandler.DTDHandler#elementDecl
379          */

380         public void elementDecl(QName elementDecl,
381                                 int contentSpecType,
382                                 int contentSpecIndex,
383                                 XMLContentSpec.Provider contentSpecProvider) throws Exception JavaDoc {
384             if (fElements.containsKey(getString(elementDecl.rawname))) {
385                 throw new Error JavaDoc("Duplicate element definintion: " + elementDecl.rawname);
386             }
387             ElementInfo element = new ElementInfo(getString(elementDecl.rawname));
388             fElements.put(element.getRawName(), element);
389         }
390
391         /**
392          * <!ATTLIST Name AttDef>
393          *
394          * @see XMLDocumentHandler.DTDHandler#attlistDecl
395          */

396         public void attlistDecl(QName elementDecl,
397                                 QName attributeDecl,
398                                 int attType,
399                                 boolean attList,
400                                 String JavaDoc enumString,
401                                 int attDefaultType,
402                                 int attDefaultValue) throws Exception JavaDoc {
403             ElementInfo element = (ElementInfo)fElements.get(getString(elementDecl.rawname));
404             if (!fElements.containsKey(getString(elementDecl.rawname))) {
405                 throw new Error JavaDoc("Element definintion not found when adding attribute: " + elementDecl.rawname);
406             }
407             element.addAttr(new AttrInfo(element, getString(attributeDecl.rawname)));
408         }
409
410         /**
411          * <!ENTITY % Name EntityValue>
412          *
413          * @see XMLDocumentHandler.DTDHandler#internalPEDecl
414          */

415         public void internalPEDecl(int entityName,
416                                    int entityValue) {
417         }
418
419         /**
420          * <!ENTITY % Name ExternalID>
421          *
422          * @see XMLDocumentHandler.DTDHandler#externalPEDecl
423          */

424         public void externalPEDecl(int entityName,
425                                    int publicId,
426                                    int systemId) {
427         }
428
429         /**
430          * <!ENTITY Name EntityValue>
431          *
432          * @see XMLDocumentHandler.DTDHandler#internalEntityDecl
433          */

434         public void internalEntityDecl(int entityName,
435                                        int entityValue) {
436         }
437
438         /**
439          * <!ENTITY Name ExternalID>
440          *
441          * @see XMLDocumentHandler.DTDHandler#externalEntityDecl
442          */

443         public void externalEntityDecl(int entityName,
444                                        int publicId,
445                                        int systemId) {
446         }
447
448         /**
449          * <!ENTITY Name ExternalID NDataDecl>
450          *
451          * @see XMLDocumentHandler.DTDHandler#unparsedEntityDecl
452          */

453         public void unparsedEntityDecl(int entityName,
454                                        int publicId,
455                                        int systemId,
456                                        int notationName) {
457         }
458
459         /**
460          * <!NOTATION Name ExternalId>
461          *
462          * @see XMLDocumentHandler.DTDHandler#notationDecl
463          */

464         public void notationDecl(int notationName,
465                                  int publicId,
466                                  int systemId) {
467         }
468     }
469
470     /**
471      * Constructor.
472      */

473     public DTDInfo(String JavaDoc dtdPath) {
474         try {
475             fDTDPath = dtdPath;
476             DTDParser parser = new DTDParser();
477             parser.parse(dtdPath);
478         } catch (IOException JavaDoc except) {
479             throw new FatalExceptionError(except);
480         } catch (SAXException JavaDoc except) {
481             throw new FatalExceptionError(except);
482         }
483     }
484
485     /**
486      * Get the DTD path.
487      */

488     public String JavaDoc getDTDPath() {
489         return fDTDPath;
490     }
491
492     /* Get the element names */
493     public Set JavaDoc getElementNames() {
494         return fElements.keySet();
495     }
496
497     /* Get an element */
498     public ElementInfo getElement(String JavaDoc name) {
499         ElementInfo element = (ElementInfo)fElements.get(name);
500         if (element == null) {
501             throw new Error JavaDoc("Can't find element \"" + name + "\"");
502         }
503         return element;
504     }
505
506     /* Get the set of ElementInfo objects */
507     public Set JavaDoc getElementInfoSet() {
508         HashSet JavaDoc set = new HashSet JavaDoc();
509
510         Iterator JavaDoc elementNames = getElementNames().iterator();
511         while (elementNames.hasNext()) {
512             set.add(getElement((String JavaDoc)elementNames.next()));
513         }
514         return set;
515     }
516
517     /**
518      * Dump the elements in the tree.
519      */

520     public void dump(PrintWriter JavaDoc out) {
521         Iterator JavaDoc elementNames = getElementNames().iterator();
522         while (elementNames.hasNext()) {
523             getElement((String JavaDoc)elementNames.next()).dump(out, 0);
524         }
525     }
526
527     /**
528      * Main used for testing.
529      */

530     public static void main(String JavaDoc[] args) throws IOException JavaDoc, SAXException JavaDoc {
531         if (args.length != 1) {
532             System.err.println("Wrong # args: DTDInfo dtdfile");
533             System.exit(1);
534         }
535         DTDInfo dtdInfo = new DTDInfo(args[0]);
536         dtdInfo.dump(new PrintWriter JavaDoc(System.out, true));
537     }
538 }
539
Popular Tags