KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > contrib > sam > xmlform > dtd > ValidatorImpl


1 /**
2  * This class was generated from a set of XML constraints
3  * by the Enhydra Zeus XML Data Binding Framework. All
4  * source code in this file is constructed specifically
5  * to work with other Zeus-generated classes. If you
6  * modify this file by hand, you run the risk of breaking
7  * this interoperation, as well as introducing errors in
8  * source code compilation.
9  *
10  * * * * * MODIFY THIS FILE AT YOUR OWN RISK * * * * *
11  *
12  * To find out more about the Enhydra Zeus framework, you
13  * can point your browser at <http://zeus.enhydra.org>
14  * where you can download releases, join and discuss Zeus
15  * on user and developer mailing lists, and access source
16  * code. Please report any bugs through that website.
17  */

18 package org.enhydra.barracuda.contrib.sam.xmlform.dtd;
19
20 // Global Implementation Import Statements
21
import java.io.File JavaDoc;
22 import java.io.FileReader JavaDoc;
23 import java.io.FileWriter JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.InputStreamReader JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.io.OutputStreamWriter JavaDoc;
29 import java.io.Reader JavaDoc;
30 import java.io.Writer JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Map JavaDoc;
34 import org.xml.sax.EntityResolver JavaDoc;
35 import org.xml.sax.ErrorHandler JavaDoc;
36 import org.xml.sax.InputSource JavaDoc;
37 import org.xml.sax.Locator JavaDoc;
38 import org.xml.sax.SAXException JavaDoc;
39 import org.xml.sax.SAXParseException JavaDoc;
40 import org.xml.sax.XMLReader JavaDoc;
41 import org.xml.sax.ext.LexicalHandler JavaDoc;
42 import org.xml.sax.helpers.DefaultHandler JavaDoc;
43 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
44
45 // Local Implementation Import Statements
46
import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.LinkedList JavaDoc;
49
50 public class ValidatorImpl extends DefaultHandler JavaDoc implements Cloneable JavaDoc, Unmarshallable, LexicalHandler JavaDoc, Validator {
51
52     private List JavaDoc paraList;
53     private List JavaDoc validatorList;
54     private String JavaDoc classname;
55     private boolean zeus_ClassnameSet;
56
57     /** Any DOCTYPE reference/statements. */
58     private String JavaDoc docTypeString;
59
60     /** The encoding for the output document */
61     private String JavaDoc outputEncoding;
62
63     /** The current node in unmarshalling */
64     private Unmarshallable zeus_currentUNode;
65
66     /** The parent node in unmarshalling */
67     private Unmarshallable zeus_parentUNode;
68
69     /** Whether this node has been handled */
70     private boolean zeus_thisNodeHandled = false;
71
72     /** Whether a DTD exists for an unmarshal call */
73     private boolean hasDTD;
74
75     /** Whether validation is occurring */
76     private boolean validate;
77
78     /** The namespace mappings on this element */
79     private Map JavaDoc namespaceMappings;
80
81     /** The EntityResolver for SAX parsing to use */
82     private static EntityResolver JavaDoc entityResolver;
83
84     /** The ErrorHandler for SAX parsing to use */
85     private static ErrorHandler JavaDoc errorHandler;
86
87     private static ValidatorImpl prototype = null;
88
89     public static void setPrototype(ValidatorImpl prototype) {
90         ValidatorImpl.prototype = prototype;
91     }
92     public static ValidatorImpl newInstance() {
93         try {
94             return (prototype!=null)?(ValidatorImpl)prototype.clone(): new ValidatorImpl();
95         } catch (CloneNotSupportedException JavaDoc e) {
96             return null; // never
97
}
98     }
99     public ValidatorImpl() {
100         paraList = new LinkedList JavaDoc();
101         validatorList = new LinkedList JavaDoc();
102         zeus_ClassnameSet = false;
103         docTypeString = "";
104         hasDTD = false;
105         validate = false;
106         namespaceMappings = new HashMap JavaDoc();
107     }
108
109     public List JavaDoc getParaList() {
110         return paraList;
111     }
112
113     public void setParaList(List JavaDoc paraList) {
114         this.paraList = paraList;
115     }
116
117     public void addPara(Para para) {
118         paraList.add(para);
119     }
120
121     public void removePara(Para para) {
122         paraList.remove(para);
123     }
124
125     public List JavaDoc getValidatorList() {
126         return validatorList;
127     }
128
129     public void setValidatorList(List JavaDoc validatorList) {
130         this.validatorList = validatorList;
131     }
132
133     public void addValidator(Validator validator) {
134         validatorList.add(validator);
135     }
136
137     public void removeValidator(Validator validator) {
138         validatorList.remove(validator);
139     }
140
141     public String JavaDoc getClassname() {
142         return classname;
143     }
144
145     public void setClassname(String JavaDoc classname) {
146         this.classname = classname;
147         zeus_ClassnameSet = true;
148     }
149
150     public void setDocType(String JavaDoc name, String JavaDoc publicID, String JavaDoc systemID) {
151         try {
152             startDTD(name, publicID, systemID);
153         } catch (SAXException JavaDoc neverHappens) { }
154     }
155
156     public void setOutputEncoding(String JavaDoc outputEncoding) {
157         this.outputEncoding = outputEncoding;
158     }
159
160     public void marshal(File JavaDoc file) throws IOException JavaDoc {
161         // Delegate to the marshal(Writer) method
162
marshal(new FileWriter JavaDoc(file));
163     }
164
165     public void marshal(OutputStream JavaDoc outputStream) throws IOException JavaDoc {
166         // Delegate to the marshal(Writer) method
167
marshal(new OutputStreamWriter JavaDoc(outputStream));
168     }
169
170     public void marshal(Writer JavaDoc writer) throws IOException JavaDoc {
171         // Write out the XML declaration
172
writer.write("<?xml version=\"1.0\" ");
173         if (outputEncoding != null) {
174             writer.write("encoding=\"");
175             writer.write(outputEncoding);
176             writer.write("\"?>\n\n");
177
178         } else {
179             writer.write("encoding=\"UTF-8\"?>\n\n");
180
181         }
182         // Handle DOCTYPE declaration
183
writer.write(docTypeString);
184         writer.write("\n");
185         // Now start the recursive writing
186
writeXMLRepresentation(writer, "");
187
188         // Close up
189
writer.flush();
190         writer.close();
191     }
192
193     protected void writeXMLRepresentation(Writer JavaDoc writer,
194                                           String JavaDoc indent)
195         throws IOException JavaDoc {
196
197         writer.write(indent);
198         writer.write("<validator");
199
200         // Handle namespace mappings (if needed)
201
for (Iterator JavaDoc i = namespaceMappings.keySet().iterator(); i.hasNext(); ) {
202             String JavaDoc prefix = (String JavaDoc)i.next();
203             String JavaDoc uri = (String JavaDoc)namespaceMappings.get(prefix);
204             writer.write(" xmlns");
205             if (!prefix.trim().equals("")) {
206                 writer.write(":");
207                 writer.write(prefix);
208             }
209             writer.write("=\"");
210             writer.write(uri);
211             writer.write("\"\n ");
212         }
213
214         // Handle attributes (if needed)
215
if (zeus_ClassnameSet) {
216             writer.write(" classname=\"");
217             writer.write(escapeAttributeValue(classname));
218             writer.write("\"");
219         }
220         writer.write(">");
221         writer.write("\n");
222
223         // Handle child elements
224
for (Iterator JavaDoc i=paraList.iterator(); i.hasNext(); ) {
225             ParaImpl para = (ParaImpl)i.next();
226             para.writeXMLRepresentation(writer,
227                 new StringBuffer JavaDoc(indent).append(" ").toString());
228         }
229         for (Iterator JavaDoc i=validatorList.iterator(); i.hasNext(); ) {
230             ValidatorImpl validator = (ValidatorImpl)i.next();
231             validator.writeXMLRepresentation(writer,
232                 new StringBuffer JavaDoc(indent).append(" ").toString());
233         }
234         writer.write(indent);
235         writer.write("</validator>\n");
236     }
237
238     private String JavaDoc escapeAttributeValue(String JavaDoc attributeValue) {
239         String JavaDoc returnValue = attributeValue;
240         for (int i = 0; i < returnValue.length(); i++) {
241             char ch = returnValue.charAt(i);
242             if (ch == '"') {
243                 returnValue = new StringBuffer JavaDoc()
244                     .append(returnValue.substring(0, i))
245                     .append("&quot;")
246                     .append(returnValue.substring(i+1))
247                     .toString();
248             }
249         }
250         return returnValue;
251     }
252
253     private String JavaDoc escapeTextValue(String JavaDoc textValue) {
254         String JavaDoc returnValue = textValue;
255         for (int i = 0; i < returnValue.length(); i++) {
256             char ch = returnValue.charAt(i);
257             if (ch == '<') {
258                 returnValue = new StringBuffer JavaDoc()
259                     .append(returnValue.substring(0, i))
260                     .append("&lt;")
261                     .append(returnValue.substring(i+1))
262                     .toString();
263             } else if (ch == '>') {
264                 returnValue = new StringBuffer JavaDoc()
265                     .append(returnValue.substring(0, i))
266                     .append("&gt;")
267                     .append(returnValue.substring(i+1))
268                     .toString();
269             }
270         }
271         return returnValue;
272     }
273
274     /**
275      * <p>
276      * This sets a SAX <code>EntityResolver</code> for this unmarshalling process.
277      * </p>
278      *
279      * @param resolver the entity resolver to use.
280      */

281     public static void setEntityResolver(EntityResolver JavaDoc resolver) {
282         entityResolver = resolver;
283     }
284
285     /**
286      * <p>
287      * This sets a SAX <code>ErrorHandler</code> for this unmarshalling process.
288      * </p>
289      *
290      * @param handler the entity resolver to use.
291      */

292     public static void setErrorHandler(ErrorHandler JavaDoc handler) {
293         errorHandler = handler;
294     }
295
296     public static Validator unmarshal(File JavaDoc file) throws IOException JavaDoc {
297         // Delegate to the unmarshal(Reader) method
298
return unmarshal(new FileReader JavaDoc(file));
299     }
300
301     public static Validator unmarshal(File JavaDoc file, boolean validate) throws IOException JavaDoc {
302         // Delegate to the unmarshal(Reader) method
303
return unmarshal(new FileReader JavaDoc(file), validate);
304     }
305
306     public static Validator unmarshal(InputStream JavaDoc inputStream) throws IOException JavaDoc {
307         // Delegate to the unmarshal(Reader) method
308
return unmarshal(new InputStreamReader JavaDoc(inputStream));
309     }
310
311     public static Validator unmarshal(InputStream JavaDoc inputStream, boolean validate) throws IOException JavaDoc {
312         // Delegate to the unmarshal(Reader) method
313
return unmarshal(new InputStreamReader JavaDoc(inputStream), validate);
314     }
315
316     public static Validator unmarshal(Reader JavaDoc reader) throws IOException JavaDoc {
317         // Delegate with default validation value
318
return unmarshal(reader, false);
319     }
320
321     public static Validator unmarshal(Reader JavaDoc reader, boolean validate) throws IOException JavaDoc {
322         ValidatorImpl validator = ValidatorImpl.newInstance();
323         validator.setValidating(validate);
324         validator.setCurrentUNode(validator);
325         validator.setParentUNode(null);
326         // Load the XML parser
327
XMLReader JavaDoc parser = null;
328         String JavaDoc parserClass = System.getProperty("org.xml.sax.driver",
329             "org.apache.xerces.parsers.SAXParser");
330         try {
331             parser = XMLReaderFactory.createXMLReader(parserClass);
332
333             // Set entity resolver, if needed
334
if (entityResolver != null) {
335                 parser.setEntityResolver(entityResolver);
336             }
337
338             // Set error handler
339
parser.setErrorHandler(validator);
340
341             // Register lexical handler
342
parser.setProperty("http://xml.org/sax/properties/lexical-handler", validator);
343
344             // Register content handler
345
parser.setContentHandler(validator);
346         } catch (SAXException JavaDoc e) {
347             throw new IOException JavaDoc("Could not load XML parser: " +
348                 e.getMessage());
349         }
350
351         InputSource JavaDoc inputSource = new InputSource JavaDoc(reader);
352         try {
353             parser.setFeature("http://xml.org/sax/features/validation", new Boolean JavaDoc(validate).booleanValue());
354             parser.setFeature("http://xml.org/sax/features/namespaces", true);
355             parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
356             parser.parse(inputSource);
357         } catch (SAXException JavaDoc e) {
358             throw new IOException JavaDoc("Error parsing XML document: " +
359                 e.getMessage());
360         }
361
362         // Return the resultant object
363
return validator;
364     }
365
366     public Unmarshallable getParentUNode() {
367         return zeus_parentUNode;
368     }
369
370     public void setParentUNode(Unmarshallable parentUNode) {
371         this.zeus_parentUNode = parentUNode;
372     }
373
374     public Unmarshallable getCurrentUNode() {
375         return zeus_currentUNode;
376     }
377
378     public void setCurrentUNode(Unmarshallable currentUNode) {
379         this.zeus_currentUNode = currentUNode;
380     }
381
382     public void setValidating(boolean validate) {
383         this.validate = validate;
384     }
385
386     public void startDocument() throws SAXException JavaDoc {
387         // no-op
388
}
389
390     public void setDocumentLocator(Locator JavaDoc locator) {
391         // no-op
392
}
393
394     public void startPrefixMapping(String JavaDoc prefix, String JavaDoc uri)
395         throws SAXException JavaDoc {
396         namespaceMappings.put(prefix, uri);
397     }
398
399     public void startElement(String JavaDoc namespaceURI, String JavaDoc localName,
400                              String JavaDoc qName, org.xml.sax.Attributes JavaDoc atts)
401         throws SAXException JavaDoc {
402
403         // Feed this to the correct ContentHandler
404
Unmarshallable current = getCurrentUNode();
405         if (current != this) {
406             current.startElement(namespaceURI, localName, qName, atts);
407             return;
408         }
409
410         // See if we handle, or we delegate
411
if ((localName.equals("validator")) && (!zeus_thisNodeHandled)) {
412             // Handle ourselves
413
for (int i=0, len=atts.getLength(); i<len; i++) {
414                 String JavaDoc attName= atts.getLocalName(i);
415                 String JavaDoc attValue = atts.getValue(i);
416                 if (attName.equals("classname")) {
417                     setClassname(attValue);
418                 }
419             }
420             zeus_thisNodeHandled = true;
421             return;
422         } else {
423             // Delegate handling
424
if (localName.equals("para")) {
425                 ParaImpl para = ParaImpl.newInstance();
426                 current = getCurrentUNode();
427                 para.setParentUNode(current);
428                 para.setCurrentUNode(para);
429                 this.setCurrentUNode(para);
430                 para.startElement(namespaceURI, localName, qName, atts);
431                 // Add this value in
432
paraList.add(para);
433                 return;
434             }
435             if (localName.equals("validator")) {
436                 ValidatorImpl validator = ValidatorImpl.newInstance();
437                 current = getCurrentUNode();
438                 validator.setParentUNode(current);
439                 validator.setCurrentUNode(validator);
440                 this.setCurrentUNode(validator);
441                 validator.startElement(namespaceURI, localName, qName, atts);
442                 // Add this value in
443
validatorList.add(validator);
444                 return;
445             }
446         }
447     }
448
449     public void endElement(String JavaDoc namespaceURI, String JavaDoc localName,
450                            String JavaDoc qName)
451         throws SAXException JavaDoc {
452
453         Unmarshallable current = getCurrentUNode();
454         if (current != this) {
455             current.endElement(namespaceURI, localName, qName);
456             return;
457         }
458
459         Unmarshallable parent = getCurrentUNode().getParentUNode();
460         if (parent != null) {
461             parent.setCurrentUNode(parent);
462         }
463     }
464
465     public void characters(char[] ch, int start, int len)
466         throws SAXException JavaDoc {
467
468         // Feed this to the correct ContentHandler
469
Unmarshallable current = getCurrentUNode();
470         if (current != this) {
471             current.characters(ch, start, len);
472             return;
473         }
474
475         String JavaDoc text = new String JavaDoc(ch, start, len);
476         text = text.trim();
477     }
478
479     public void comment(char ch[], int start, int len) throws SAXException JavaDoc {
480         // Currently no-op
481
}
482
483     public void warning(SAXParseException JavaDoc e) throws SAXException JavaDoc {
484         if (errorHandler != null) {
485             errorHandler.warning(e);
486         }
487     }
488
489     public void error(SAXParseException JavaDoc e) throws SAXException JavaDoc {
490         if ((validate) && (!hasDTD)) {
491             throw new SAXException JavaDoc("Validation is turned on, but no DTD has been specified in the input XML document. Please supply a DTD through a DOCTYPE reference.");
492         }
493         if (errorHandler != null) {
494             errorHandler.error(e);
495         }
496     }
497
498     public void fatalError(SAXParseException JavaDoc e) throws SAXException JavaDoc {
499         if ((validate) && (!hasDTD)) {
500             throw new SAXException JavaDoc("Validation is turned on, but no DTD has been specified in the input XML document. Please supply a DTD through a DOCTYPE reference.");
501         }
502         if (errorHandler != null) {
503             errorHandler.fatalError(e);
504         }
505     }
506
507     public void startDTD(String JavaDoc name, String JavaDoc publicID, String JavaDoc systemID)
508         throws SAXException JavaDoc {
509
510         if ((name == null) || (name.equals(""))) {
511             docTypeString = "";
512             return;
513         }
514
515         hasDTD = true;
516         StringBuffer JavaDoc docTypeSB = new StringBuffer JavaDoc();
517         boolean hasPublic = false;
518
519         docTypeSB.append("<!DOCTYPE ")
520                  .append(name);
521
522         if ((publicID != null) && (!publicID.equals(""))) {
523             docTypeSB.append(" PUBLIC \"")
524                      .append(publicID)
525                      .append("\"");
526             hasPublic = true;
527         }
528
529         if ((systemID != null) && (!systemID.equals(""))) {
530             if (!hasPublic) {
531                 docTypeSB.append(" SYSTEM");
532             }
533             docTypeSB.append(" \"")
534                      .append(systemID)
535                      .append("\"");
536
537         }
538
539         docTypeSB.append(">");
540
541         docTypeString = docTypeSB.toString();
542     }
543
544     public void endDTD() throws SAXException JavaDoc {
545         // Currently no-op
546
}
547
548     public void startEntity(String JavaDoc name) throws SAXException JavaDoc {
549         // Currently no-op
550
}
551
552     public void endEntity(String JavaDoc name) throws SAXException JavaDoc {
553         // Currently no-op
554
}
555
556     public void startCDATA() throws SAXException JavaDoc {
557         // Currently no-op
558
}
559
560     public void endCDATA() throws SAXException JavaDoc {
561         // Currently no-op
562
}
563
564 }
565
Popular Tags