KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exoplatform > services > xml > querying > impl > xtas > WellFormedUniFormTree


1 package org.exoplatform.services.xml.querying.impl.xtas;
2
3 import java.io.ByteArrayOutputStream JavaDoc;
4 import java.io.InputStream JavaDoc;
5 import java.io.ByteArrayInputStream JavaDoc;
6
7 import org.xml.sax.XMLReader JavaDoc;
8 import org.xml.sax.InputSource JavaDoc;
9 import org.xml.sax.ContentHandler JavaDoc;
10 import org.xml.sax.SAXException JavaDoc;
11
12 import javax.xml.transform.sax.TransformerHandler JavaDoc;
13 import javax.xml.transform.sax.SAXTransformerFactory JavaDoc;
14 import javax.xml.transform.stream.StreamResult JavaDoc;
15 import javax.xml.transform.stream.StreamSource JavaDoc;
16 import javax.xml.transform.dom.DOMSource JavaDoc;
17 import javax.xml.transform.dom.DOMResult JavaDoc;
18 import javax.xml.transform.sax.SAXResult JavaDoc;
19 import javax.xml.transform.Result JavaDoc;
20 import javax.xml.transform.TransformerException JavaDoc;
21 import javax.xml.transform.Transformer JavaDoc;
22 import javax.xml.transform.Source JavaDoc;
23
24 import javax.xml.parsers.SAXParserFactory JavaDoc;
25 import javax.xml.parsers.ParserConfigurationException JavaDoc;
26
27 import org.exoplatform.services.xml.querying.UniFormTransformationException;
28 import org.exoplatform.services.xml.querying.XMLWellFormedData;
29 import org.exoplatform.services.xml.querying.impl.xtas.object.MappingType;
30 import org.exoplatform.services.xml.querying.impl.xtas.object.ObjectMarshaller;
31 import org.exoplatform.services.xml.querying.impl.xtas.object.ObjectMarshallerFactory;
32 import org.exoplatform.services.xml.querying.impl.xtas.xml.DtdTracer;
33 import org.exoplatform.services.xml.querying.impl.xtas.xml.Utils;
34 import org.exoplatform.services.xml.querying.object.MarshallerCreateException;
35 import org.exoplatform.services.xml.querying.object.ObjectMappingException;
36 import org.exoplatform.services.xml.querying.object.ObjectMarshalException;
37 import org.w3c.dom.Node JavaDoc;
38 import org.w3c.dom.NodeList JavaDoc;
39 import org.w3c.dom.Document JavaDoc;
40
41
42 /**
43  * Well-formed UniFormTree - "natural" XML
44  * Can be validated, serialized etc.
45  *
46  * @version $Id: WellFormedUniFormTree.java 566 2005-01-25 12:50:49Z kravchuk $
47  */

48 public class WellFormedUniFormTree extends UniFormTree implements XMLWellFormedData {
49
50     private DtdTracer validationHandler;
51     protected XMLReader JavaDoc reader=null;
52     protected TransformerHandler JavaDoc handler;
53     protected static SAXTransformerFactory JavaDoc sFactory;
54     protected static SAXParserFactory JavaDoc parserFactory;
55
56
57     static {
58
59         try {
60
61              parserFactory = SAXParserFactory.newInstance();
62              sFactory = (SAXTransformerFactory JavaDoc) tFactory;
63
64         } catch (Exception JavaDoc e) {
65             // @todo Log system!
66
System.out.println("Can not INSTANTIATE WellFormedUniFormTree Object Reason: " + e);
67         }
68
69     }
70
71
72     /**
73      * Creates an empty UniFormTree
74      */

75     public WellFormedUniFormTree() throws UniFormTransformationException
76     {
77          validationHandler = new DtdTracer();
78
79          try {
80
81         // If this feature is set to true, the document must specify a
82
// grammar. By default, validation will occur against DTD.
83
// If this feature is set to false, and document specifies a
84
// grammar that grammar might be parsed but no validation
85
// of the document contents will be performed.
86

87
88              handler = sFactory.newTransformerHandler();
89              handler.setResult(new StreamResult JavaDoc( this.thisStream ));
90
91              handler.getTransformer().setOutputProperty(
92                  javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
93
94              reader = parserFactory.newSAXParser().getXMLReader();
95
96              reader.setContentHandler(handler);
97
98              setValidate(false);
99
100              reader.setProperty("http://xml.org/sax/properties/lexical-handler",
101                                 validationHandler);
102              reader.setProperty("http://xml.org/sax/properties/declaration-handler",
103                                 validationHandler);
104
105
106          } catch (Exception JavaDoc e) {
107              // @todo Log system!
108
throw new UniFormTransformationException (" WellFormedUniFormTree(InputStream stream) ERROR: Reason: " + e);
109          }
110
111
112     }
113
114     /**
115      * Initializes this with the SAX's InputSource
116      */

117     public void init(InputSource JavaDoc src) throws UniFormTransformationException
118     {
119
120        try {
121
122            reader.parse( src );
123
124         } catch (Exception JavaDoc e) {
125
126            throw new UniFormTransformationException("UniformTree.Init(inputStream): Can not parse InputSource Reason: " + e);
127         }
128     }
129
130     /**
131      * Initializes this with the DOM's Node
132      */

133     public void init(Node JavaDoc node) throws UniFormTransformationException
134     {
135
136         try {
137
138              // Reinitialize thisStream
139
thisStream = new ByteArrayOutputStream JavaDoc();
140
141              transformer.transform( new DOMSource JavaDoc(node) ,
142                                     new StreamResult JavaDoc( thisStream ) );
143
144         //FactoryConfigurationError,FactoryConfigurationError,SAXException
145
} catch (Exception JavaDoc e) {
146
147             throw new UniFormTransformationException("UniformTree.Init(Node): Can not Transform Reason: " + e);
148
149         }
150     }
151
152     /**
153      * Marshalls Java object using obj.getClass() as mapping and creates UniFormTree object
154      * WARNING: Will be used for all objects except NodeList, InputStream, DOM Document, InputSource
155      */

156     public void init(Object JavaDoc obj) throws ObjectMarshalException, MarshallerCreateException, ObjectMappingException
157     {
158         if ( (obj instanceof InputStream JavaDoc) || (obj instanceof NodeList JavaDoc) || (obj instanceof Document JavaDoc) || (obj instanceof InputSource JavaDoc) )
159             throw new ObjectMappingException( "DEV-ERROR! init(Object) Parameter MUST NOT BE "+
160                        obj.getClass().getName()+" TYPE!");
161         init( obj.getClass(), obj );
162     }
163
164     /**
165      * Marshalls Java object using <code> mapping </code> and creates UniFormTree object
166      */

167     public void init(Object JavaDoc mapping, Object JavaDoc obj) throws ObjectMarshalException, MarshallerCreateException, ObjectMappingException
168     {
169         // Reinitialize thisStream
170
thisStream = new ByteArrayOutputStream JavaDoc();
171
172
173         int mappingType = MappingType.INTERNAL;
174         if( !(mapping instanceof Class JavaDoc) )
175             mappingType = MappingType.CUSTOM;
176
177         ObjectMarshaller marshaller = ObjectMarshallerFactory.getInstance().getMarshaller( mappingType );
178         marshaller.loadMapping( mapping );
179
180         try {
181
182             Document JavaDoc doc = Utils.createDocument();
183             doc = marshaller.marshal( obj );
184
185             transformer.transform( new DOMSource JavaDoc(doc) ,
186                                    new StreamResult JavaDoc( thisStream ) );
187         } catch (Exception JavaDoc e) {
188
189             throw new ObjectMarshalException("UniFormTree.init(Object mapping, Object obj) Exception: " + e);
190         }
191     }
192
193     /**
194      * Initializes with root node
195      * Note: it is impossible to insert without child
196      * adding " " for as a text child - Statement.append("root/text()",.....)
197      */

198     public void initRoot(String JavaDoc nodeName) throws UniFormTransformationException
199     {
200
201        try {
202
203            init ( new InputSource JavaDoc (new ByteArrayInputStream JavaDoc(("<"+nodeName+"> </"+nodeName+">").getBytes() ) ) );
204
205         } catch (Exception JavaDoc e) {
206
207            throw new UniFormTransformationException("UniformTree.Init(inputStream): Can not parse InputSource Reason: " + e);
208         }
209     }
210
211     /**
212      * This object as ByteArray (is required by superclass)
213      */

214     public byte[] getAsByteArray()
215     {
216         ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
217         StreamResult JavaDoc sr = new StreamResult JavaDoc(bos);
218         convert( sr );
219         return bos.toByteArray();
220     }
221
222     /**
223      * This object as DOM Node
224      */

225     public Node JavaDoc getAsDOM()
226     {
227
228         Document JavaDoc tmpDoc = null;
229         try {
230
231             tmpDoc = Utils.createDocument();
232
233         } catch (ParserConfigurationException JavaDoc e) {
234 // throw new UniFormTransformationException("Can not create DOM Reason: " + e);
235
System.out.println("UniFormTree.getAsDOM(): Can not create DOM Reason: " + e);
236         }
237
238         convert( new DOMResult JavaDoc(tmpDoc) );
239         return tmpDoc;
240     }
241
242     /**
243      * Parse this XML using ContentHandler
244      */

245     public void processAsSAX(ContentHandler JavaDoc handler) throws SAXException JavaDoc
246     {
247         try {
248            convert( new SAXResult JavaDoc(handler), true );
249
250         } catch (Exception JavaDoc e) {
251
252            throw new SAXException JavaDoc("WellFormedUniFormTree.processAsSAX() failed. Reason: "+e);
253         }
254     }
255
256     /**
257      * Parse this XML using ContentHandler
258      */

259     public void transformWithXSL(Result JavaDoc result, Source JavaDoc xslTemplate) throws TransformerException JavaDoc
260     {
261
262         try {
263              if(xslTemplate == null)
264                  convert( result, true );
265              else {
266                 Transformer JavaDoc trans;
267                 trans = tFactory.newTransformer(xslTemplate);
268                 trans.transform( new StreamSource JavaDoc( new ByteArrayInputStream JavaDoc(
269                                      thisStream.toByteArray() ) ), result );
270              }
271
272         } catch (Exception JavaDoc e) {
273
274            throw new TransformerException JavaDoc("WellFormedUniFormTree.transformWithXSL() failed. Reason: "+e);
275         }
276     }
277
278     /**
279      * Will output be wit the xml declaration?
280      */

281     public void setOmitXmlDeclaration(boolean yesNo)
282     {
283         transformer.setOutputProperty(
284             javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, (yesNo?"yes":"no"));
285     }
286
287     /**
288      * Will output be indent?
289      */

290     public void setIndentOutput(boolean yesNo)
291     {
292         transformer.setOutputProperty(
293             javax.xml.transform.OutputKeys.INDENT, (yesNo?"yes":"no"));
294     }
295
296     /**
297      * SystemId for output
298      */

299     public void setDTDSystemId(String JavaDoc systemId)
300     {
301         transformer.setOutputProperty(
302              javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM, systemId);
303     }
304
305     /**
306      * PublicId for output
307      */

308     public void setDTDPublicId(String JavaDoc publicId)
309     {
310         transformer.setOutputProperty(
311              javax.xml.transform.OutputKeys.DOCTYPE_PUBLIC, publicId);
312     }
313
314     public DtdTracer getValidationHandler()
315     {
316        return validationHandler;
317     }
318
319     /**
320      * Will this object be validated?
321      */

322     public void setValidate(boolean yesNo)
323     {
324          try {
325              reader.setFeature("http://xml.org/sax/features/validation", yesNo);
326
327          } catch (Exception JavaDoc e) {
328              // @todo Log system!
329
System.out.println("WellFormedUniFormTree.setValidate(): " + e);
330          }
331     }
332 }
333
Popular Tags