KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > utils > XmlUtils


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2003-2004 TONBELLER AG.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  *
11  *
12  */

13 package com.tonbeller.wcf.utils;
14
15 import java.io.File JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.io.Writer JavaDoc;
18 import java.net.MalformedURLException JavaDoc;
19 import java.net.URL JavaDoc;
20 import java.util.Hashtable JavaDoc;
21 import java.util.Properties JavaDoc;
22
23 import javax.servlet.ServletContext JavaDoc;
24 import javax.servlet.http.HttpSession JavaDoc;
25 import javax.xml.parsers.DocumentBuilder JavaDoc;
26 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
27 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
28 import javax.xml.parsers.ParserConfigurationException JavaDoc;
29 import javax.xml.transform.Result JavaDoc;
30 import javax.xml.transform.Source JavaDoc;
31 import javax.xml.transform.Templates JavaDoc;
32 import javax.xml.transform.Transformer JavaDoc;
33 import javax.xml.transform.TransformerConfigurationException JavaDoc;
34 import javax.xml.transform.TransformerException JavaDoc;
35 import javax.xml.transform.TransformerFactory JavaDoc;
36 import javax.xml.transform.TransformerFactoryConfigurationError JavaDoc;
37 import javax.xml.transform.dom.DOMSource JavaDoc;
38 import javax.xml.transform.stream.StreamResult JavaDoc;
39 import javax.xml.transform.stream.StreamSource JavaDoc;
40
41 import org.apache.log4j.Logger;
42 import org.w3c.dom.Document JavaDoc;
43 import org.w3c.dom.Node JavaDoc;
44 import org.xml.sax.InputSource JavaDoc;
45 import org.xml.sax.SAXException JavaDoc;
46
47 /**
48  * @author av
49  * XML Utilities
50  */

51 public class XmlUtils {
52
53   private static final String JavaDoc WEBKEY = XmlUtils.class.getName();
54   private static Logger logger = Logger.getLogger(XmlUtils.class);
55
56   private XmlUtils() {
57   }
58
59   /**
60    * Xalan Templates are not thread safe (as the spec requires),
61    * so we have one instance of the templatesCache for every
62    * http session.
63    */

64   private Hashtable JavaDoc templatesCache = new Hashtable JavaDoc();
65
66   /**
67    * creates a transformer for a xsl stylesheet
68    * @param xsltURI the uri of the xslt stylesheet, e.g. "/WEB-INF/mystyle.xsl"
69    * @param useCache cache the transformer
70    */

71   public Transformer JavaDoc getTransformer(ServletContext JavaDoc ctx, String JavaDoc xslUri, boolean xslCache) {
72     synchronized (templatesCache) {
73       try {
74         Templates JavaDoc templates = null;
75         if (xslCache)
76           templates = (Templates JavaDoc) templatesCache.get(xslUri);
77         if (templates == null) {
78           TransformerFactory JavaDoc tf = TransformerFactory.newInstance();
79           URL JavaDoc url = ctx.getResource(xslUri);
80           if (url == null)
81             throw new IllegalArgumentException JavaDoc("stylesheet \"" + xslUri + "\" not found");
82
83           StreamSource JavaDoc ss = new StreamSource JavaDoc(url.toExternalForm());
84           // BEA 8.1 needs SystemID to resolve includes
85
if ("file".equals(url.getProtocol())) {
86             File JavaDoc f = new File JavaDoc(url.getFile());
87             ss.setSystemId(f);
88           }
89           templates = tf.newTemplates(ss);
90           if (xslCache)
91             templatesCache.put(xslUri, templates);
92         }
93         return templates.newTransformer();
94       } catch (TransformerConfigurationException JavaDoc e) {
95         throw new SoftException(e);
96       } catch (MalformedURLException JavaDoc e) {
97         throw new SoftException(e);
98       }
99     }
100   }
101
102   /**
103    * creates a transformer for a xsl stylesheet
104    * @param context for resource lookup and stylesheet caching
105    * @param xsltURI the uri of the xslt stylesheet, e.g. "/WEB-INF/mystyle.xsl"
106    * @param useCache cache the transformer
107    */

108   public static Transformer JavaDoc getTransformer(HttpSession JavaDoc session, String JavaDoc xslUri, boolean xslCache) {
109     return instance(session).getTransformer(session.getServletContext(), xslUri, xslCache);
110   }
111
112   public static DocumentBuilder JavaDoc getParser() {
113     try {
114       DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
115       dbf.setValidating(false);
116       dbf.setExpandEntityReferences(true);
117       return dbf.newDocumentBuilder();
118     } catch (FactoryConfigurationError JavaDoc e) {
119       throw new SoftException(e);
120     } catch (ParserConfigurationException JavaDoc e) {
121       throw new SoftException(e);
122     }
123   }
124
125   public static Document JavaDoc createDocument() {
126     try {
127       return getParser().newDocument();
128     } catch (FactoryConfigurationError JavaDoc e) {
129       throw new SoftException(e);
130     }
131   }
132
133   public static void print(Node JavaDoc node, Writer JavaDoc out, Properties JavaDoc p) {
134     try {
135       TransformerFactory JavaDoc tf = TransformerFactory.newInstance();
136       Source JavaDoc src = new DOMSource JavaDoc(node);
137       Result JavaDoc dest = new StreamResult JavaDoc(out);
138       Transformer JavaDoc t = tf.newTransformer();
139       if (p != null)
140         t.setOutputProperties(p);
141       t.transform(src, dest);
142     } catch (TransformerConfigurationException JavaDoc e) {
143       throw new SoftException(e);
144     } catch (TransformerFactoryConfigurationError JavaDoc e) {
145       throw new SoftException(e);
146     } catch (TransformerException JavaDoc e) {
147       throw new SoftException(e);
148     }
149   }
150
151   public static void print(Node JavaDoc node, Writer JavaDoc out) {
152     print(node, out, null);
153   }
154
155   public static synchronized XmlUtils instance(HttpSession JavaDoc session) {
156     XmlUtils service = (XmlUtils) session.getAttribute(WEBKEY);
157     if (service == null) {
158       service = new XmlUtils();
159       session.setAttribute(WEBKEY, service);
160     }
161     return service;
162   }
163
164   /**
165    * returns the Document. node itself may be a Document node in which case
166    * node.getOwnerDocument() will return null
167    */

168   public static Document JavaDoc getDocument(Node JavaDoc node) {
169     if (node.getNodeType() == Node.DOCUMENT_NODE)
170       return (Document JavaDoc) node;
171     return node.getOwnerDocument();
172   }
173
174   public static Document JavaDoc parse(URL JavaDoc url) {
175     try {
176       InputSource JavaDoc src = new InputSource JavaDoc(url.toExternalForm());
177       return getParser().parse(src);
178     } catch (IOException JavaDoc e) {
179       throw new SoftException(e);
180     } catch (SAXException JavaDoc e) {
181       throw new SoftException(e);
182     }
183   }
184
185   /**
186    * escapes xml characters
187    * <, > &, "
188    */

189   public static String JavaDoc escapeXml(String JavaDoc s) {
190     if (s == null)
191       return null;
192     char[] arr = s.toCharArray();
193     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
194     for (int i = 0; i < arr.length; i++) {
195       switch(arr[i]) {
196       case '>':
197         sb.append("&gt;");
198         break;
199       case '<':
200         sb.append("&lt;");
201         break;
202       case '&':
203         sb.append("&amp;");
204         break;
205       case '"':
206         sb.append("&quot;");
207         break;
208       default:
209         sb.append(arr[i]);
210       }
211     }
212     return sb.toString();
213   }
214   
215
216 }
217
Popular Tags