KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdom > contrib > beans > JDOMBean


1 /*--
2
3  $Id: JDOMBean.java,v 1.4 2004/02/06 09:57:48 jhunter Exp $
4
5  Copyright (C) 2000-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.contrib.beans;
58
59 import java.io.File JavaDoc;
60 import java.io.IOException JavaDoc;
61 import java.io.PrintStream JavaDoc;
62 import java.util.Iterator JavaDoc;
63 import java.util.*;
64 import org.jdom.Document;
65 import org.jdom.Element;
66 import org.jdom.JDOMException;
67 import org.jdom.input.SAXBuilder;
68 import org.jdom.output.XMLOutputter;
69
70 // todo:
71
// weak references and/or timeout cache
72
// load from URL (instead of just from file)
73
// pathname normalization (remove ./ and foo/../ and so forth)
74
// allow DOM builder or arbitrary builder
75

76 /**
77  * A light wrapper on the JDOM library that you use to load in a file
78  * and turn it into a JDOM Document. It also keeps a cache of
79  * already-parsed files, and checks to see if they've changed on disk,
80  * and reloads if they have. (I know there's some sort of swap-out or
81  * weak-reference stuff either in JDOM or coming soon, so this may be
82  * a redundant feature.)
83  * <p>
84  *
85  * <h3>Usage from Java:</h3>
86  *
87  * <pre>
88  * JDOMBean jdom = new JDOMBean(); // or new JDOMBean("com.foo.saxparser")
89  * jdom.setFileRoot("/path/to/my/xml/documents/");
90  * Document doc = jdom.getDocument("foo.xml");
91  * Element root = jdom.getRootElement("foo.xml");
92  * </pre>
93  *
94  * <h3>Usage from JSP:</h3>
95  *
96  * <pre>
97  *
98  * &lt;jsp:useBean id="jdom" class="JDOMBean" scope="application"&gt;
99  * &lt;% jdom.setFileRoot(application.getRealPath("")); %&gt;
100  * &lt;/jsp:useBean&gt;
101  *
102  * or
103  *
104  * &lt;jsp:useBean id="jdom" class="JDOMBean" scope="application"&gt;
105  * &lt;jsp:setProperty name="jdom" property="fileRoot"
106  * +value='&lt;%=application.getRealPath("")%&gt;' /&gt;
107  * &lt;/jsp:useBean&gt;
108  *
109  * then
110  *
111  * &lt;%
112  * Element root = jdom.getRootElement("foo.xml");
113  * %&gt;
114  * Bar: &lt;%=root.getChild("bar").getContent()%&gt;
115  * </pre>
116  *
117  * @author Alex Chaffee [alex@jguru.com]
118  **/

119 public class JDOMBean {
120
121     /** Default SAX parser class to use */
122     private static final String JavaDoc DEFAULT_PARSER =
123         "org.apache.xerces.parsers.SAXParser";
124
125     /** SAX parser class to use */
126     private String JavaDoc parser;
127
128     /** <code>{@link SAXBuilder}</code> instance to use */
129     private SAXBuilder builder;
130     
131     /** file cache **/
132     private Map files = new HashMap();
133
134     /** where to locate files **/
135     private File JavaDoc fileRoot;
136
137     /**
138      * default constructor, uses "org.apache.xerces.parsers.SAXParser"
139      **/

140     public JDOMBean() {
141         setParser(DEFAULT_PARSER);
142     }
143
144     /**
145      * @param parser <code>String</code> name of driver class to use.
146      **/

147     public JDOMBean(String JavaDoc parser) {
148         setParser(parser);
149     }
150     
151     /**
152      * <p>
153      * This will create an instance of <code>{@link SAXBuilder}</code>
154      * for use in the rest of this program.
155      * </p>
156      *
157      * @param parser <code>String</code> name of SAX parser class to use.
158      */

159     public void setParser(String JavaDoc parser) {
160         this.parser = parser;
161         builder = new SAXBuilder(parser);
162     }
163
164     /**
165      * @return name of SAX parser class being used
166      **/

167     public String JavaDoc getParser() {
168         return parser;
169     }
170
171     /**
172      * All files are fetched relative to this path
173      * @param root the path (absolute or relative) to the document root
174      **/

175     public void setFileRoot(String JavaDoc root) {
176         if (!root.endsWith("/")) {
177             root = root + "/";
178         }
179         this.fileRoot = new File JavaDoc(root);
180         System.out.println("fileroot=" + fileRoot);
181     }
182
183     /**
184      * @return the path (absolute or relative) to the document root
185      **/

186     public String JavaDoc getFileRoot() {
187         if (fileRoot == null) return null;
188         else return fileRoot.getAbsolutePath();
189     }
190     
191     /**
192      * Load a file, parse it with JDOM, return a org.jdom.Document.
193      * If the file has already been parsed, return the previously
194      * cached object. If the file has changed, ignore the previously
195      * parsed version and reload. <p>
196      *
197      * Note that this never unloads a document, so is unsuitable for
198      * long-term server-side use for a constantly changing set of
199      * files. Todo: use weak references or cache timeouts. <p>
200      *
201      * Also does not do secure checking on file requested, so if
202      * there's no root, and the parameter starts with a "/", this
203      * could conceivably access files you don't want accessed. So be
204      * careful out there.
205      *
206      * @param filename the file to load, relative to file root
207      * @return a JDOM Document corresponding to the given filename
208      **/

209     public Document getDocument(String JavaDoc filename) throws JDOMException, IOException JavaDoc {
210         FileInfo info = (FileInfo) files.get(filename);
211         File JavaDoc file = getFile(filename);
212         if (info == null ||
213             info.modified < file.lastModified())
214         {
215             Document doc = builder.build(file);
216             info = new FileInfo(filename, file.lastModified(), doc);
217             files.put(filename, info);
218         }
219         return info.document;
220     }
221
222     /**
223      * Convenience method, calls getDocument(filename).getRootElement()
224      **/

225     public Element getRootElement(String JavaDoc file) throws JDOMException, IOException JavaDoc {
226         Document doc = getDocument(file);
227         if (doc != null) return doc.getRootElement();
228         return null;
229     }
230
231     private File JavaDoc getFile(String JavaDoc filename) {
232         File JavaDoc file;
233         if (fileRoot == null) {
234             return new File JavaDoc(filename);
235         }
236         else {
237             return new File JavaDoc(fileRoot, filename);
238         }
239     }
240     
241     /**
242      * Information stored in the cache
243      **/

244     class FileInfo {
245         String JavaDoc name;
246         long modified;
247         Document document;
248         public FileInfo(String JavaDoc name, long modified, Document document) {
249             this.name = name;
250             this.modified = modified;
251             this.document = document;
252         }
253     }
254
255     // Usage: java JDOMBean [-parser com.foo.parser] file1.xml file2.xml
256
// Fetches and prints files
257
public static void main(String JavaDoc[] args) throws IOException JavaDoc, JDOMException {
258         int i=0;
259         JDOMBean bean;
260         if (args[i].equals("-parser")) {
261             ++i;
262             bean = new JDOMBean(args[i]);
263             i++;
264         }
265         else {
266             bean = new JDOMBean();
267         }
268
269         XMLOutputter out = new XMLOutputter();
270                 
271         for (; i<args.length; ++i) {
272             Document doc = bean.getDocument(args[i]);
273             out.output(doc, System.out);
274             System.out.println();
275         }
276     }
277     
278 }
279
280
Popular Tags