source: greenstone3/trunk/src/java/org/greenstone/gsdl3/util/XMLTransformer.java@ 17024

Last change on this file since 17024 was 17024, checked in by max, 16 years ago

When something goes wrong, send a document containing the error message in HTML instead of a null document.

  • Property svn:keywords set to Author Date Id Revision
File size: 8.7 KB
Line 
1/*
2 * XMLTransformer.java
3 * Copyright (C) 2002 New Zealand Digital Library, http://www.nzdl.org
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19package org.greenstone.gsdl3.util;
20
21// XML classes
22import javax.xml.transform.Transformer;
23import javax.xml.transform.TransformerFactory;
24import javax.xml.transform.TransformerConfigurationException;
25import javax.xml.transform.TransformerException;
26
27import javax.xml.transform.stream.StreamSource;
28import javax.xml.transform.dom.DOMSource;
29import javax.xml.transform.stream.StreamResult;
30import javax.xml.transform.dom.DOMResult;
31
32import javax.xml.parsers.DocumentBuilderFactory;
33import javax.xml.parsers.DocumentBuilder;
34import org.w3c.dom.Element;
35import org.w3c.dom.Document;
36
37import org.w3c.dom.Node;
38import org.w3c.dom.NodeList;
39
40// other java classes
41import java.io.StringReader;
42import java.io.StringWriter;
43import java.io.File;
44import java.util.HashMap;
45import java.util.Set;
46import java.util.Map;
47import java.util.Iterator;
48
49import org.apache.xml.utils.DefaultErrorHandler;
50
51import org.apache.log4j.*;
52
53/** XMLTransformer - utility class for greenstone
54 *
55 * transforms xml using xslt
56 *
57 * @author <a href="mailto:[email protected]">Katherine Don</a>
58 * @version $Revision: 17024 $
59 */
60public class XMLTransformer {
61
62 static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.XMLTransformer.class.getName());
63
64 /** The transformer factory we're using */
65 TransformerFactory t_factory=null;
66
67 /**
68 * The no-arguments constructor.
69 *
70 * Any exceptions thrown are caught internally
71 *
72 * @see javax.xml.transform.TransformerFactory
73 */
74 public XMLTransformer() {
75
76 // make sure we are using the xalan transformer
77 System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");
78 try {
79 this.t_factory = org.apache.xalan.processor.TransformerFactoryImpl.newInstance();
80
81 } catch (Exception e) {
82 logger.error("exception "+e.getMessage());
83 }
84 }
85
86
87
88 /**
89 * Transform an XML document using a XSLT stylesheet
90 *
91 * @param stylesheet a filename for an XSLT stylesheet
92 * @param xml_in the XML to be transformed
93 * @return the transformed XML
94 */
95 public String transform(String stylesheet, String xml_in) {
96
97 try {
98 // Use the TransformerFactory to process the stylesheet Source and generate a Transformer.
99 Transformer transformer = this.t_factory.newTransformer(new StreamSource(stylesheet));
100
101 // Use the Transformer to transform an XML Source and send the output to a Result object.
102 StringWriter output = new StringWriter();
103
104 transformer.transform(new StreamSource(new StringReader(xml_in)), new StreamResult(output));
105 return output.toString();
106 } catch (TransformerConfigurationException e) {
107 logger.error("couldn't create transformer object: "+e.getMessageAndLocation());
108 logger.error(e.getLocationAsString());
109 return "";
110 } catch (TransformerException e) {
111 logger.error("couldn't transform the source: " + e.getMessage());
112 return "";
113 }
114 }
115
116 public String transformToString(Document stylesheet, Document source) {
117 return transformToString(stylesheet, source, null);
118 }
119
120 public String transformToString(Document stylesheet, Document source, HashMap parameters) {
121
122 try {
123 // Use the TransformerFactory to process the stylesheet Source and generate a Transformer.
124 Transformer transformer = this.t_factory.newTransformer(new DOMSource(stylesheet));
125 if (parameters != null) {
126 Set params = parameters.entrySet();
127 Iterator i = params.iterator();
128 while (i.hasNext()) {
129 Map.Entry m = (Map.Entry)i.next();
130 transformer.setParameter((String)m.getKey(), m.getValue());
131 }
132 }
133 //transformer.setParameter("page_lang", source.getDocumentElement().getAttribute(GSXML.LANG_ATT));
134
135
136 // Use the Transformer to transform an XML Source and send the output to a Result object.
137 StringWriter output = new StringWriter();
138
139 transformer.transform(new DOMSource(source), new StreamResult(output));
140 return output.toString();
141 } catch (TransformerConfigurationException e) {
142 logger.error("couldn't create transformer object: "+e.getMessageAndLocation());
143 logger.error(e.getLocationAsString());
144 return "";
145 } catch (TransformerException e) {
146 logger.error("couldn't transform the source: " + e.getMessage());
147 return "";
148 }
149 }
150
151 public Node transform(Document stylesheet, Document source) {
152 return transform(stylesheet, source, null);
153 }
154
155 public Node transform(Document stylesheet, Document source, HashMap parameters) {
156
157 try {
158 // Use the TransformerFactory to process the stylesheet Source and generate a Transformer.
159 Transformer transformer = this.t_factory.newTransformer(new DOMSource(stylesheet));
160
161 if (parameters != null) {
162 Set params = parameters.entrySet();
163 Iterator i = params.iterator();
164 while (i.hasNext()) {
165 Map.Entry m = (Map.Entry)i.next();
166 transformer.setParameter((String)m.getKey(), m.getValue());
167 }
168 }
169
170 DOMResult result = new DOMResult();
171 transformer.transform(new DOMSource(source), result);
172 return result.getNode().getFirstChild();
173 } catch (TransformerConfigurationException e) {
174 String message = "TransformerConfigurationException: "+e.getMessageAndLocation();
175 //System.err.println(message);
176 logger.error("couldn't create transformer object: "+e.getMessageAndLocation());
177 logger.error(e.getLocationAsString());
178 return constructErrorXHTMLPage(message);
179 } catch (TransformerException e) {
180 String message = "TransformerException: " + e.getMessageAndLocation();
181 //System.err.println(message);
182 logger.error("couldn't transform the source: " + e.getMessage());
183 return constructErrorXHTMLPage(message);
184 }
185
186
187 }
188
189
190
191 public Node transform(File stylesheet, File source) {
192
193 try {
194 Transformer transformer = this.t_factory.newTransformer(new StreamSource(stylesheet));
195
196 DOMResult result = new DOMResult();
197 transformer.transform(new StreamSource(source), result);
198 return result.getNode().getFirstChild();
199 } catch (TransformerConfigurationException e) {
200 logger.error("couldn't create transformer object: "+e.getMessageAndLocation());
201 logger.error(e.getLocationAsString());
202 String message = "TransformerConfigurationException: "+e.getMessageAndLocation();
203 return constructErrorXHTMLPage(message);
204 } catch (TransformerException e) {
205 logger.error("couldn't transform the source: " + e.getMessage());
206 String message = "TransformerException: " + e.getMessageAndLocation();
207 return constructErrorXHTMLPage(message);
208 }
209 }
210
211
212 protected Element constructErrorXHTMLPage(String message) {
213 try{
214 Document xhtmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
215 // <html></html>
216 Node htmlNode = xhtmlDoc.createElement("html");
217 xhtmlDoc.appendChild(htmlNode);
218 // <head></head>
219 Node headNode = xhtmlDoc.createElement("head");
220 htmlNode.appendChild(headNode);
221 // <title></title>
222 Node titleNode = xhtmlDoc.createElement("title");
223 headNode.appendChild(titleNode);
224 Node titleString = xhtmlDoc.createTextNode("Error occurred");
225 titleNode.appendChild(titleString);
226
227 // <body></body>
228 Node bodyNode = xhtmlDoc.createElement("body");
229 htmlNode.appendChild(bodyNode);
230
231 // finally put the message in the body
232 Node h1Node = xhtmlDoc.createElement("h1");
233 bodyNode.appendChild(h1Node);
234 Node headingString = xhtmlDoc.createTextNode("The following error occurred:");
235 h1Node.appendChild(headingString);
236
237 Node textNode = xhtmlDoc.createTextNode(message);
238 bodyNode.appendChild(textNode);
239
240 return xhtmlDoc.getDocumentElement();
241
242 }catch(Exception e) {
243 String errmsg = "Exception trying to construct error xhtml page from message: " + message
244 + "\n" + e.getMessage();
245 System.err.println(errmsg);
246 logger.error(errmsg);
247 return null;
248 }
249 }
250
251}
252
253
Note: See TracBrowser for help on using the repository browser.