1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.ken.util;
17
18 import java.io.StringReader;
19 import java.io.StringWriter;
20 import java.util.HashMap;
21 import java.util.Iterator;
22
23 import javax.xml.transform.ErrorListener;
24 import javax.xml.transform.Source;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerException;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.stream.StreamResult;
29 import javax.xml.transform.stream.StreamSource;
30
31 import org.apache.log4j.Logger;
32
33
34
35
36
37 public class ContentTransformer {
38 private static final Logger LOG = Logger.getLogger(ContentTransformer.class);
39
40 private static final class LoggingErrorListener implements ErrorListener {
41 private final ErrorListener delegate;
42 public LoggingErrorListener(ErrorListener delegate) {
43 this.delegate = delegate;
44 }
45
46 public void error(TransformerException exception) throws TransformerException {
47 LOG.error("Error transforming document", exception);
48 }
49
50 public void fatalError(TransformerException exception) throws TransformerException {
51 if (delegate != null) {
52 delegate.fatalError(exception);
53 } else {
54 throw exception;
55 }
56
57 }
58
59 public void warning(TransformerException exception) throws TransformerException {
60 LOG.warn("Error transforming document", exception);
61 }
62
63 };
64
65 private Transformer transformer;
66
67
68
69
70
71
72 public ContentTransformer(StreamSource aStyleSheet) throws Exception {
73
74 TransformerFactory factory = TransformerFactory.newInstance();
75 transformer = factory.newTransformer( aStyleSheet );
76 }
77
78
79
80
81
82
83
84 public ContentTransformer(StreamSource aStyleSheet, HashMap parametermap) throws Exception {
85
86 TransformerFactory factory = TransformerFactory.newInstance();
87 transformer = factory.newTransformer( aStyleSheet );
88 Iterator iter = parametermap.keySet().iterator();
89 while (iter.hasNext()) {
90 Object o = iter.next();
91 String param = o.toString();
92 String value = (String) parametermap.get(param);
93 transformer.setParameter(param, value);
94 }
95 transformer.setErrorListener(new LoggingErrorListener(transformer.getErrorListener()));
96 }
97
98
99
100
101
102
103
104 public String transform(String xml) throws Exception {
105
106
107 Source xmlsource = new StreamSource(new StringReader(xml));
108 StringWriter sout = new StringWriter();
109
110 transformer.transform(xmlsource, new StreamResult(sout));
111
112
113 return sout.toString();
114 }
115 }