KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > convert > xml > DistributableImpl


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.convert.xml;
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 public class DistributableImpl extends DefaultHandler JavaDoc implements Cloneable JavaDoc, Unmarshallable, LexicalHandler JavaDoc, Distributable {
46
47     private String JavaDoc id;
48     private boolean zeus_IdSet;
49
50     /** Any DOCTYPE reference/statements. */
51     private String JavaDoc docTypeString;
52
53     /** The encoding for the output document */
54     private String JavaDoc outputEncoding;
55
56     /** The current node in unmarshalling */
57     private Unmarshallable zeus_currentUNode;
58
59     /** The parent node in unmarshalling */
60     private Unmarshallable zeus_parentUNode;
61
62     /** Whether this node has been handled */
63     private boolean zeus_thisNodeHandled = false;
64
65     /** Whether a DTD exists for an unmarshal call */
66     private boolean hasDTD;
67
68     /** Whether validation is occurring */
69     private boolean validate;
70
71     /** The namespace mappings on this element */
72     private Map JavaDoc namespaceMappings;
73
74     /** The EntityResolver for SAX parsing to use */
75     private static EntityResolver JavaDoc entityResolver;
76
77     /** The ErrorHandler for SAX parsing to use */
78     private static ErrorHandler JavaDoc errorHandler;
79
80     private static DistributableImpl prototype = null;
81
82     public static void setPrototype(DistributableImpl prototype) {
83         DistributableImpl.prototype = prototype;
84     }
85     public static DistributableImpl newInstance() {
86         try {
87             return (prototype!=null)?(DistributableImpl)prototype.clone(): new DistributableImpl();
88         } catch (CloneNotSupportedException JavaDoc e) {
89             return null; // never
90
}
91     }
92     public DistributableImpl() {
93         zeus_IdSet = false;
94         docTypeString = "";
95         hasDTD = false;
96         validate = false;
97         namespaceMappings = new HashMap JavaDoc();
98     }
99
100     public String JavaDoc getId() {
101         return id;
102     }
103
104     public void setId(String JavaDoc id) {
105         this.id = id;
106         zeus_IdSet = true;
107     }
108
109     public void setDocType(String JavaDoc name, String JavaDoc publicID, String JavaDoc systemID) {
110         try {
111             startDTD(name, publicID, systemID);
112         } catch (SAXException JavaDoc neverHappens) { }
113     }
114
115     public void setOutputEncoding(String JavaDoc outputEncoding) {
116         this.outputEncoding = outputEncoding;
117     }
118
119     public void marshal(File JavaDoc file) throws IOException JavaDoc {
120         // Delegate to the marshal(Writer) method
121
marshal(new FileWriter JavaDoc(file));
122     }
123
124     public void marshal(OutputStream JavaDoc outputStream) throws IOException JavaDoc {
125         // Delegate to the marshal(Writer) method
126
marshal(new OutputStreamWriter JavaDoc(outputStream));
127     }
128
129     public void marshal(Writer JavaDoc writer) throws IOException JavaDoc {
130         // Write out the XML declaration
131
writer.write("<?xml version=\"1.0\" ");
132         if (outputEncoding != null) {
133             writer.write("encoding=\"");
134             writer.write(outputEncoding);
135             writer.write("\"?>\n\n");
136
137         } else {
138             writer.write("encoding=\"UTF-8\"?>\n\n");
139
140         }
141         // Handle DOCTYPE declaration
142
writer.write(docTypeString);
143         writer.write("\n");
144         // Now start the recursive writing
145
writeXMLRepresentation(writer, "");
146
147         // Close up
148
writer.flush();
149         writer.close();
150     }
151
152     protected void writeXMLRepresentation(Writer JavaDoc writer,
153                                           String JavaDoc indent)
154         throws IOException JavaDoc {
155
156         writer.write(indent);
157         writer.write("<distributable");
158
159         // Handle namespace mappings (if needed)
160
for (Iterator JavaDoc i = namespaceMappings.keySet().iterator(); i.hasNext(); ) {
161             String JavaDoc prefix = (String JavaDoc)i.next();
162             String JavaDoc uri = (String JavaDoc)namespaceMappings.get(prefix);
163             writer.write(" xmlns");
164             if (!prefix.trim().equals("")) {
165                 writer.write(":");
166                 writer.write(prefix);
167             }
168             writer.write("=\"");
169             writer.write(uri);
170             writer.write("\"\n ");
171         }
172
173         // Handle attributes (if needed)
174
if (zeus_IdSet) {
175             writer.write(" id=\"");
176             writer.write(escapeAttributeValue(id));
177             writer.write("\"");
178         }
179         writer.write("/>\n");
180     }
181
182     private String JavaDoc escapeAttributeValue(String JavaDoc attributeValue) {
183         String JavaDoc returnValue = attributeValue;
184         for (int i = 0; i < returnValue.length(); i++) {
185             char ch = returnValue.charAt(i);
186             if (ch == '"') {
187                 returnValue = new StringBuffer JavaDoc()
188                     .append(returnValue.substring(0, i))
189                     .append("&quot;")
190                     .append(returnValue.substring(i+1))
191                     .toString();
192             }
193         }
194         return returnValue;
195     }
196
197     private String JavaDoc escapeTextValue(String JavaDoc textValue) {
198         String JavaDoc returnValue = textValue;
199         for (int i = 0; i < returnValue.length(); i++) {
200             char ch = returnValue.charAt(i);
201             if (ch == '<') {
202                 returnValue = new StringBuffer JavaDoc()
203                     .append(returnValue.substring(0, i))
204                     .append("&lt;")
205                     .append(returnValue.substring(i+1))
206                     .toString();
207             } else if (ch == '>') {
208                 returnValue = new StringBuffer JavaDoc()
209                     .append(returnValue.substring(0, i))
210                     .append("&gt;")
211                     .append(returnValue.substring(i+1))
212                     .toString();
213             }
214         }
215         return returnValue;
216     }
217
218     /**
219      * <p>
220      * This sets a SAX <code>EntityResolver</code> for this unmarshalling process.
221      * </p>
222      *
223      * @param resolver the entity resolver to use.
224      */

225     public static void setEntityResolver(EntityResolver JavaDoc resolver) {
226         entityResolver = resolver;
227     }
228
229     /**
230      * <p>
231      * This sets a SAX <code>ErrorHandler</code> for this unmarshalling process.
232      * </p>
233      *
234      * @param handler the entity resolver to use.
235      */

236     public static void setErrorHandler(ErrorHandler JavaDoc handler) {
237         errorHandler = handler;
238     }
239
240     public static Distributable unmarshal(File JavaDoc file) throws IOException JavaDoc {
241         // Delegate to the unmarshal(Reader) method
242
return unmarshal(new FileReader JavaDoc(file));
243     }
244
245     public static Distributable unmarshal(File JavaDoc file, boolean validate) throws IOException JavaDoc {
246         // Delegate to the unmarshal(Reader) method
247
return unmarshal(new FileReader JavaDoc(file), validate);
248     }
249
250     public static Distributable unmarshal(InputStream JavaDoc inputStream) throws IOException JavaDoc {
251         // Delegate to the unmarshal(Reader) method
252
return unmarshal(new InputStreamReader JavaDoc(inputStream));
253     }
254
255     public static Distributable unmarshal(InputStream JavaDoc inputStream, boolean validate) throws IOException JavaDoc {
256         // Delegate to the unmarshal(Reader) method
257
return unmarshal(new InputStreamReader JavaDoc(inputStream), validate);
258     }
259
260     public static Distributable unmarshal(Reader JavaDoc reader) throws IOException JavaDoc {
261         // Delegate with default validation value
262
return unmarshal(reader, false);
263     }
264
265     public static Distributable unmarshal(Reader JavaDoc reader, boolean validate) throws IOException JavaDoc {
266         DistributableImpl distributable = DistributableImpl.newInstance();
267         distributable.setValidating(validate);
268         distributable.setCurrentUNode(distributable);
269         distributable.setParentUNode(null);
270         // Load the XML parser
271
XMLReader JavaDoc parser = null;
272         String JavaDoc parserClass = System.getProperty("org.xml.sax.driver",
273             "org.apache.xerces.parsers.SAXParser");
274         try {
275             parser = XMLReaderFactory.createXMLReader(parserClass);
276
277             // Set entity resolver, if needed
278
if (entityResolver != null) {
279                 parser.setEntityResolver(entityResolver);
280             }
281
282             // Set error handler
283
parser.setErrorHandler(distributable);
284
285             // Register lexical handler
286
parser.setProperty("http://xml.org/sax/properties/lexical-handler", distributable);
287
288             // Register content handler
289
parser.setContentHandler(distributable);
290         } catch (SAXException JavaDoc e) {
291             throw new IOException JavaDoc("Could not load XML parser: " +
292                 e.getMessage());
293         }
294
295         InputSource JavaDoc inputSource = new InputSource JavaDoc(reader);
296         try {
297             parser.setFeature("http://xml.org/sax/features/validation", new Boolean JavaDoc(validate).booleanValue());
298             parser.setFeature("http://xml.org/sax/features/namespaces", true);
299             parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
300             parser.parse(inputSource);
301         } catch (SAXException JavaDoc e) {
302             throw new IOException JavaDoc("Error parsing XML document: " +
303                 e.getMessage());
304         }
305
306         // Return the resultant object
307
return distributable;
308     }
309
310     public Unmarshallable getParentUNode() {
311         return zeus_parentUNode;
312     }
313
314     public void setParentUNode(Unmarshallable parentUNode) {
315         this.zeus_parentUNode = parentUNode;
316     }
317
318     public Unmarshallable getCurrentUNode() {
319         return zeus_currentUNode;
320     }
321
322     public void setCurrentUNode(Unmarshallable currentUNode) {
323         this.zeus_currentUNode = currentUNode;
324     }
325
326     public void setValidating(boolean validate) {
327         this.validate = validate;
328     }
329
330     public void startDocument() throws SAXException JavaDoc {
331         // no-op
332
}
333
334     public void setDocumentLocator(Locator JavaDoc locator) {
335         // no-op
336
}
337
338     public void startPrefixMapping(String JavaDoc prefix, String JavaDoc uri)
339         throws SAXException JavaDoc {
340         namespaceMappings.put(prefix, uri);
341     }
342
343     public void startElement(String JavaDoc namespaceURI, String JavaDoc localName,
344                              String JavaDoc qName, org.xml.sax.Attributes JavaDoc atts)
345         throws SAXException JavaDoc {
346
347         // Feed this to the correct ContentHandler
348
Unmarshallable current = getCurrentUNode();
349         if (current != this) {
350             current.startElement(namespaceURI, localName, qName, atts);
351             return;
352         }
353
354         // See if we handle, or we delegate
355
if ((localName.equals("distributable")) && (!zeus_thisNodeHandled)) {
356             // Handle ourselves
357
for (int i=0, len=atts.getLength(); i<len; i++) {
358                 String JavaDoc attName= atts.getLocalName(i);
359                 String JavaDoc attValue = atts.getValue(i);
360                 if (attName.equals("id")) {
361                     setId(attValue);
362                 }
363             }
364             zeus_thisNodeHandled = true;
365             return;
366         } else {
367             // Delegate handling
368
}
369     }
370
371     public void endElement(String JavaDoc namespaceURI, String JavaDoc localName,
372                            String JavaDoc qName)
373         throws SAXException JavaDoc {
374
375         Unmarshallable current = getCurrentUNode();
376         if (current != this) {
377             current.endElement(namespaceURI, localName, qName);
378             return;
379         }
380
381         Unmarshallable parent = getCurrentUNode().getParentUNode();
382         if (parent != null) {
383             parent.setCurrentUNode(parent);
384         }
385     }
386
387     public void characters(char[] ch, int start, int len)
388         throws SAXException JavaDoc {
389
390         // Feed this to the correct ContentHandler
391
Unmarshallable current = getCurrentUNode();
392         if (current != this) {
393             current.characters(ch, start, len);
394             return;
395         }
396
397         String JavaDoc text = new String JavaDoc(ch, start, len);
398     }
399
400     public void comment(char ch[], int start, int len) throws SAXException JavaDoc {
401         // Currently no-op
402
}
403
404     public void warning(SAXParseException JavaDoc e) throws SAXException JavaDoc {
405         if (errorHandler != null) {
406             errorHandler.warning(e);
407         }
408     }
409
410     public void error(SAXParseException JavaDoc e) throws SAXException JavaDoc {
411         if ((validate) && (!hasDTD)) {
412             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.");
413         }
414         if (errorHandler != null) {
415             errorHandler.error(e);
416         }
417     }
418
419     public void fatalError(SAXParseException JavaDoc e) throws SAXException JavaDoc {
420         if ((validate) && (!hasDTD)) {
421             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.");
422         }
423         if (errorHandler != null) {
424             errorHandler.fatalError(e);
425         }
426     }
427
428     public void startDTD(String JavaDoc name, String JavaDoc publicID, String JavaDoc systemID)
429         throws SAXException JavaDoc {
430
431         if ((name == null) || (name.equals(""))) {
432             docTypeString = "";
433             return;
434         }
435
436         hasDTD = true;
437         StringBuffer JavaDoc docTypeSB = new StringBuffer JavaDoc();
438         boolean hasPublic = false;
439
440         docTypeSB.append("<!DOCTYPE ")
441                  .append(name);
442
443         if ((publicID != null) && (!publicID.equals(""))) {
444             docTypeSB.append(" PUBLIC \"")
445                      .append(publicID)
446                      .append("\"");
447             hasPublic = true;
448         }
449
450         if ((systemID != null) && (!systemID.equals(""))) {
451             if (!hasPublic) {
452                 docTypeSB.append(" SYSTEM");
453             }
454             docTypeSB.append(" \"")
455                      .append(systemID)
456                      .append("\"");
457
458         }
459
460         docTypeSB.append(">");
461
462         docTypeString = docTypeSB.toString();
463     }
464
465     public void endDTD() throws SAXException JavaDoc {
466         // Currently no-op
467
}
468
469     public void startEntity(String JavaDoc name) throws SAXException JavaDoc {
470         // Currently no-op
471
}
472
473     public void endEntity(String JavaDoc name) throws SAXException JavaDoc {
474         // Currently no-op
475
}
476
477     public void startCDATA() throws SAXException JavaDoc {
478         // Currently no-op
479
}
480
481     public void endCDATA() throws SAXException JavaDoc {
482         // Currently no-op
483
}
484
485 }
486
Popular Tags