KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > jaxp > SourceTransformer


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.jbi.jaxp;
18
19 import java.io.ByteArrayInputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.io.InputStreamReader JavaDoc;
23 import java.io.Reader JavaDoc;
24 import java.io.StringWriter JavaDoc;
25
26 import javax.jbi.messaging.MessagingException;
27 import javax.jbi.messaging.NormalizedMessage;
28 import javax.xml.parsers.DocumentBuilder JavaDoc;
29 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
30 import javax.xml.parsers.ParserConfigurationException JavaDoc;
31 import javax.xml.transform.Result JavaDoc;
32 import javax.xml.transform.Source JavaDoc;
33 import javax.xml.transform.Transformer JavaDoc;
34 import javax.xml.transform.TransformerConfigurationException JavaDoc;
35 import javax.xml.transform.TransformerException JavaDoc;
36 import javax.xml.transform.TransformerFactory JavaDoc;
37 import javax.xml.transform.dom.DOMSource JavaDoc;
38 import javax.xml.transform.sax.SAXSource JavaDoc;
39 import javax.xml.transform.stream.StreamResult JavaDoc;
40 import javax.xml.transform.stream.StreamSource JavaDoc;
41
42 import org.apache.commons.logging.Log;
43 import org.apache.commons.logging.LogFactory;
44 import org.apache.xalan.xsltc.trax.DOM2SAX;
45 import org.apache.xalan.xsltc.trax.SAX2DOM;
46 import org.w3c.dom.Document JavaDoc;
47 import org.w3c.dom.Element JavaDoc;
48 import org.w3c.dom.Node JavaDoc;
49 import org.xml.sax.InputSource JavaDoc;
50 import org.xml.sax.SAXException JavaDoc;
51 import org.xml.sax.XMLReader JavaDoc;
52 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
53
54 /**
55  * A helper class to transform from one type of {@link Source} to another
56  *
57  * @version $Revision: 431309 $
58  */

59 public class SourceTransformer {
60     public static final String JavaDoc CONTENT_DOCUMENT_PROPERTY = "org.apache.servicemix.content.document";
61
62     private static final transient Log log = LogFactory.getLog(SourceTransformer.class);
63
64     private DocumentBuilderFactory JavaDoc documentBuilderFactory;
65     private TransformerFactory JavaDoc transformerFactory;
66
67     public static final String JavaDoc defaultCharEncodingName = "UTF-8";
68         
69     public SourceTransformer() {
70     }
71
72     public SourceTransformer(DocumentBuilderFactory JavaDoc documentBuilderFactory) {
73         this.documentBuilderFactory = documentBuilderFactory;
74     }
75
76
77     /**
78      * Converts the given input Source into the required result
79      */

80     public void toResult(Source JavaDoc source, Result JavaDoc result) throws TransformerException JavaDoc {
81         Transformer JavaDoc transformer = createTransfomer();
82         if (transformer == null) {
83             throw new TransformerException JavaDoc("Could not create a transformer - JAXP is misconfigured!");
84         }
85         if (source != null) {
86             transformer.transform(source, result);
87         }
88         else {
89             log.warn("No Source available");
90         }
91     }
92
93
94     /**
95      * Converts the given input Source into text
96      */

97     public String JavaDoc toString(Source JavaDoc source) throws TransformerException JavaDoc {
98         if (source == null) {
99             return null;
100         } else if (source instanceof StringSource) {
101             return ((StringSource) source).getText();
102         } else if (source instanceof BytesSource) {
103             return new String JavaDoc(((BytesSource) source).getData());
104         } else {
105             StringWriter JavaDoc buffer = new StringWriter JavaDoc();
106             toResult(source, new StreamResult JavaDoc(buffer));
107             return buffer.toString();
108         }
109     }
110
111     /**
112      * Converts the given input Node into text
113      */

114     public String JavaDoc toString(Node JavaDoc node) throws TransformerException JavaDoc {
115         return toString(new DOMSource JavaDoc(node));
116     }
117
118     /**
119      * Converts the content of the given message to a String
120      * @throws SAXException
121      * @throws IOException
122      * @throws ParserConfigurationException
123      */

124     public String JavaDoc contentToString(NormalizedMessage message) throws MessagingException, TransformerException JavaDoc, ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
125         return toString(message.getContent());
126     }
127
128     /**
129      * Converts the source instance to a {@link DOMSource} or returns null if the conversion is not
130      * supported (making it easy to derive from this class to add new kinds of conversion).
131      */

132     public DOMSource JavaDoc toDOMSource(Source JavaDoc source) throws ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc, TransformerException JavaDoc {
133         if (source instanceof DOMSource JavaDoc) {
134             return (DOMSource JavaDoc) source;
135         }
136         else if (source instanceof SAXSource JavaDoc) {
137             return toDOMSourceFromSAX((SAXSource JavaDoc) source);
138         }
139         else if (source instanceof StreamSource JavaDoc) {
140             return toDOMSourceFromStream((StreamSource JavaDoc) source);
141         }
142         else {
143             return null;
144         }
145     }
146
147     public Source JavaDoc toDOMSource(NormalizedMessage message) throws MessagingException, TransformerException JavaDoc, ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
148         Node JavaDoc node = toDOMNode(message);
149         return new DOMSource JavaDoc(node);
150     }
151
152     /**
153      * Converts the source instance to a {@link SAXSource} or returns null if the conversion is not
154      * supported (making it easy to derive from this class to add new kinds of conversion).
155      */

156     public SAXSource JavaDoc toSAXSource(Source JavaDoc source) throws IOException JavaDoc, SAXException JavaDoc {
157         if (source instanceof SAXSource JavaDoc) {
158             return (SAXSource JavaDoc) source;
159         }
160         else if (source instanceof DOMSource JavaDoc) {
161             return toSAXSourceFromDOM((DOMSource JavaDoc) source);
162         }
163         else if (source instanceof StreamSource JavaDoc) {
164             return toSAXSourceFromStream((StreamSource JavaDoc) source);
165         }
166         else {
167             return null;
168         }
169     }
170
171     public StreamSource JavaDoc toStreamSource(Source JavaDoc source) throws TransformerException JavaDoc {
172         if (source instanceof StreamSource JavaDoc) {
173             return (StreamSource JavaDoc) source;
174         } else if (source instanceof DOMSource JavaDoc) {
175             return toStreamSourceFromDOM((DOMSource JavaDoc) source);
176         } else if (source instanceof SAXSource JavaDoc) {
177             return toStreamSourceFromSAX((SAXSource JavaDoc) source);
178         } else {
179             return null;
180         }
181     }
182
183     public StreamSource JavaDoc toStreamSourceFromSAX(SAXSource JavaDoc source) throws TransformerException JavaDoc {
184         InputSource JavaDoc inputSource = source.getInputSource();
185         if (inputSource != null) {
186             if (inputSource.getByteStream() != null) {
187                 return new StreamSource JavaDoc(inputSource.getByteStream());
188             }
189             if (inputSource.getCharacterStream() != null) {
190                 return new StreamSource JavaDoc(inputSource.getCharacterStream());
191             }
192         }
193         String JavaDoc result = toString(source);
194         return new StreamSource JavaDoc(new ByteArrayInputStream JavaDoc(result.getBytes()));
195     }
196
197     public StreamSource JavaDoc toStreamSourceFromDOM(DOMSource JavaDoc source) throws TransformerException JavaDoc {
198         String JavaDoc result = toString(source);
199         return new StreamSource JavaDoc(new ByteArrayInputStream JavaDoc(result.getBytes()));
200     }
201
202     public SAXSource JavaDoc toSAXSourceFromStream(StreamSource JavaDoc source) {
203         InputSource JavaDoc inputSource = new InputSource JavaDoc(source.getInputStream());
204         inputSource.setSystemId(source.getSystemId());
205         inputSource.setPublicId(source.getPublicId());
206         return new SAXSource JavaDoc(inputSource);
207     }
208
209     public Reader JavaDoc toReaderFromSource(Source JavaDoc src) throws TransformerException JavaDoc {
210         StreamSource JavaDoc stSrc = toStreamSource(src);
211         Reader JavaDoc r = stSrc.getReader();
212         if (r == null) {
213             r = new InputStreamReader JavaDoc(stSrc.getInputStream());
214         }
215         return r;
216     }
217
218     public DOMSource JavaDoc toDOMSourceFromStream(StreamSource JavaDoc source) throws ParserConfigurationException JavaDoc, IOException JavaDoc,
219             SAXException JavaDoc {
220         DocumentBuilder JavaDoc builder = createDocumentBuilder();
221         String JavaDoc systemId = source.getSystemId();
222         Document JavaDoc document = null;
223         InputStream JavaDoc inputStream = source.getInputStream();
224         if (inputStream != null) {
225             InputSource JavaDoc inputsource = new InputSource JavaDoc(inputStream);
226             inputsource.setSystemId(systemId);
227             inputsource.setEncoding(defaultCharEncodingName);
228             document = builder.parse(inputsource);
229         }
230         else {
231             Reader JavaDoc reader = source.getReader();
232             if (reader != null) {
233                 document = builder.parse(new InputSource JavaDoc(reader));
234             }
235             else {
236                 throw new IOException JavaDoc("No input stream or reader available");
237             }
238         }
239         return new DOMSource JavaDoc(document, systemId);
240     }
241
242     public SAXSource JavaDoc toSAXSourceFromDOM(DOMSource JavaDoc source) {
243         DOM2SAX converter = new DOM2SAX(source.getNode());
244         String JavaDoc systemId = converter.getSystemId();
245         return new SAXSource JavaDoc(converter, new InputSource JavaDoc(systemId));
246     }
247
248     public DOMSource JavaDoc toDOMSourceFromSAX(SAXSource JavaDoc source) throws IOException JavaDoc, SAXException JavaDoc, ParserConfigurationException JavaDoc {
249         return new DOMSource JavaDoc(toDOMNodeFromSAX(source));
250     }
251
252     public Node JavaDoc toDOMNodeFromSAX(SAXSource JavaDoc source) throws ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
253         SAX2DOM converter = new SAX2DOM(createDocument());
254         XMLReader JavaDoc xmlReader = source.getXMLReader();
255         if (xmlReader == null) {
256             xmlReader = createXMLReader();
257         }
258         xmlReader.setContentHandler(converter);
259         xmlReader.parse(source.getInputSource());
260         return converter.getDOM();
261     }
262
263     private XMLReader JavaDoc createXMLReader() throws SAXException JavaDoc {
264         // In JDK 1.4, the xml reader factory does not look for META-INF services
265
// If the org.xml.sax.driver system property is not defined, and exception will be thrown.
266
// In these cases, default to xerces parser
267
try {
268             return XMLReaderFactory.createXMLReader();
269         } catch (Exception JavaDoc e) {
270             return XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
271         }
272     }
273
274
275     /**
276      * Converts the given TRaX Source into a W3C DOM node
277      * @throws SAXException
278      * @throws IOException
279      * @throws ParserConfigurationException
280      */

281     public Node JavaDoc toDOMNode(Source JavaDoc source) throws TransformerException JavaDoc, ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
282         return toDOMSource(source).getNode();
283     }
284
285     /**
286      * Avoids multple parsing to DOM by caching the DOM representation in the message
287      * as a property so future calls will avoid the reparse - and avoid issues with
288      * stream based Source instances.
289      *
290      * @param message the normalized message
291      * @return the W3C DOM node for this message
292      * @throws SAXException
293      * @throws IOException
294      * @throws ParserConfigurationException
295      */

296     public Node JavaDoc toDOMNode(NormalizedMessage message) throws MessagingException, TransformerException JavaDoc, ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
297         Object JavaDoc value = message.getProperty(CONTENT_DOCUMENT_PROPERTY);
298         if (value != null) {
299             if (value instanceof Node JavaDoc) {
300                 return (Node JavaDoc) value;
301             }
302             else {
303                 throw new MessagingException("Invalid property type: Expected W3C DOM node but found: " + value.getClass().getName() + " with value: " + value);
304             }
305         }
306         else {
307             Source JavaDoc content = message.getContent();
308             if (content != null) {
309                 Node JavaDoc node = toDOMNode(content);
310                 message.setProperty(CONTENT_DOCUMENT_PROPERTY, node);
311                 return node;
312             }
313             else {
314                 return null;
315             }
316         }
317     }
318     
319     /**
320      * Create a DOM element from the normalized message.
321      *
322      * @param message
323      * @return
324      * @throws MessagingException
325      * @throws TransformerException
326      * @throws ParserConfigurationException
327      * @throws IOException
328      * @throws SAXException
329      */

330     public Element JavaDoc toDOMElement(NormalizedMessage message) throws MessagingException, TransformerException JavaDoc, ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
331         Node JavaDoc node = toDOMNode(message);
332         return toDOMElement(node);
333     }
334     
335     /**
336      * Create a DOM element from the given source.
337      *
338      * @param source
339      * @return
340      * @throws TransformerException
341      * @throws ParserConfigurationException
342      * @throws IOException
343      * @throws SAXException
344      */

345     public Element JavaDoc toDOMElement(Source JavaDoc source) throws TransformerException JavaDoc, ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
346         Node JavaDoc node = toDOMNode(source);
347         return toDOMElement(node);
348     }
349     
350     /**
351      * Create a DOM element from the DOM node.
352      * Simply cast if the node is an Element, or
353      * return the root element if it is a Document.
354      *
355      * @param node
356      * @return
357      * @throws TransformerException
358      */

359     public Element JavaDoc toDOMElement(Node JavaDoc node) throws TransformerException JavaDoc {
360         Element JavaDoc elem;
361         // If the node is an document, return the root element
362
if (node instanceof Document JavaDoc) {
363             return ((Document JavaDoc) node).getDocumentElement();
364         // If the node is an element, just cast it
365
} else if (node instanceof Element JavaDoc) {
366             return (Element JavaDoc) node;
367         // Other node types are not handled
368
} else {
369             throw new TransformerException JavaDoc("Unable to convert DOM node to an Element");
370         }
371     }
372     
373     /**
374      * Create a DOM document from the given normalized message
375      *
376      * @param message
377      * @return
378      * @throws MessagingException
379      * @throws TransformerException
380      * @throws ParserConfigurationException
381      * @throws IOException
382      * @throws SAXException
383      */

384     public Document JavaDoc toDOMDocument(NormalizedMessage message) throws MessagingException, TransformerException JavaDoc, ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
385         Node JavaDoc node = toDOMNode(message);
386         return toDOMDocument(node);
387     }
388     
389     /**
390      * Create a DOM document from the given source.
391      *
392      * @param source
393      * @return
394      * @throws TransformerException
395      * @throws ParserConfigurationException
396      * @throws IOException
397      * @throws SAXException
398      */

399     public Document JavaDoc toDOMDocument(Source JavaDoc source) throws TransformerException JavaDoc, ParserConfigurationException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
400         Node JavaDoc node = toDOMNode(source);
401         return toDOMDocument(node);
402     }
403     
404     /**
405      * Create a DOM document from the given Node.
406      * If the node is an document, just cast it,
407      * if the node is an root element, retrieve its
408      * owner element or create a new document and import
409      * the node.
410      *
411      * @param node
412      * @return
413      * @throws ParserConfigurationException
414      * @throws TransformerException
415      */

416     public Document JavaDoc toDOMDocument(Node JavaDoc node) throws ParserConfigurationException JavaDoc, TransformerException JavaDoc {
417         // If the node is the document, just cast it
418
if (node instanceof Document JavaDoc) {
419             return (Document JavaDoc) node;
420         // If the node is an element
421
} else if (node instanceof Element JavaDoc) {
422             Element JavaDoc elem = (Element JavaDoc) node;
423             // If this is the root element, return its owner document
424
if (elem.getOwnerDocument().getDocumentElement() == elem) {
425                 return elem.getOwnerDocument();
426             // else, create a new doc and copy the element inside it
427
} else {
428                 Document JavaDoc doc = createDocument();
429                 doc.appendChild(doc.importNode(node, true));
430                 return doc;
431             }
432         // other element types are not handled
433
} else {
434             throw new TransformerException JavaDoc("Unable to convert DOM node to a Document");
435         }
436     }
437
438     // Properties
439
//-------------------------------------------------------------------------
440
public DocumentBuilderFactory JavaDoc getDocumentBuilderFactory() {
441         if (documentBuilderFactory == null) {
442             documentBuilderFactory = createDocumentBuilderFactory();
443         }
444         return documentBuilderFactory;
445     }
446
447     public void setDocumentBuilderFactory(DocumentBuilderFactory JavaDoc documentBuilderFactory) {
448         this.documentBuilderFactory = documentBuilderFactory;
449     }
450
451
452     // Helper methods
453
//-------------------------------------------------------------------------
454
public DocumentBuilderFactory JavaDoc createDocumentBuilderFactory() {
455         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
456         factory.setNamespaceAware(true);
457         factory.setIgnoringElementContentWhitespace(true);
458         factory.setIgnoringComments(true);
459         return factory;
460     }
461
462
463     public DocumentBuilder JavaDoc createDocumentBuilder() throws ParserConfigurationException JavaDoc {
464         DocumentBuilderFactory JavaDoc factory = getDocumentBuilderFactory();
465         return factory.newDocumentBuilder();
466     }
467
468     public Document JavaDoc createDocument() throws ParserConfigurationException JavaDoc {
469         DocumentBuilder JavaDoc builder = createDocumentBuilder();
470         return builder.newDocument();
471     }
472
473     public TransformerFactory JavaDoc getTransformerFactory() {
474         if (transformerFactory == null) {
475             transformerFactory = createTransformerFactory();
476         }
477         return transformerFactory;
478     }
479
480     public void setTransformerFactory(TransformerFactory JavaDoc transformerFactory) {
481         this.transformerFactory = transformerFactory;
482     }
483
484     public Transformer JavaDoc createTransfomer() throws TransformerConfigurationException JavaDoc {
485         TransformerFactory JavaDoc factory = getTransformerFactory();
486         return factory.newTransformer();
487     }
488
489     public TransformerFactory JavaDoc createTransformerFactory() {
490         TransformerFactory JavaDoc answer = TransformerFactory.newInstance();
491         return answer;
492     }
493
494 }
495
Popular Tags