1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.xml.transform;
18
19 import javax.xml.transform.Result;
20 import javax.xml.transform.Source;
21 import javax.xml.transform.Transformer;
22 import javax.xml.transform.TransformerConfigurationException;
23 import javax.xml.transform.TransformerException;
24 import javax.xml.transform.TransformerFactory;
25 import javax.xml.transform.TransformerFactoryConfigurationError;
26
27 import org.springframework.util.Assert;
28
29
30
31
32
33
34
35
36 public class TransformerHelper {
37
38 private volatile TransformerFactory transformerFactory;
39
40 private Class<? extends TransformerFactory> transformerFactoryClass;
41
42
43
44
45 public TransformerHelper() {
46 }
47
48
49
50
51 public TransformerHelper(TransformerFactory transformerFactory) {
52 this.transformerFactory = transformerFactory;
53 }
54
55
56
57
58 public TransformerHelper(Class<? extends TransformerFactory> transformerFactoryClass) {
59 setTransformerFactoryClass(transformerFactoryClass);
60 }
61
62
63
64
65 public void setTransformerFactoryClass(Class<? extends TransformerFactory> transformerFactoryClass) {
66 Assert.isAssignable(TransformerFactory.class, transformerFactoryClass);
67 this.transformerFactoryClass = transformerFactoryClass;
68 }
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84 protected TransformerFactory newTransformerFactory(Class<? extends TransformerFactory> transformerFactoryClass) {
85 if (transformerFactoryClass != null) {
86 try {
87 return transformerFactoryClass.newInstance();
88 }
89 catch (Exception ex) {
90 throw new TransformerFactoryConfigurationError(ex,
91 "Could not instantiate TransformerFactory [" + transformerFactoryClass + "]");
92 }
93 }
94 else {
95 return TransformerFactory.newInstance();
96 }
97 }
98
99
100
101
102
103
104 public TransformerFactory getTransformerFactory() {
105 TransformerFactory result = transformerFactory;
106 if (result == null) {
107 synchronized (this) {
108 result = transformerFactory;
109 if (result == null) {
110 transformerFactory = result = newTransformerFactory(transformerFactoryClass);
111 }
112 }
113 }
114 return result;
115 }
116
117
118
119
120
121
122
123
124 public Transformer createTransformer() throws TransformerConfigurationException {
125 return getTransformerFactory().newTransformer();
126 }
127
128
129
130
131
132
133
134
135
136 public void transform(Source source, Result result) throws TransformerException {
137 Transformer transformer = createTransformer();
138 transformer.transform(source, result);
139 }
140
141 }