KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdom > transform > JDOMSource


1 /*--
2
3  $Id: JDOMSource.java,v 1.18 2004/08/31 04:43:48 jhunter Exp $
4
5  Copyright (C) 2001-2004 Jason Hunter & Brett McLaughlin.
6  All rights reserved.
7  
8  Redistribution and use in source and binary forms, with or without
9  modification, are permitted provided that the following conditions
10  are met:
11  
12  1. Redistributions of source code must retain the above copyright
13     notice, this list of conditions, and the following disclaimer.
14  
15  2. Redistributions in binary form must reproduce the above copyright
16     notice, this list of conditions, and the disclaimer that follows
17     these conditions in the documentation and/or other materials
18     provided with the distribution.
19
20  3. The name "JDOM" must not be used to endorse or promote products
21     derived from this software without prior written permission. For
22     written permission, please contact <request_AT_jdom_DOT_org>.
23  
24  4. Products derived from this software may not be called "JDOM", nor
25     may "JDOM" appear in their name, without prior written permission
26     from the JDOM Project Management <request_AT_jdom_DOT_org>.
27  
28  In addition, we request (but do not require) that you include in the
29  end-user documentation provided with the redistribution and/or in the
30  software itself an acknowledgement equivalent to the following:
31      "This product includes software developed by the
32       JDOM Project (http://www.jdom.org/)."
33  Alternatively, the acknowledgment may be graphical using the logos
34  available at http://www.jdom.org/images/logos.
35
36  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
40  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  SUCH DAMAGE.
48
49  This software consists of voluntary contributions made by many
50  individuals on behalf of the JDOM Project and was originally
51  created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
52  Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information
53  on the JDOM Project, please see <http://www.jdom.org/>.
54  
55  */

56
57 package org.jdom.transform;
58
59 import java.io.*;
60 import java.util.*;
61
62 import javax.xml.transform.sax.*;
63
64 import org.jdom.*;
65 import org.jdom.output.*;
66 import org.xml.sax.*;
67
68 /**
69  * A holder for an XML Transformation source: a Document, Element, or list of
70  * nodes.
71  * <p>
72  * The is provides input to a
73  * {@link javax.xml.transform.Transformer JAXP TrAX Transformer}.
74  * <p>
75  * The following example shows how to apply an XSL Transformation
76  * to a JDOM document and get the transformation result in the form
77  * of a list of JDOM nodes:
78  * <pre><code>
79  * public static List transform(Document doc, String stylesheet)
80  * throws JDOMException {
81  * try {
82  * Transformer transformer = TransformerFactory.newInstance()
83  * .newTransformer(new StreamSource(stylesheet));
84  * JDOMSource in = new JDOMSource(doc);
85  * JDOMResult out = new JDOMResult();
86  * transformer.transform(in, out);
87  * return out.getResult();
88  * }
89  * catch (TransformerException e) {
90  * throw new JDOMException("XSLT Transformation failed", e);
91  * }
92  * }
93  * </code></pre>
94  *
95  * @see org.jdom.transform.JDOMResult
96  *
97  * @version $Revision: 1.18 $, $Date: 2004/08/31 04:43:48 $
98  * @author Laurent Bihanic
99  * @author Jason Hunter
100  */

101 public class JDOMSource extends SAXSource {
102
103     private static final String JavaDoc CVS_ID =
104     "@(#) $RCSfile: JDOMSource.java,v $ $Revision: 1.18 $ $Date: 2004/08/31 04:43:48 $ $Name: $";
105
106   /**
107    * If {@link javax.xml.transform.TransformerFactory#getFeature}
108    * returns <code>true</code> when passed this value as an
109    * argument, the Transformer natively supports JDOM.
110    * <p>
111    * <strong>Note</strong>: This implementation does not override
112    * the {@link SAXSource#FEATURE} value defined by its superclass
113    * to be considered as a SAXSource by Transformer implementations
114    * not natively supporting JDOM.
115    * </p>
116    */

117   public final static String JavaDoc JDOM_FEATURE =
118                       "http://org.jdom.transform.JDOMSource/feature";
119
120   /**
121    * The XMLReader object associated to this source or
122    * <code>null</code> if no XMLReader has yet been requested.
123    *
124    * @see #getXMLReader
125    */

126   private XMLReader xmlReader = null;
127
128   /**
129    * Creates a JDOM TrAX source wrapping a JDOM document.
130    *
131    * @param source the JDOM document to use as source for the
132    * transformations
133    *
134    * @throws IllegalArgumentException if <code>source</code> is
135    * <code>null</code>.
136    */

137   public JDOMSource(Document source) {
138     setDocument(source);
139   }
140
141   /**
142    * Creates a JDOM TrAX source wrapping a list of JDOM nodes.
143    *
144    * @param source the JDOM nodes to use as source for the
145    * transformations
146    *
147    * @throws IllegalArgumentException if <code>source</code> is
148    * <code>null</code>.
149    */

150   public JDOMSource(List source) {
151     setNodes(source);
152   }
153
154   /**
155    * Creates a JDOM TrAX source wrapping a JDOM element.
156    *
157    * @param source the JDOM element to use as source for the
158    * transformations
159    *
160    * @throws IllegalArgumentException if <code>source</code> is
161    * <code>null</code>.
162    */

163   public JDOMSource(Element source) {
164     List nodes = new ArrayList();
165     nodes.add(source);
166
167     setNodes(nodes);
168   }
169
170   /**
171    * Sets the source document used by this TrAX source.
172    *
173    * @param source the JDOM document to use as source for the
174    * transformations
175    *
176    * @throws IllegalArgumentException if <code>source</code> is
177    * <code>null</code>.
178    *
179    * @see #getDocument
180    */

181   public void setDocument(Document source) {
182     super.setInputSource(new JDOMInputSource(source));
183   }
184
185   /**
186    * Returns the source document used by this TrAX source.
187    *
188    * @return the source document used by this TrAX source or
189    * <code>null</code> if the source is a node list.
190    *
191    * @see #setDocument
192    */

193   public Document getDocument() {
194     Object JavaDoc src = ((JDOMInputSource)getInputSource()).getSource();
195     Document doc = null;
196
197     if (src instanceof Document) {
198       doc = (Document)src;
199     }
200     return doc;
201   }
202
203   /**
204    * Sets the source node list used by this TrAX source.
205    *
206    * @param source the JDOM nodes to use as source for the
207    * transformations
208    *
209    * @throws IllegalArgumentException if <code>source</code> is
210    * <code>null</code>.
211    *
212    * @see #getNodes
213    */

214   public void setNodes(List source) {
215     super.setInputSource(new JDOMInputSource(source));
216   }
217
218   /**
219    * Returns the source node list used by this TrAX source.
220    *
221    * @return the source node list used by this TrAX source or
222    * <code>null</code> if the source is a JDOM document.
223    *
224    * @see #setDocument
225    */

226   public List getNodes() {
227     Object JavaDoc src = ((JDOMInputSource)getInputSource()).getSource();
228     List nodes = null;
229
230     if (src instanceof List) {
231       nodes = (List)src;
232     }
233     return nodes;
234   }
235
236
237   //-------------------------------------------------------------------------
238
// SAXSource overwritten methods
239
//-------------------------------------------------------------------------
240

241   /**
242    * Sets the SAX InputSource to be used for the Source.
243    * <p>
244    * As this implementation only supports JDOM document as data
245    * source, this method always throws an
246    * {@link UnsupportedOperationException}.
247    * </p>
248    *
249    * @param inputSource a valid InputSource reference.
250    *
251    * @throws UnsupportedOperationException always!
252    */

253   public void setInputSource(InputSource inputSource)
254                                   throws UnsupportedOperationException JavaDoc {
255     throw new UnsupportedOperationException JavaDoc();
256   }
257
258   /**
259    * Set the XMLReader to be used for the Source.
260    * <p>
261    * As this implementation only supports JDOM document as data
262    * source, this method throws an
263    * {@link UnsupportedOperationException} if the provided reader
264    * object does not implement the SAX {@link XMLFilter}
265    * interface. Otherwise, the JDOM document reader will be
266    * attached as parent of the filter chain.</p>
267    *
268    * @param reader a valid XMLReader or XMLFilter reference.
269    *
270    * @throws UnsupportedOperationException if <code>reader</code>
271    * is not a SAX
272    * {@link XMLFilter}.
273    * @see #getXMLReader
274    */

275   public void setXMLReader(XMLReader reader)
276                               throws UnsupportedOperationException JavaDoc {
277     if (reader instanceof XMLFilter) {
278       // Connect the filter chain to a document reader.
279
XMLFilter filter = (XMLFilter)reader;
280       while (filter.getParent() instanceof XMLFilter) {
281         filter = (XMLFilter)(filter.getParent());
282       }
283       filter.setParent(new DocumentReader());
284
285       // Read XML data from filter chain.
286
this.xmlReader = reader;
287     }
288     else {
289       throw new UnsupportedOperationException JavaDoc();
290     }
291   }
292
293   /**
294    * Returns the XMLReader to be used for the Source.
295    * <p>
296    * This implementation returns a specific XMLReader reading
297    * the XML data from the source JDOM document.
298    * </p>
299    *
300    * @return an XMLReader reading the XML data from the source
301    * JDOM document.
302    */

303   public XMLReader getXMLReader() {
304     if (this.xmlReader == null) {
305       this.xmlReader = new DocumentReader();
306     }
307     return this.xmlReader;
308   }
309
310   //=========================================================================
311
// JDOMInputSource nested class
312
//=========================================================================
313

314   /**
315    * A subclass of the SAX InputSource interface that wraps a JDOM
316    * Document.
317    * <p>
318    * This class is nested in JDOMSource as it is not intented to
319    * be used independently of its friend: DocumentReader.
320    * </p>
321    *
322    * @see org.jdom.Document
323    */

324   private static class JDOMInputSource extends InputSource {
325     /**
326      * The source as a JDOM document or a list of JDOM nodes.
327      */

328     private Object JavaDoc source = null;
329
330     /**
331      * Builds a InputSource wrapping the specified JDOM Document.
332      *
333      * @param document the source document.
334      */

335     public JDOMInputSource(Document document) {
336       this.source = document;
337     }
338
339     /**
340      * Builds a InputSource wrapping a list of JDOM nodes.
341      *
342      * @param nodes the source JDOM nodes.
343      */

344     public JDOMInputSource(List nodes) {
345       this.source = nodes;
346     }
347
348     /**
349      * Returns the source.
350      *
351      * @return the source as a JDOM document or a list of JDOM nodes.
352      */

353     public Object JavaDoc getSource() {
354       return source;
355     }
356
357     //-------------------------------------------------------------------------
358
// InputSource overwritten methods
359
//-------------------------------------------------------------------------
360

361     /**
362      * Sets the character stream for this input source.
363      * <p>
364      * This implementation always throws an
365      * {@link UnsupportedOperationException} as the only source
366      * stream supported is the source JDOM document.
367      * </p>
368      *
369      * @param characterStream a character stream containing
370      * an XML document.
371      *
372      * @throws UnsupportedOperationException always!
373      */

374     public void setCharacterStream(Reader characterStream)
375                                       throws UnsupportedOperationException JavaDoc {
376       throw new UnsupportedOperationException JavaDoc();
377     }
378
379     /**
380      * Gets the character stream for this input source.
381      * <p>
382      * Note that this method is only provided to make this
383      * InputSource implementation acceptable by any XML
384      * parser. As it generates an in-memory string representation
385      * of the JDOM document, it is quite inefficient from both
386      * speed and memory consumption points of view.
387      * </p>
388      *
389      * @return a Reader to a string representation of the
390      * source JDOM document.
391      */

392     public Reader getCharacterStream() {
393       Object JavaDoc src = this.getSource();
394       Reader reader = null;
395
396       if (src instanceof Document) {
397         // Get an in-memory string representation of the document
398
// and return a reader on it.
399
reader = new StringReader(
400                             new XMLOutputter().outputString((Document)src));
401       }
402       else {
403         if (src instanceof List) {
404           reader = new StringReader(
405                             new XMLOutputter().outputString((List)src));
406         }
407         // Else: No source, no reader!
408
}
409       return reader;
410     }
411   }
412
413   //=========================================================================
414
// DocumentReader nested class
415
//=========================================================================
416

417   /**
418    * An implementation of the SAX2 XMLReader interface that presents
419    * a SAX view of a JDOM Document. The actual generation of the
420    * SAX events is delegated to JDOM's SAXOutputter.
421    *
422    * @see org.jdom.Document
423    * @see org.jdom.output.SAXOutputter
424    */

425   private static class DocumentReader extends SAXOutputter
426                                         implements XMLReader {
427     /**
428      * Public default constructor.
429      */

430     public DocumentReader() {
431       super();
432     }
433
434     //----------------------------------------------------------------------
435
// SAX XMLReader interface support
436
//----------------------------------------------------------------------
437

438     /**
439      * Parses an XML document from a system identifier (URI).
440      * <p>
441      * This implementation does not support reading XML data from
442      * system identifiers, only from JDOM documents. Hence,
443      * this method always throws a {@link SAXNotSupportedException}.
444      * </p>
445      *
446      * @param systemId the system identifier (URI).
447      *
448      * @throws SAXNotSupportedException always!
449      */

450     public void parse(String JavaDoc systemId) throws SAXNotSupportedException {
451       throw new SAXNotSupportedException(
452                        "Only JDOM Documents are supported as input");
453     }
454
455     /**
456      * Parses an XML document.
457      * <p>
458      * The methods accepts only <code>JDOMInputSource</code>s
459      * instances as input sources.
460      * </p>
461      *
462      * @param input the input source for the top-level of the
463      * XML document.
464      *
465      * @throws SAXException any SAX exception,
466      * possibly wrapping
467      * another exception.
468      * @throws SAXNotSupportedException if the input source does
469      * not wrap a JDOM document.
470      */

471     public void parse(InputSource input) throws SAXException {
472       if (input instanceof JDOMInputSource) {
473         try {
474           Object JavaDoc source = ((JDOMInputSource)input).getSource();
475           if (source instanceof Document) {
476             this.output((Document)source);
477           }
478           else {
479             this.output((List)source);
480           }
481         }
482         catch (JDOMException e) {
483           throw new SAXException(e.getMessage(), e);
484         }
485       }
486       else {
487         throw new SAXNotSupportedException(
488                          "Only JDOM Documents are supported as input");
489       }
490     }
491   }
492 }
493
494
Popular Tags