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 | */
|
---|
19 | package org.greenstone.gsdl3.util;
|
---|
20 |
|
---|
21 | import java.io.BufferedReader;
|
---|
22 | import java.io.File;
|
---|
23 | import java.io.FileInputStream;
|
---|
24 | import java.io.FileNotFoundException;
|
---|
25 | import java.io.FileWriter;
|
---|
26 | import java.io.InputStreamReader;
|
---|
27 | import java.io.StringReader;
|
---|
28 | import java.io.StringWriter;
|
---|
29 | import java.io.UnsupportedEncodingException;
|
---|
30 | import java.util.HashMap;
|
---|
31 | import java.util.Iterator;
|
---|
32 | import java.util.Map;
|
---|
33 | import java.util.Set;
|
---|
34 |
|
---|
35 | import javax.xml.parsers.DocumentBuilderFactory;
|
---|
36 | import javax.xml.transform.ErrorListener;
|
---|
37 | import javax.xml.transform.Source;
|
---|
38 | import javax.xml.transform.Transformer;
|
---|
39 | import javax.xml.transform.TransformerConfigurationException;
|
---|
40 | import javax.xml.transform.TransformerException;
|
---|
41 | import javax.xml.transform.TransformerFactory;
|
---|
42 | import javax.xml.transform.dom.DOMResult;
|
---|
43 | import javax.xml.transform.dom.DOMSource;
|
---|
44 | import javax.xml.transform.stream.StreamResult;
|
---|
45 | import javax.xml.transform.stream.StreamSource;
|
---|
46 |
|
---|
47 | import org.apache.log4j.Logger;
|
---|
48 | import org.greenstone.util.GlobalProperties;
|
---|
49 | import org.w3c.dom.Document;
|
---|
50 | import org.w3c.dom.Element;
|
---|
51 | import org.w3c.dom.Node;
|
---|
52 |
|
---|
53 | /**
|
---|
54 | * XMLTransformer - utility class for greenstone
|
---|
55 | *
|
---|
56 | * transforms xml using xslt
|
---|
57 | *
|
---|
58 | * @author Katherine Don
|
---|
59 | * @version $Revision: 26457 $
|
---|
60 | */
|
---|
61 | public class XMLTransformer
|
---|
62 | {
|
---|
63 | private static int debugFileCount = 0; // for unique filenames when debugging XML transformations with physical files
|
---|
64 |
|
---|
65 | static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.XMLTransformer.class.getName());
|
---|
66 |
|
---|
67 | /** The transformer factory we're using */
|
---|
68 | TransformerFactory t_factory = null;
|
---|
69 |
|
---|
70 | /**
|
---|
71 | * The no-arguments constructor.
|
---|
72 | *
|
---|
73 | * Any exceptions thrown are caught internally
|
---|
74 | *
|
---|
75 | * @see javax.xml.transform.TransformerFactory
|
---|
76 | */
|
---|
77 | public XMLTransformer()
|
---|
78 | {
|
---|
79 | // http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/index.html?javax/xml/transform/TransformerFactory.html states that
|
---|
80 | // TransformerFactory.newInstance() looks in jar files for a Factory specified in META-INF/services/javax.xml.transform.TransformerFactory,
|
---|
81 | // else it will use the "platform default"
|
---|
82 | // In this case: xalan.jar's META-INF/services/javax.xml.transform.TransformerFactory contains org.apache.xalan.processor.TransformerFactoryImpl
|
---|
83 | // as required.
|
---|
84 |
|
---|
85 | // This means we no longer have to do a System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");
|
---|
86 | // followed by a this.t_factory = org.apache.xalan.processor.TransformerFactoryImpl.newInstance();
|
---|
87 | // The System.setProperty step to force the TransformerFactory implementation that gets used, conflicts with
|
---|
88 | // Fedora (visiting the Greenstone server pages breaks the Greenstone-tomcat hosted Fedora pages) as Fedora
|
---|
89 | // does not include the xalan.jar and therefore can't then find the xalan TransformerFactory explicitly set.
|
---|
90 |
|
---|
91 | // Gone back to forcing use of xalan transformer, since other jars like crimson.jar, which may be on some
|
---|
92 | // classpaths, could be be chosen as the TransformerFactory implementation over xalan. This is what used to
|
---|
93 | // give problems before. Instead, have placed copies of the jars that Fedora needs (xalan.jar and serializer.jar
|
---|
94 | // and the related xsltc.jar which it may need) into packages/tomcat/lib so that it's on the server's classpath
|
---|
95 | // and will be found by Fedora.
|
---|
96 |
|
---|
97 | // make sure we are using the xalan transformer
|
---|
98 | System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");
|
---|
99 | try
|
---|
100 | {
|
---|
101 | this.t_factory = org.apache.xalan.processor.TransformerFactoryImpl.newInstance();
|
---|
102 | //this.t_factory = TransformerFactory.newInstance();
|
---|
103 | this.t_factory.setErrorListener(new TransformErrorListener()); // handle errors in the xml Source used to instantiate transformers
|
---|
104 | }
|
---|
105 | catch (Exception e)
|
---|
106 | {
|
---|
107 | logger.error("exception creating t_factory " + e.getMessage());
|
---|
108 | }
|
---|
109 | }
|
---|
110 |
|
---|
111 | /**
|
---|
112 | * Transform an XML document using a XSLT stylesheet
|
---|
113 | *
|
---|
114 | * @param stylesheet
|
---|
115 | * a filename for an XSLT stylesheet
|
---|
116 | * @param xml_in
|
---|
117 | * the XML to be transformed
|
---|
118 | * @return the transformed XML
|
---|
119 | */
|
---|
120 | public String transform(String stylesheet, String xml_in)
|
---|
121 | {
|
---|
122 |
|
---|
123 | try
|
---|
124 | {
|
---|
125 | TransformErrorListener transformerErrorListener = (TransformErrorListener) this.t_factory.getErrorListener();
|
---|
126 | transformerErrorListener.setStylesheet(stylesheet);
|
---|
127 | // Use the TransformerFactory to process the stylesheet Source and generate a Transformer.
|
---|
128 | Transformer transformer = this.t_factory.newTransformer(new StreamSource(stylesheet));
|
---|
129 |
|
---|
130 | // Use the Transformer to transform an XML Source and send the output to a Result object.
|
---|
131 | StringWriter output = new StringWriter();
|
---|
132 | StreamSource streamSource = new StreamSource(new StringReader(xml_in));
|
---|
133 | transformer.setErrorListener(new TransformErrorListener(stylesheet, streamSource));
|
---|
134 | transformer.transform(streamSource, new StreamResult(output));
|
---|
135 | return output.toString();
|
---|
136 | }
|
---|
137 | catch (TransformerConfigurationException e)
|
---|
138 | {
|
---|
139 | logger.error("couldn't create transformer object: " + e.getMessageAndLocation());
|
---|
140 | logger.error(e.getLocationAsString());
|
---|
141 | return "";
|
---|
142 | }
|
---|
143 | catch (TransformerException e)
|
---|
144 | {
|
---|
145 | logger.error("couldn't transform the source: " + e.getMessageAndLocation());
|
---|
146 | return "";
|
---|
147 | }
|
---|
148 | }
|
---|
149 |
|
---|
150 | public String transformToString(Document stylesheet, Document source)
|
---|
151 | {
|
---|
152 | return transformToString(stylesheet, source, null);
|
---|
153 | }
|
---|
154 |
|
---|
155 | public String transformToString(Document stylesheet, Document source, HashMap parameters)
|
---|
156 | {
|
---|
157 |
|
---|
158 | try
|
---|
159 | {
|
---|
160 | TransformErrorListener transformerErrorListener = (TransformErrorListener) this.t_factory.getErrorListener();
|
---|
161 | transformerErrorListener.setStylesheet(stylesheet);
|
---|
162 | // Use the TransformerFactory to process the stylesheet Source and generate a Transformer.
|
---|
163 | Transformer transformer = this.t_factory.newTransformer(new DOMSource(stylesheet));
|
---|
164 | if (parameters != null)
|
---|
165 | {
|
---|
166 | Set params = parameters.entrySet();
|
---|
167 | Iterator i = params.iterator();
|
---|
168 | while (i.hasNext())
|
---|
169 | {
|
---|
170 | Map.Entry m = (Map.Entry) i.next();
|
---|
171 | transformer.setParameter((String) m.getKey(), m.getValue());
|
---|
172 | }
|
---|
173 | }
|
---|
174 | //transformer.setParameter("page_lang", source.getDocumentElement().getAttribute(GSXML.LANG_ATT));
|
---|
175 |
|
---|
176 | // Use the Transformer to transform an XML Source and send the output to a Result object.
|
---|
177 | StringWriter output = new StringWriter();
|
---|
178 | DOMSource domSource = new DOMSource(source);
|
---|
179 |
|
---|
180 | transformer.setErrorListener(new TransformErrorListener(stylesheet, domSource));
|
---|
181 | transformer.transform(domSource, new StreamResult(output));
|
---|
182 | return output.toString();
|
---|
183 | }
|
---|
184 | catch (TransformerConfigurationException e)
|
---|
185 | {
|
---|
186 | logger.error("couldn't create transformer object: " + e.getMessageAndLocation());
|
---|
187 | logger.error(e.getLocationAsString());
|
---|
188 | return "";
|
---|
189 | }
|
---|
190 | catch (TransformerException e)
|
---|
191 | {
|
---|
192 | logger.error("couldn't transform the source: " + e.getMessageAndLocation());
|
---|
193 | return "";
|
---|
194 | }
|
---|
195 | }
|
---|
196 |
|
---|
197 | /**
|
---|
198 | * Transform an XML document using a XSLT stylesheet, but using a DOMResult
|
---|
199 | * whose node should be set to the Document donated by resultNode
|
---|
200 | */
|
---|
201 | public Node transform_withResultNode(Document stylesheet, Document source, Document resultNode)
|
---|
202 | {
|
---|
203 | return transform(stylesheet, source, null, null, resultNode);
|
---|
204 | }
|
---|
205 |
|
---|
206 | public Node transform(Document stylesheet, Document source)
|
---|
207 | {
|
---|
208 | return transform(stylesheet, source, null, null, null);
|
---|
209 | }
|
---|
210 |
|
---|
211 | public Node transform(Document stylesheet, Document source, HashMap<String, Comparable> parameters)
|
---|
212 | {
|
---|
213 | return transform(stylesheet, source, parameters, null, null);
|
---|
214 | }
|
---|
215 |
|
---|
216 | public Node transform(Document stylesheet, Document source, HashMap<String, Comparable> parameters, Document docDocType)
|
---|
217 | {
|
---|
218 | return transform(stylesheet, source, parameters, docDocType, null);
|
---|
219 | }
|
---|
220 |
|
---|
221 | protected Node transform(Document stylesheet, Document source, HashMap<String, Comparable> parameters, Document docDocType, Document resultNode)
|
---|
222 | {
|
---|
223 | try
|
---|
224 | {
|
---|
225 | // Use the TransformerFactory to process the stylesheet Source and generate a Transformer.
|
---|
226 | TransformErrorListener transformerErrorListener = (TransformErrorListener) this.t_factory.getErrorListener();
|
---|
227 | transformerErrorListener.setStylesheet(stylesheet);
|
---|
228 | Transformer transformer = this.t_factory.newTransformer(new DOMSource(stylesheet));
|
---|
229 | //logger.info("XMLTransformer transformer is " + transformer); //done in ErrorListener
|
---|
230 |
|
---|
231 | if (parameters != null)
|
---|
232 | {
|
---|
233 | Set params = parameters.entrySet();
|
---|
234 | Iterator i = params.iterator();
|
---|
235 | while (i.hasNext())
|
---|
236 | {
|
---|
237 | Map.Entry m = (Map.Entry) i.next();
|
---|
238 | transformer.setParameter((String) m.getKey(), m.getValue());
|
---|
239 | }
|
---|
240 | }
|
---|
241 |
|
---|
242 | // When we transform the DOMResult, we need to make sure the result of
|
---|
243 | // the transformation has a DocType. For that to happen, we need to create
|
---|
244 | // the DOMResult using a Document with a predefined docType.
|
---|
245 | // If we don't have a DocType then do the transformation with a DOMResult
|
---|
246 | // that does not contain any doctype (like we use to do before).
|
---|
247 | DOMResult result = docDocType == null ? new DOMResult() : new DOMResult(docDocType);
|
---|
248 | if (resultNode != null)
|
---|
249 | {
|
---|
250 | result.setNode(resultNode);
|
---|
251 | }
|
---|
252 | DOMSource domSource = new DOMSource(source);
|
---|
253 | transformer.setErrorListener(new TransformErrorListener(stylesheet, domSource));
|
---|
254 | transformer.transform(domSource, result);
|
---|
255 | return result.getNode(); // pass the entire document
|
---|
256 | }
|
---|
257 | catch (TransformerConfigurationException e)
|
---|
258 | {
|
---|
259 | return transformError("XMLTransformer.transform(Doc, Doc, HashMap, Doc)" + "\ncouldn't create transformer object", e);
|
---|
260 | }
|
---|
261 | catch (TransformerException e)
|
---|
262 | {
|
---|
263 | return transformError("XMLTransformer.transform(Doc, Doc, HashMap, Doc)" + "\ncouldn't transform the source", e);
|
---|
264 | }
|
---|
265 | }
|
---|
266 |
|
---|
267 | public Node transform(File stylesheet, File source)
|
---|
268 | {
|
---|
269 | return transform(stylesheet, source, null);
|
---|
270 | }
|
---|
271 |
|
---|
272 | // debugAsFile is only to be set to true when either the stylesheet or source parameters
|
---|
273 | // are not objects of type File. The debugAsFile variable is passed into the
|
---|
274 | // TransformErrorListener. When set to true, the TransformErrorListener will itself create
|
---|
275 | // two files containing the stylesheet and source XML, and try to transform the new source
|
---|
276 | // file with the stylesheet file for debugging purposes.
|
---|
277 | protected Node transform(File stylesheet, File source, Document docDocType)
|
---|
278 | {
|
---|
279 | try
|
---|
280 | {
|
---|
281 | TransformErrorListener transformerErrorListener = (TransformErrorListener) this.t_factory.getErrorListener();
|
---|
282 | transformerErrorListener.setStylesheet(stylesheet);
|
---|
283 | Transformer transformer = this.t_factory.newTransformer(new StreamSource(new InputStreamReader(new FileInputStream(stylesheet), "UTF-8")));
|
---|
284 | DOMResult result = (docDocType == null) ? new DOMResult() : new DOMResult(docDocType);
|
---|
285 | StreamSource streamSource = new StreamSource(new InputStreamReader(new FileInputStream(source), "UTF-8"));
|
---|
286 |
|
---|
287 | transformer.setErrorListener(new TransformErrorListener(stylesheet, streamSource));
|
---|
288 |
|
---|
289 | transformer.transform(streamSource, result);
|
---|
290 | return result.getNode().getFirstChild();
|
---|
291 | }
|
---|
292 | catch (TransformerConfigurationException e)
|
---|
293 | {
|
---|
294 | return transformError("XMLTransformer.transform(File, File)" + "\ncouldn't create transformer object for files\n" + stylesheet + "\n" + source, e);
|
---|
295 | }
|
---|
296 | catch (TransformerException e)
|
---|
297 | {
|
---|
298 | return transformError("XMLTransformer.transform(File, File)" + "\ncouldn't transform the source for files\n" + stylesheet + "\n" + source, e);
|
---|
299 | }
|
---|
300 | catch (UnsupportedEncodingException e)
|
---|
301 | {
|
---|
302 | return transformError("XMLTransformer.transform(File, File)" + "\ncouldn't read file due to an unsupported encoding\n" + stylesheet + "\n" + source, e);
|
---|
303 | }
|
---|
304 | catch (FileNotFoundException e)
|
---|
305 | {
|
---|
306 | return transformError("XMLTransformer.transform(File, File)" + "\ncouldn't find the file specified\n" + stylesheet + "\n" + source, e);
|
---|
307 | }
|
---|
308 | }
|
---|
309 |
|
---|
310 | // Given a heading string on the sort of transformation error that occurred and the exception object itself,
|
---|
311 | // this method prints the exception to the tomcat window (system.err) and the greenstone log and then returns
|
---|
312 | // an xhtml error page that is constructed from it.
|
---|
313 | protected Node transformError(String heading, Exception e)
|
---|
314 | {
|
---|
315 | String message = heading + "\n" + e.getMessage();
|
---|
316 | logger.error(heading + ": " + e.getMessage());
|
---|
317 |
|
---|
318 | if (e instanceof TransformerException)
|
---|
319 | {
|
---|
320 | String location = ((TransformerException) e).getLocationAsString();
|
---|
321 | if (location != null)
|
---|
322 | {
|
---|
323 | logger.error(location);
|
---|
324 | message = message + "\n" + location;
|
---|
325 | }
|
---|
326 | }
|
---|
327 | System.err.println("****\n" + message + "\n****");
|
---|
328 | return constructErrorXHTMLPage(message);
|
---|
329 | }
|
---|
330 |
|
---|
331 | // Given an error message, splits it into separate lines based on any newlines present and generates an xhtml page
|
---|
332 | // (xml Element) with paragraphs for each line. This is then returned so that it can be displayed in the browser.
|
---|
333 | public static Element constructErrorXHTMLPage(String message)
|
---|
334 | {
|
---|
335 | try
|
---|
336 | {
|
---|
337 | String[] lines = message.split("\n");
|
---|
338 |
|
---|
339 | Document xhtmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
|
---|
340 | // <html></html>
|
---|
341 | Node htmlNode = xhtmlDoc.createElement("html");
|
---|
342 | xhtmlDoc.appendChild(htmlNode);
|
---|
343 | // <head></head>
|
---|
344 | Node headNode = xhtmlDoc.createElement("head");
|
---|
345 | htmlNode.appendChild(headNode);
|
---|
346 | // <title></title>
|
---|
347 | Node titleNode = xhtmlDoc.createElement("title");
|
---|
348 | headNode.appendChild(titleNode);
|
---|
349 | Node titleString = xhtmlDoc.createTextNode("Error occurred");
|
---|
350 | titleNode.appendChild(titleString);
|
---|
351 |
|
---|
352 | // <body></body>
|
---|
353 | Node bodyNode = xhtmlDoc.createElement("body");
|
---|
354 | htmlNode.appendChild(bodyNode);
|
---|
355 |
|
---|
356 | // finally put the message in the body
|
---|
357 | Node h1Node = xhtmlDoc.createElement("h1");
|
---|
358 | bodyNode.appendChild(h1Node);
|
---|
359 | Node headingString = xhtmlDoc.createTextNode("The following error occurred:");
|
---|
360 | h1Node.appendChild(headingString);
|
---|
361 |
|
---|
362 | //Node textNode = xhtmlDoc.createTextNode(message);
|
---|
363 | //bodyNode.appendChild(textNode);
|
---|
364 |
|
---|
365 | for (int i = 0; i < lines.length; i++)
|
---|
366 | {
|
---|
367 | Node pNode = xhtmlDoc.createElement("p");
|
---|
368 | Node textNode = xhtmlDoc.createTextNode(lines[i]);
|
---|
369 | pNode.appendChild(textNode);
|
---|
370 | bodyNode.appendChild(pNode);
|
---|
371 | }
|
---|
372 |
|
---|
373 | return xhtmlDoc.getDocumentElement();
|
---|
374 |
|
---|
375 | }
|
---|
376 | catch (Exception e)
|
---|
377 | {
|
---|
378 | String errmsg = "Exception trying to construct error xhtml page from message: " + message + "\n" + e.getMessage();
|
---|
379 | System.err.println(errmsg);
|
---|
380 | logger.error(errmsg);
|
---|
381 | return null;
|
---|
382 | }
|
---|
383 | }
|
---|
384 |
|
---|
385 | // ErrorListener class for both Transformer objects and TransformerFactory objects.
|
---|
386 | // This class can be used to register a handler for any fatal errors, errors and warnings that
|
---|
387 | // may occur when either transforming an xml file with an xslt stylesheet using the XMLTransformer,
|
---|
388 | // or when instantiating a Transformer object using the XMLTransformer's TransformerFactory member var.
|
---|
389 | // The latter case occurs when the xml Source used to instantiate a Transformer from a TransformerFactory
|
---|
390 | // is invalid in some manner, which results in a null Transformer object. However, as no
|
---|
391 | // TransformerConfigurationException or TransformerException are thrown in this case, the errors
|
---|
392 | // would have not been noticed until things go wrong later when trying to use the (null) Transformer.
|
---|
393 | //
|
---|
394 | // The errors caught by this ErrorListener class are printed both to the greenstone.log and to the
|
---|
395 | // tomcat console (System.err), and the error message is stored in the errorMessage variable so that
|
---|
396 | // it can be retrieved and be used to generate an xhtml error page.
|
---|
397 | public class TransformErrorListener implements ErrorListener
|
---|
398 | {
|
---|
399 | protected String errorMessage = null;
|
---|
400 | protected String stylesheet = null;
|
---|
401 | protected Source source = null; // can be DOMSource or StreamSource
|
---|
402 | protected boolean debugAsFile = true; // true if xslt or source are not real physical files
|
---|
403 |
|
---|
404 | // *********** METHODS TO BE CALLED WHEN SETTING AN ERROR LISTENER ON TRANSFORMERFACTORY OBJECTS
|
---|
405 | // The default constructor is only for when setting an ErrorListener on TransformerFactory objects
|
---|
406 | public TransformErrorListener()
|
---|
407 | {
|
---|
408 | this.stylesheet = null;
|
---|
409 | this.source = null;
|
---|
410 | XMLTransformer.debugFileCount++;
|
---|
411 | }
|
---|
412 |
|
---|
413 | public void setStylesheet(Document xslt)
|
---|
414 | {
|
---|
415 | this.debugAsFile = true;
|
---|
416 | this.stylesheet = GSXML.elementToString(xslt.getDocumentElement(), true);
|
---|
417 | this.source = null;
|
---|
418 | }
|
---|
419 |
|
---|
420 | public void setStylesheet(String xslt)
|
---|
421 | {
|
---|
422 | this.debugAsFile = true;
|
---|
423 | this.stylesheet = xslt;
|
---|
424 | this.source = null;
|
---|
425 | }
|
---|
426 |
|
---|
427 | public void setStylesheet(File xslt)
|
---|
428 | {
|
---|
429 | this.debugAsFile = false; // if this constructor is called, we're dealing with physical files for both xslt and source
|
---|
430 | this.stylesheet = xslt.getAbsolutePath();
|
---|
431 | this.source = null;
|
---|
432 | }
|
---|
433 |
|
---|
434 | // *********** METHODS TO BE CALLED WHEN SETTING AN ERROR LISTENER ON TRANSFORMERFACTORY OBJECTS
|
---|
435 | // When setting an ErrorListener on Transformer object, the ErrorListener takes a Stylesheet xslt and a Source
|
---|
436 | public TransformErrorListener(String xslt, Source source)
|
---|
437 | {
|
---|
438 | this.stylesheet = xslt;
|
---|
439 | this.source = source;
|
---|
440 | XMLTransformer.debugFileCount++;
|
---|
441 | }
|
---|
442 |
|
---|
443 | public TransformErrorListener(Document xslt, Source source)
|
---|
444 | {
|
---|
445 | this.stylesheet = GSXML.elementToString(xslt.getDocumentElement(), true);
|
---|
446 | this.source = source;
|
---|
447 | XMLTransformer.debugFileCount++;
|
---|
448 | }
|
---|
449 |
|
---|
450 | public TransformErrorListener(File xslt, Source source)
|
---|
451 | {
|
---|
452 | this.debugAsFile = false; // if this constructor is called, we're dealing with physical files for both xslt and source
|
---|
453 | this.source = source;
|
---|
454 | this.stylesheet = xslt.getAbsolutePath(); // not necessary to get the string from the file
|
---|
455 | // all we were going to do with it *on error* was write it out to a file anyway
|
---|
456 | }
|
---|
457 |
|
---|
458 | // *********** METHODS CALLED AUTOMATICALLY ON ERROR
|
---|
459 |
|
---|
460 | // Receive notification of a recoverable error.
|
---|
461 | public void error(TransformerException exception)
|
---|
462 | {
|
---|
463 | handleError("Error:\n", exception);
|
---|
464 | }
|
---|
465 |
|
---|
466 | // Receive notification of a non-recoverable error.
|
---|
467 | public void fatalError(TransformerException exception)
|
---|
468 | {
|
---|
469 | handleError("Fatal Error:\n", exception);
|
---|
470 | }
|
---|
471 |
|
---|
472 | // Receive notification of a warning.
|
---|
473 | public void warning(TransformerException exception)
|
---|
474 | {
|
---|
475 | handleError("Warning:\n", exception);
|
---|
476 | }
|
---|
477 |
|
---|
478 | public String toString(TransformerException e)
|
---|
479 | {
|
---|
480 | String msg = "Exception encountered was:\n\t";
|
---|
481 | String location = e.getLocationAsString();
|
---|
482 | if (location != null)
|
---|
483 | {
|
---|
484 | msg = msg + "Location: " + location + "\n\t";
|
---|
485 | }
|
---|
486 |
|
---|
487 | return msg + "Message: " + e.getMessage();
|
---|
488 | }
|
---|
489 |
|
---|
490 | // clears the errorPage variable after the first call to this method
|
---|
491 | public String getErrorMessage()
|
---|
492 | {
|
---|
493 | String errMsg = this.errorMessage;
|
---|
494 | if (this.errorMessage != null)
|
---|
495 | {
|
---|
496 | this.errorMessage = null;
|
---|
497 | }
|
---|
498 | return errMsg;
|
---|
499 | }
|
---|
500 |
|
---|
501 | // sets the errorMessage member variable to the data stored in the exception
|
---|
502 | // and writes the errorMessage to the logger and tomcat's System.err
|
---|
503 | protected void handleError(String errorType, TransformerException exception)
|
---|
504 | {
|
---|
505 |
|
---|
506 | this.errorMessage = errorType + toString(exception);
|
---|
507 |
|
---|
508 | // If either the stylesheet or the source to be transformed with it were not files,
|
---|
509 | // so that the transformation was performed in-memory, then the "location" information
|
---|
510 | // during the error handling (if any) wouldn't have been helpful.
|
---|
511 | // To allow proper debugging, we write both stylesheet and source out as physical files
|
---|
512 | // and perform the same transformation again, so that when a transformation error does
|
---|
513 | // occur, the files are not in-memory but can be viewed, and any location information
|
---|
514 | // for the error given by the ErrorListener will be sensible (instead of the unhelpful
|
---|
515 | // "line#0 column#0 in file://somewhere/dummy.xsl").
|
---|
516 | // Note that if the stylesheet and the source it is to transform were both physical
|
---|
517 | // files to start off with, we will not need to perform the same transformation again
|
---|
518 | // since the error reporting would have provided accurate locations for those.
|
---|
519 | if (debugAsFile)
|
---|
520 | {
|
---|
521 |
|
---|
522 | performTransformWithPhysicalFiles(); // will give accurate line numbers
|
---|
523 |
|
---|
524 | // No need to print out the current error message (seen in the Else statement below),
|
---|
525 | // as the recursive call to XMLTransformer.transform(File, File, false) in method
|
---|
526 | // performTransformWithPhysicalFiles() will do this for us.
|
---|
527 | }
|
---|
528 | else
|
---|
529 | {
|
---|
530 | // printing out the error message
|
---|
531 | // since !debugAsFile, we are dealing with physical files,
|
---|
532 | // variable stylesheet would have stored the filename instead of contents
|
---|
533 | this.errorMessage = this.errorMessage + "\nstylesheet filename: " + stylesheet;
|
---|
534 |
|
---|
535 | this.errorMessage += "\nException CAUSE:\n" + exception.getCause();
|
---|
536 | System.err.println("\n****Error transforming xml:\n" + this.errorMessage + "\n****\n");
|
---|
537 | //System.err.println("Stylesheet was:\n + this.stylesheet + "************END STYLESHEET***********\n\n");
|
---|
538 |
|
---|
539 | logger.error(this.errorMessage);
|
---|
540 |
|
---|
541 | // now print out the source to a file, and run the stylesheet on it using a transform()
|
---|
542 | // then any error will be referring to one of these two input files.
|
---|
543 | }
|
---|
544 | }
|
---|
545 |
|
---|
546 | // This method will redo the transformation that went wrong with *real* files:
|
---|
547 | // it writes out the stylesheet and source XML to files first, then performs the transformation
|
---|
548 | // to get the actual line location of where things went wrong (instead of "line#0 column#0 in dummy.xsl")
|
---|
549 | protected void performTransformWithPhysicalFiles()
|
---|
550 | {
|
---|
551 | File webLogsTmpFolder = new File(GlobalProperties.getGSDL3Home() + File.separator + "logs" + File.separator + "tmp");
|
---|
552 | if (!webLogsTmpFolder.exists())
|
---|
553 | {
|
---|
554 | webLogsTmpFolder.mkdirs(); // create any necessary folders
|
---|
555 | }
|
---|
556 | File styleFile = new File(webLogsTmpFolder + File.separator + "stylesheet" + XMLTransformer.debugFileCount + ".xml");
|
---|
557 | File sourceFile = new File(webLogsTmpFolder + File.separator + "source" + XMLTransformer.debugFileCount + ".xml");
|
---|
558 | try
|
---|
559 | {
|
---|
560 | // write stylesheet to a file called stylesheet_systemID in tmp
|
---|
561 | FileWriter styleSheetWriter = new FileWriter(styleFile);
|
---|
562 | styleSheetWriter.write(stylesheet, 0, stylesheet.length());
|
---|
563 | styleSheetWriter.flush();
|
---|
564 | styleSheetWriter.close();
|
---|
565 | }
|
---|
566 | catch (Exception e)
|
---|
567 | {
|
---|
568 | System.err.println("*** Exception when trying to write out stylesheet to " + styleFile.getAbsolutePath());
|
---|
569 | }
|
---|
570 |
|
---|
571 | if (this.source != null)
|
---|
572 | { // ErrorListener was set on a Transformer object
|
---|
573 | try
|
---|
574 | {
|
---|
575 | FileWriter srcWriter = new FileWriter(sourceFile);
|
---|
576 | String contents = "";
|
---|
577 | if (source instanceof DOMSource)
|
---|
578 | {
|
---|
579 | DOMSource domSource = (DOMSource) source;
|
---|
580 | Document doc = (Document) domSource.getNode();
|
---|
581 | contents = GSXML.elementToString(doc.getDocumentElement(), true);
|
---|
582 | //contents = GSXML.xmlNodeToXMLString(domSource.getNode());
|
---|
583 | }
|
---|
584 | else if (source instanceof StreamSource)
|
---|
585 | {
|
---|
586 | StreamSource streamSource = (StreamSource) source;
|
---|
587 | BufferedReader reader = new BufferedReader(streamSource.getReader());
|
---|
588 | String line = "";
|
---|
589 | while ((line = reader.readLine()) != null)
|
---|
590 | {
|
---|
591 | contents = contents + line + "\n";
|
---|
592 | }
|
---|
593 | }
|
---|
594 | srcWriter.write(contents, 0, contents.length());
|
---|
595 | srcWriter.flush();
|
---|
596 | srcWriter.close();
|
---|
597 | }
|
---|
598 | catch (Exception e)
|
---|
599 | {
|
---|
600 | System.err.println("*** Exception when trying to write out stylesheet to " + sourceFile.getAbsolutePath());
|
---|
601 | }
|
---|
602 | }
|
---|
603 |
|
---|
604 | System.err.println("*****************************************");
|
---|
605 | System.err.println("Look for stylesheet in: " + styleFile.getAbsolutePath());
|
---|
606 | if (this.source != null)
|
---|
607 | { // ErrorListener was set on a Transformer object
|
---|
608 | System.err.println("Look for source XML in: " + sourceFile.getAbsolutePath());
|
---|
609 | }
|
---|
610 |
|
---|
611 | // now perform the transform again, which will assign another TransformErrorListener
|
---|
612 | // but since debuggingAsFile is turned off, we won't recurse into this section of
|
---|
613 | // handling the error again
|
---|
614 | if (this.source != null)
|
---|
615 | { // ErrorListener was set on a Transformer object
|
---|
616 | XMLTransformer.this.transform(styleFile, sourceFile); // calls the File, File version, so debugAsFile will be false
|
---|
617 | }
|
---|
618 | else
|
---|
619 | { // ErrorListener was set on a TransformerFactory object
|
---|
620 |
|
---|
621 | // The recursive step in this case is to perform the instantiation
|
---|
622 | // of the Transformer object again.
|
---|
623 | // Only one TransformerFactory object per XMLTransformer,
|
---|
624 | // and only one TransformerHandler object set on any TransformerFactory
|
---|
625 | // But the stylesheet used to create a Transformer from that TransformerFactory
|
---|
626 | // object changes each time, by calls to setStylesheet(),
|
---|
627 | // Therefore, the debugAsFile state for the single TransformerFactory's
|
---|
628 | // TransformerHandler changes each time also.
|
---|
629 |
|
---|
630 | try
|
---|
631 | {
|
---|
632 | debugAsFile = false;
|
---|
633 | this.stylesheet = styleFile.getAbsolutePath();
|
---|
634 | //TransformErrorListener transformerErrorListener = (TransformErrorListener)XMLTransformer.this.t_factory.getErrorListener();
|
---|
635 | //transformerErrorListener.setStylesheet(styleFile);
|
---|
636 | Transformer transformer = XMLTransformer.this.t_factory.newTransformer(new StreamSource(styleFile));
|
---|
637 | if (transformer == null)
|
---|
638 | {
|
---|
639 | String msg = "XMLTransformer transformer is " + transformer;
|
---|
640 | logger.info(msg);
|
---|
641 | System.out.println(msg + "\n****\n");
|
---|
642 | }
|
---|
643 | }
|
---|
644 | catch (TransformerConfigurationException e)
|
---|
645 | {
|
---|
646 | String message = "Couldn't create transformer object: " + e.getMessageAndLocation();
|
---|
647 | logger.error(message);
|
---|
648 | logger.error(e.getLocationAsString());
|
---|
649 | System.out.println(message);
|
---|
650 | }
|
---|
651 | }
|
---|
652 | }
|
---|
653 | }
|
---|
654 | }
|
---|