29
29
import org .apache .hadoop .classification .InterfaceAudience ;
30
30
import org .apache .hadoop .classification .InterfaceStability ;
31
31
32
+ import org .slf4j .Logger ;
33
+ import org .slf4j .LoggerFactory ;
32
34
import org .xml .sax .SAXException ;
33
35
34
36
import java .io .*;
41
43
@ InterfaceStability .Unstable
42
44
public class XMLUtils {
43
45
46
+ private static final Logger LOG =
47
+ LoggerFactory .getLogger (XMLUtils .class );
48
+
44
49
public static final String DISALLOW_DOCTYPE_DECL =
45
50
"http://apache.org/xml/features/disallow-doctype-decl" ;
46
51
public static final String LOAD_EXTERNAL_DECL =
@@ -138,8 +143,8 @@ public static TransformerFactory newSecureTransformerFactory()
138
143
throws TransformerConfigurationException {
139
144
TransformerFactory trfactory = TransformerFactory .newInstance ();
140
145
trfactory .setFeature (XMLConstants .FEATURE_SECURE_PROCESSING , true );
141
- trfactory . setAttribute ( XMLConstants .ACCESS_EXTERNAL_DTD , "" );
142
- trfactory . setAttribute ( XMLConstants .ACCESS_EXTERNAL_STYLESHEET , "" );
146
+ bestEffortSetAttribute ( trfactory , XMLConstants .ACCESS_EXTERNAL_DTD , "" );
147
+ bestEffortSetAttribute ( trfactory , XMLConstants .ACCESS_EXTERNAL_STYLESHEET , "" );
143
148
return trfactory ;
144
149
}
145
150
@@ -156,8 +161,29 @@ public static SAXTransformerFactory newSecureSAXTransformerFactory()
156
161
throws TransformerConfigurationException {
157
162
SAXTransformerFactory trfactory = (SAXTransformerFactory ) SAXTransformerFactory .newInstance ();
158
163
trfactory .setFeature (XMLConstants .FEATURE_SECURE_PROCESSING , true );
159
- trfactory . setAttribute ( XMLConstants .ACCESS_EXTERNAL_DTD , "" );
160
- trfactory . setAttribute ( XMLConstants .ACCESS_EXTERNAL_STYLESHEET , "" );
164
+ bestEffortSetAttribute ( trfactory , XMLConstants .ACCESS_EXTERNAL_DTD , "" );
165
+ bestEffortSetAttribute ( trfactory , XMLConstants .ACCESS_EXTERNAL_STYLESHEET , "" );
161
166
return trfactory ;
162
167
}
168
+
169
+ /**
170
+ * Set an attribute value on a {@link TransformerFactory}. If the TransformerFactory
171
+ * does not support the attribute, the method just returns <code>false</code> and
172
+ * logs the issue at debug level.
173
+ *
174
+ * @param transformerFactory to update
175
+ * @param name of the attribute to set
176
+ * @param value to set on the attribute
177
+ * @return whether the attribute was successfully set
178
+ */
179
+ static boolean bestEffortSetAttribute (TransformerFactory transformerFactory ,
180
+ String name , Object value ) {
181
+ try {
182
+ transformerFactory .setAttribute (name , value );
183
+ return true ;
184
+ } catch (Throwable t ) {
185
+ LOG .debug ("Issue setting TransformerFactory attribute {}: {}" , name , t .toString ());
186
+ }
187
+ return false ;
188
+ }
163
189
}
0 commit comments