You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@poi.apache.org by fa...@apache.org on 2019/09/24 20:52:38 UTC
svn commit: r1867496 - in /poi/trunk/src/ooxml/java/org/apache/poi:
ooxml/dev/OOXMLPrettyPrint.java ooxml/util/TransformerHelper.java
openxml4j/opc/StreamHelper.java xssf/extractor/XSSFExportToXml.java
xssf/usermodel/XSSFBuiltinTableStyle.java
Author: fanningpj
Date: Tue Sep 24 20:52:37 2019
New Revision: 1867496
URL: http://svn.apache.org/viewvc?rev=1867496&view=rev
Log:
add TransformerHelper
Added:
poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java
- copied, changed from r1867492, poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/DocumentHelper.java
Modified:
poi/trunk/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java
poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java
poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java
poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java
Modified: poi/trunk/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java?rev=1867496&r1=1867495&r2=1867496&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java Tue Sep 24 20:52:37 2019
@@ -16,35 +16,24 @@
==================================================================== */
package org.apache.poi.ooxml.dev;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Enumeration;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipOutputStream;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Result;
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.poi.ooxml.util.DocumentHelper;
+import org.apache.poi.ooxml.util.TransformerHelper;
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.util.IOUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.*;
+import java.util.Enumeration;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
/**
* Reads a zipped OOXML file and produces a copy with the included
* pretty-printed XML files.
@@ -82,8 +71,7 @@ public class OOXMLPrettyPrint {
System.out.println("Done.");
}
- private static void handleFile(File file, File outFile) throws ZipException,
- IOException, ParserConfigurationException {
+ private static void handleFile(File file, File outFile) throws IOException {
System.out.println("Reading zip-file " + file + " and writing pretty-printed XML to " + outFile);
try (ZipSecureFile zipFile = ZipHelper.openZipFile(file)) {
@@ -121,7 +109,7 @@ public class OOXMLPrettyPrint {
}
private static void pretty(Document document, OutputStream outputStream, int indent) throws TransformerException {
- TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ TransformerFactory transformerFactory = TransformerHelper.getFactory();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
if (indent > 0) {
Copied: poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java (from r1867492, poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/DocumentHelper.java)
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java?p2=poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java&p1=poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/DocumentHelper.java&r1=1867492&r2=1867496&rev=1867496&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/DocumentHelper.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java Tue Sep 24 20:52:37 2019
@@ -17,187 +17,33 @@
package org.apache.poi.ooxml.util;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.Method;
-import java.util.concurrent.TimeUnit;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.events.Namespace;
-
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
-import org.w3c.dom.*;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-
-public final class DocumentHelper {
- private static POILogger logger = POILogFactory.getLogger(DocumentHelper.class);
- private static long lastLog;
-
- private DocumentHelper() {}
- private static class DocHelperErrorHandler implements ErrorHandler {
-
- public void warning(SAXParseException exception) {
- printError(POILogger.WARN, exception);
- }
-
- public void error(SAXParseException exception) {
- printError(POILogger.ERROR, exception);
- }
+import javax.xml.XMLConstants;
+import javax.xml.transform.TransformerFactory;
- public void fatalError(SAXParseException exception) throws SAXException {
- printError(POILogger.FATAL, exception);
- throw exception;
- }
+public final class TransformerHelper {
+ private static POILogger logger = POILogFactory.getLogger(TransformerHelper.class);
- /** Prints the error message. */
- private void printError(int type, SAXParseException ex) {
- StringBuilder sb = new StringBuilder();
-
- String systemId = ex.getSystemId();
- if (systemId != null) {
- int index = systemId.lastIndexOf('/');
- if (index != -1)
- systemId = systemId.substring(index + 1);
- sb.append(systemId);
- }
- sb.append(':');
- sb.append(ex.getLineNumber());
- sb.append(':');
- sb.append(ex.getColumnNumber());
- sb.append(": ");
- sb.append(ex.getMessage());
+ private TransformerHelper() {}
- logger.log(type, sb.toString(), ex);
- }
- }
-
- /**
- * Creates a new document builder, with sensible defaults
- *
- * @throws IllegalStateException If creating the DocumentBuilder fails, e.g.
- * due to {@link ParserConfigurationException}.
- */
- public static DocumentBuilder newDocumentBuilder() {
- try {
- DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
- documentBuilder.setEntityResolver(SAXHelper.IGNORING_ENTITY_RESOLVER);
- documentBuilder.setErrorHandler(new DocHelperErrorHandler());
- return documentBuilder;
- } catch (ParserConfigurationException e) {
- throw new IllegalStateException("cannot create a DocumentBuilder", e);
- }
+ static final TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ static {
+ trySetFeature(transformerFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
- static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
- static {
- documentBuilderFactory.setNamespaceAware(true);
- documentBuilderFactory.setValidating(false);
- //this doesn't appear to work, and we still need to limit
- //entity expansions to 1 in trySetXercesSecurityManager
- documentBuilderFactory.setExpandEntityReferences(false);
- trySetFeature(documentBuilderFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
- trySetFeature(documentBuilderFactory, POIXMLConstants.FEATURE_DISALLOW_DOCTYPE_DECL, true);
- trySetFeature(documentBuilderFactory, POIXMLConstants.FEATURE_LOAD_DTD_GRAMMAR, false);
- trySetFeature(documentBuilderFactory, POIXMLConstants.FEATURE_LOAD_EXTERNAL_DTD, false);
- trySetXercesSecurityManager(documentBuilderFactory);
+ public static TransformerFactory getFactory() {
+ return transformerFactory;
}
- private static void trySetFeature(@SuppressWarnings("SameParameterValue") DocumentBuilderFactory dbf, String feature, boolean enabled) {
+ private static void trySetFeature(TransformerFactory tf, String feature, boolean enabled) {
try {
- dbf.setFeature(feature, enabled);
+ tf.setFeature(feature, enabled);
} catch (Exception e) {
- logger.log(POILogger.WARN, "DocumentBuilderFactory Feature unsupported", feature, e);
+ logger.log(POILogger.WARN, "TransformerFactory Feature unsupported", feature, e);
} catch (AbstractMethodError ame) {
- logger.log(POILogger.WARN, "Cannot set DocumentBuilderFactory feature because outdated XML parser in classpath", feature, ame);
+ logger.log(POILogger.WARN, "Cannot set TransformerFactory feature because outdated XML parser in classpath", feature, ame);
}
}
-
- private static void trySetXercesSecurityManager(@SuppressWarnings("SameParameterValue") DocumentBuilderFactory dbf) {
- // Try built-in JVM one first, standalone if not
- for (String securityManagerClassName : new String[]{
- //"com.sun.org.apache.xerces.internal.util.SecurityManager",
- "org.apache.xerces.util.SecurityManager"
- }) {
- try {
- Object mgr = Class.forName(securityManagerClassName).newInstance();
- Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE);
- setLimit.invoke(mgr, 1);
- dbf.setAttribute(POIXMLConstants.PROPERTY_SECURITY_MANAGER, mgr);
- // Stop once one can be setup without error
- return;
- } catch (ClassNotFoundException e) {
- // continue without log, this is expected in some setups
- } catch (Throwable e) { // NOSONAR - also catch things like NoClassDefError here
- if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
- logger.log(POILogger.WARN, "DocumentBuilderFactory Security Manager could not be setup [log suppressed for 5 minutes]", e);
- lastLog = System.currentTimeMillis();
- }
- }
- }
-
- // separate old version of Xerces not found => use the builtin way of setting the property
- // Note: when entity_expansion_limit==0, there is no limit!
- try {
- dbf.setAttribute(POIXMLConstants.PROPERTY_ENTITY_EXPANSION_LIMIT, 1);
- } catch (Throwable e) {
- if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
- logger.log(POILogger.WARN, "DocumentBuilderFactory Entity Expansion Limit could not be setup [log suppressed for 5 minutes]", e);
- lastLog = System.currentTimeMillis();
- }
- }
- }
-
- /**
- * Parses the given stream via the default (sensible)
- * DocumentBuilder
- * @param inp Stream to read the XML data from
- * @return the parsed Document
- */
- public static Document readDocument(InputStream inp) throws IOException, SAXException {
- return newDocumentBuilder().parse(inp);
- }
-
- /**
- * Parses the given stream via the default (sensible)
- * DocumentBuilder
- * @param inp sax source to read the XML data from
- * @return the parsed Document
- */
- public static Document readDocument(InputSource inp) throws IOException, SAXException {
- return newDocumentBuilder().parse(inp);
- }
-
- // must only be used to create empty documents, do not use it for parsing!
- private static final DocumentBuilder documentBuilderSingleton = newDocumentBuilder();
-
- /**
- * Creates a new DOM Document
- */
- public static Document createDocument() {
- return documentBuilderSingleton.newDocument();
- }
-
- /**
- * Adds a namespace declaration attribute to the given element.
- */
- public static void addNamespaceDeclaration(Element element, String namespacePrefix, String namespaceURI) {
- element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
- XMLConstants.XMLNS_ATTRIBUTE + ':' + namespacePrefix,
- namespaceURI);
- }
-
- /**
- * Adds a namespace declaration attribute to the given element.
- */
- public static void addNamespaceDeclaration(Element element, Namespace namespace) {
- addNamespaceDeclaration(element, namespace.getPrefix(), namespace.getNamespaceURI());
- }
}
Modified: poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java?rev=1867496&r1=1867495&r2=1867496&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java Tue Sep 24 20:52:37 2019
@@ -27,10 +27,10 @@ import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
+import org.apache.poi.ooxml.util.TransformerHelper;
import org.w3c.dom.Document;
public final class StreamHelper {
@@ -38,12 +38,10 @@ public final class StreamHelper {
private StreamHelper() {
// Do nothing
}
-
- private static final TransformerFactory transformerFactory = TransformerFactory.newInstance();
-
- private static synchronized Transformer getIdentityTransformer() throws TransformerException {
- return transformerFactory.newTransformer();
- }
+
+ private static synchronized Transformer getIdentityTransformer() throws TransformerException {
+ return TransformerHelper.getFactory().newTransformer();
+ }
/**
* Save the document object in the specified output stream.
@@ -55,38 +53,38 @@ public final class StreamHelper {
* @return <b>true</b> if the xml is successfully written in the stream,
* else <b>false</b>.
*/
- public static boolean saveXmlInStream(Document xmlContent,
- OutputStream outStream) {
- try {
- Transformer trans = getIdentityTransformer();
- Source xmlSource = new DOMSource(xmlContent);
- // prevent close of stream by transformer:
- Result outputTarget = new StreamResult(new FilterOutputStream(
- outStream) {
- @Override
- public void write(byte[] b, int off, int len)
- throws IOException {
- out.write(b, off, len);
- }
-
- @Override
- public void close() throws IOException {
- out.flush(); // only flush, don't close!
- }
- });
- // xmlContent.setXmlStandalone(true);
- trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
- // don't indent xml documents, the indent will cause errors in calculating the xml signature
- // because of different handling of linebreaks in Windows/Unix
- // see https://stackoverflow.com/questions/36063375
- trans.setOutputProperty(OutputKeys.INDENT, "no");
- trans.setOutputProperty(OutputKeys.STANDALONE, "yes");
- trans.transform(xmlSource, outputTarget);
- } catch (TransformerException e) {
- return false;
- }
- return true;
- }
+ public static boolean saveXmlInStream(Document xmlContent,
+ OutputStream outStream) {
+ try {
+ Transformer trans = getIdentityTransformer();
+ Source xmlSource = new DOMSource(xmlContent);
+ // prevent close of stream by transformer:
+ Result outputTarget = new StreamResult(new FilterOutputStream(
+ outStream) {
+ @Override
+ public void write(byte[] b, int off, int len)
+ throws IOException {
+ out.write(b, off, len);
+ }
+
+ @Override
+ public void close() throws IOException {
+ out.flush(); // only flush, don't close!
+ }
+ });
+ // xmlContent.setXmlStandalone(true);
+ trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+ // don't indent xml documents, the indent will cause errors in calculating the xml signature
+ // because of different handling of linebreaks in Windows/Unix
+ // see https://stackoverflow.com/questions/36063375
+ trans.setOutputProperty(OutputKeys.INDENT, "no");
+ trans.setOutputProperty(OutputKeys.STANDALONE, "yes");
+ trans.transform(xmlSource, outputTarget);
+ } catch (TransformerException e) {
+ return false;
+ }
+ return true;
+ }
/**
* Copy the input stream into the output stream.
Modified: poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java?rev=1867496&r1=1867495&r2=1867496&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java Tue Sep 24 20:52:37 2019
@@ -33,13 +33,13 @@ import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
+import org.apache.poi.ooxml.util.TransformerHelper;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ooxml.util.DocumentHelper;
@@ -218,8 +218,7 @@ public class XSSFExportToXml implements
//Output the XML
//set up a transformer
- TransformerFactory transfac = TransformerFactory.newInstance();
- Transformer trans = transfac.newTransformer();
+ Transformer trans = TransformerHelper.getFactory().newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.ENCODING, encoding);
Modified: poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java?rev=1867496&r1=1867495&r2=1867496&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java Tue Sep 24 20:52:37 2019
@@ -25,6 +25,7 @@ import java.nio.charset.StandardCharsets
import java.util.EnumMap;
import java.util.Map;
+import org.apache.poi.ooxml.util.TransformerHelper;
import org.apache.poi.ss.usermodel.DifferentialStyleProvider;
import org.apache.poi.ss.usermodel.TableStyle;
import org.apache.poi.ss.usermodel.TableStyleType;
@@ -439,7 +440,7 @@ public enum XSSFBuiltinTableStyle {
}
private static String writeToString(Node node) throws IOException, TransformerException {
- TransformerFactory tf = TransformerFactory.newInstance();
+ TransformerFactory tf = TransformerHelper.getFactory();
try (StringWriter sw = new StringWriter()){
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@poi.apache.org
For additional commands, e-mail: commits-help@poi.apache.org