You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DocumentHelper.java 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.util;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.lang.reflect.Method;
  19. import javax.xml.XMLConstants;
  20. import javax.xml.parsers.DocumentBuilder;
  21. import javax.xml.parsers.DocumentBuilderFactory;
  22. import javax.xml.parsers.ParserConfigurationException;
  23. import javax.xml.stream.events.Namespace;
  24. import org.w3c.dom.Document;
  25. import org.w3c.dom.Element;
  26. import org.xml.sax.SAXException;
  27. public final class DocumentHelper {
  28. private static POILogger logger = POILogFactory.getLogger(DocumentHelper.class);
  29. private DocumentHelper() {}
  30. /**
  31. * Creates a new document builder, with sensible defaults
  32. */
  33. public static synchronized DocumentBuilder newDocumentBuilder() {
  34. try {
  35. DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  36. documentBuilder.setEntityResolver(SAXHelper.IGNORING_ENTITY_RESOLVER);
  37. return documentBuilder;
  38. } catch (ParserConfigurationException e) {
  39. throw new IllegalStateException("cannot create a DocumentBuilder", e);
  40. }
  41. }
  42. private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  43. static {
  44. documentBuilderFactory.setNamespaceAware(true);
  45. documentBuilderFactory.setValidating(false);
  46. trySetSAXFeature(documentBuilderFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
  47. trySetXercesSecurityManager(documentBuilderFactory);
  48. }
  49. private static void trySetSAXFeature(DocumentBuilderFactory documentBuilderFactory, String feature, boolean enabled) {
  50. try {
  51. documentBuilderFactory.setFeature(feature, enabled);
  52. } catch (Exception e) {
  53. logger.log(POILogger.WARN, "SAX Feature unsupported", feature, e);
  54. } catch (AbstractMethodError ame) {
  55. logger.log(POILogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame);
  56. }
  57. }
  58. private static void trySetXercesSecurityManager(DocumentBuilderFactory documentBuilderFactory) {
  59. // Try built-in JVM one first, standalone if not
  60. for (String securityManagerClassName : new String[] {
  61. "com.sun.org.apache.xerces.internal.util.SecurityManager",
  62. "org.apache.xerces.util.SecurityManager"
  63. }) {
  64. try {
  65. Object mgr = Class.forName(securityManagerClassName).newInstance();
  66. Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE);
  67. setLimit.invoke(mgr, 4096);
  68. documentBuilderFactory.setAttribute("http://apache.org/xml/properties/security-manager", mgr);
  69. // Stop once one can be setup without error
  70. return;
  71. } catch (Exception e) {
  72. logger.log(POILogger.WARN, "SAX Security Manager could not be setup", e);
  73. }
  74. }
  75. }
  76. /**
  77. * Parses the given stream via the default (sensible)
  78. * DocumentBuilder
  79. * @param inp Stream to read the XML data from
  80. * @return the parsed Document
  81. */
  82. public static Document readDocument(InputStream inp) throws IOException, SAXException {
  83. return newDocumentBuilder().parse(inp);
  84. }
  85. // must only be used to create empty documents, do not use it for parsing!
  86. private static final DocumentBuilder documentBuilderSingleton = newDocumentBuilder();
  87. /**
  88. * Creates a new DOM Document
  89. */
  90. public static synchronized Document createDocument() {
  91. return documentBuilderSingleton.newDocument();
  92. }
  93. /**
  94. * Adds a namespace declaration attribute to the given element.
  95. */
  96. public static void addNamespaceDeclaration(Element element, String namespacePrefix, String namespaceURI) {
  97. element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
  98. XMLConstants.XMLNS_ATTRIBUTE + ':' + namespacePrefix,
  99. namespaceURI);
  100. }
  101. /**
  102. * Adds a namespace declaration attribute to the given element.
  103. */
  104. public static void addNamespaceDeclaration(Element element, Namespace namespace) {
  105. addNamespaceDeclaration(element, namespace.getPrefix(), namespace.getNamespaceURI());
  106. }
  107. }