diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2019-12-03 21:56:47 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2019-12-03 21:56:47 +0000 |
commit | 08159e66a738c291572745cee8cc3617777dc2b5 (patch) | |
tree | 849e1239faa41d3493e57a0141a1c3d6b598fd9f /src/ooxml/java/org/apache/poi | |
parent | dd3279df30eb9656c3a72f4a6a2445f777c7dd5a (diff) | |
download | poi-08159e66a738c291572745cee8cc3617777dc2b5.tar.gz poi-08159e66a738c291572745cee8cc3617777dc2b5.zip |
Sonar Fixes + Refactor scattered XML initializations to XMLHelper
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1870769 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src/ooxml/java/org/apache/poi')
12 files changed, 80 insertions, 320 deletions
diff --git a/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java b/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java index 8e8b9571d1..fd48c05462 100644 --- a/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java +++ b/src/ooxml/java/org/apache/poi/ooxml/dev/OOXMLPrettyPrint.java @@ -16,24 +16,33 @@ ==================================================================== */ 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.ZipOutputStream; + +import javax.xml.parsers.DocumentBuilder; +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.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.apache.poi.util.XMLHelper; 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. @@ -42,6 +51,8 @@ import java.util.zip.ZipOutputStream; * use different formatting of the XML. */ public class OOXMLPrettyPrint { + private static final String XML_INDENT_AMOUNT = "{http://xml.apache.org/xslt}indent-amount"; + private final DocumentBuilder documentBuilder; public OOXMLPrettyPrint() { @@ -109,13 +120,11 @@ public class OOXMLPrettyPrint { } private static void pretty(Document document, OutputStream outputStream, int indent) throws TransformerException { - TransformerFactory transformerFactory = TransformerHelper.getFactory(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + Transformer transformer = XMLHelper.newTransformer(); if (indent > 0) { // set properties to indent the resulting XML nicely transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); + transformer.setOutputProperty(XML_INDENT_AMOUNT, Integer.toString(indent)); } Result result = new StreamResult(outputStream); Source source = new DOMSource(document); diff --git a/src/ooxml/java/org/apache/poi/ooxml/util/DocumentHelper.java b/src/ooxml/java/org/apache/poi/ooxml/util/DocumentHelper.java index 4e66f46b9c..f5a2b13996 100644 --- a/src/ooxml/java/org/apache/poi/ooxml/util/DocumentHelper.java +++ b/src/ooxml/java/org/apache/poi/ooxml/util/DocumentHelper.java @@ -19,66 +19,24 @@ 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.apache.poi.util.XMLHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Element; 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; + // must only be used to create empty documents, do not use it for parsing! + private static final DocumentBuilder documentBuilderSingleton = newDocumentBuilder(); 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); - } - - public void fatalError(SAXParseException exception) throws SAXException { - printError(POILogger.FATAL, exception); - throw exception; - } - - /** 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()); - - logger.log(type, sb.toString(), ex); - } - } - /** * Creates a new document builder, with sensible defaults * @@ -86,80 +44,14 @@ public final class DocumentHelper { * 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 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); - } - - private static void trySetFeature(@SuppressWarnings("SameParameterValue") DocumentBuilderFactory dbf, String feature, boolean enabled) { - try { - dbf.setFeature(feature, enabled); - } catch (Exception e) { - logger.log(POILogger.WARN, "DocumentBuilderFactory Feature unsupported", feature, e); - } catch (AbstractMethodError ame) { - logger.log(POILogger.WARN, "Cannot set DocumentBuilderFactory 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(); - } - } + return XMLHelper.newDocumentBuilder(); } /** * Parses the given stream via the default (sensible) * DocumentBuilder * @param inp Stream to read the XML data from - * @return the parsed Document + * @return the parsed Document */ public static Document readDocument(InputStream inp) throws IOException, SAXException { return newDocumentBuilder().parse(inp); @@ -175,9 +67,6 @@ public final class DocumentHelper { 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 */ diff --git a/src/ooxml/java/org/apache/poi/ooxml/util/POIXMLConstants.java b/src/ooxml/java/org/apache/poi/ooxml/util/POIXMLConstants.java deleted file mode 100644 index c6d7935fda..0000000000 --- a/src/ooxml/java/org/apache/poi/ooxml/util/POIXMLConstants.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ooxml.util; - -public class POIXMLConstants { - public static final String FEATURE_LOAD_DTD_GRAMMAR = "http://apache.org/xml/features/nonvalidating/load-dtd-grammar"; - public static final String FEATURE_LOAD_EXTERNAL_DTD = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; - public static final String FEATURE_DISALLOW_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl"; - public static final String PROPERTY_ENTITY_EXPANSION_LIMIT = "http://www.oracle.com/xml/jaxp/properties/entityExpansionLimit"; - public static final String PROPERTY_SECURITY_MANAGER = "http://apache.org/xml/properties/security-manager"; -} diff --git a/src/ooxml/java/org/apache/poi/ooxml/util/SAXHelper.java b/src/ooxml/java/org/apache/poi/ooxml/util/SAXHelper.java index ede0ac4582..a6c2b58485 100644 --- a/src/ooxml/java/org/apache/poi/ooxml/util/SAXHelper.java +++ b/src/ooxml/java/org/apache/poi/ooxml/util/SAXHelper.java @@ -17,120 +17,25 @@ package org.apache.poi.ooxml.util; -import java.io.StringReader; -import java.lang.reflect.Method; -import java.util.concurrent.TimeUnit; - -import javax.xml.XMLConstants; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParserFactory; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; +import org.apache.poi.util.Removal; +import org.apache.poi.util.XMLHelper; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * Provides handy methods for working with SAX parsers and readers + * @deprecated use {@link XMLHelper} */ +@Deprecated +@Removal(version = "5.0.0") public final class SAXHelper { - private static final POILogger logger = POILogFactory.getLogger(SAXHelper.class); - private static long lastLog; - - private SAXHelper() {} - /** * Creates a new SAX XMLReader, with sensible defaults */ public static XMLReader newXMLReader() throws SAXException, ParserConfigurationException { - XMLReader xmlReader = saxFactory.newSAXParser().getXMLReader(); - xmlReader.setEntityResolver(IGNORING_ENTITY_RESOLVER); - trySetSAXFeature(xmlReader, XMLConstants.FEATURE_SECURE_PROCESSING); - trySetXercesSecurityManager(xmlReader); - return xmlReader; - } - - static final EntityResolver IGNORING_ENTITY_RESOLVER = (publicId, systemId) -> new InputSource(new StringReader("")); - - private static final SAXParserFactory saxFactory; - static { - try { - saxFactory = SAXParserFactory.newInstance(); - saxFactory.setValidating(false); - saxFactory.setNamespaceAware(true); - trySetSAXFeature(saxFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true); - trySetSAXFeature(saxFactory, POIXMLConstants.FEATURE_LOAD_DTD_GRAMMAR, false); - trySetSAXFeature(saxFactory, POIXMLConstants.FEATURE_LOAD_EXTERNAL_DTD, false); - } catch (RuntimeException | Error re) { // NOSONAR - // this also catches NoClassDefFoundError, which may be due to a local class path issue - // This may occur if the code is run inside a web container - // or a restricted JVM - // See bug 61170: https://bz.apache.org/bugzilla/show_bug.cgi?id=61170 - logger.log(POILogger.WARN, "Failed to create SAXParserFactory", re); - throw re; - } catch (Exception e) { - logger.log(POILogger.WARN, "Failed to create SAXParserFactory", e); - throw new RuntimeException("Failed to create SAXParserFactory", e); - } - } - - private static void trySetSAXFeature(@SuppressWarnings("SameParameterValue") SAXParserFactory spf, - String feature, boolean flag) { - try { - spf.setFeature(feature, flag); - } catch (Exception e) { - logger.log(POILogger.WARN, "SAX Feature unsupported", feature, e); - } catch (AbstractMethodError ame) { - logger.log(POILogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame); - } - } - - private static void trySetSAXFeature(XMLReader xmlReader, @SuppressWarnings("SameParameterValue") String feature) { - try { - xmlReader.setFeature(feature, true); - } catch (Exception e) { - logger.log(POILogger.WARN, "SAX Feature unsupported", feature, e); - } catch (AbstractMethodError ame) { - logger.log(POILogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame); - } - } - - private static void trySetXercesSecurityManager(XMLReader xmlReader) { - // 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); - xmlReader.setProperty(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 - // throttle the log somewhat as it can spam the log otherwise - if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) { - logger.log(POILogger.WARN, "SAX 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 - try { - xmlReader.setProperty(POIXMLConstants.PROPERTY_ENTITY_EXPANSION_LIMIT, 1); - } catch (SAXException e) { // NOSONAR - also catch things like NoClassDefError here - // throttle the log somewhat as it can spam the log otherwise - if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) { - logger.log(POILogger.WARN, "SAX Security Manager could not be setup [log suppressed for 5 minutes]", e); - lastLog = System.currentTimeMillis(); - } - } + return XMLHelper.newXMLReader(); } } diff --git a/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java b/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java index 37422c6c91..e6a3f0c8f3 100644 --- a/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java +++ b/src/ooxml/java/org/apache/poi/ooxml/util/TransformerHelper.java @@ -17,33 +17,20 @@ package org.apache.poi.ooxml.util; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -import javax.xml.XMLConstants; import javax.xml.transform.TransformerFactory; -public final class TransformerHelper { - private static POILogger logger = POILogFactory.getLogger(TransformerHelper.class); +import org.apache.poi.util.Removal; +import org.apache.poi.util.XMLHelper; +/** + * @deprecated use {@link XMLHelper} + */ +@Removal(version = "5.0.0") +@Deprecated +public final class TransformerHelper { private TransformerHelper() {} - static final TransformerFactory transformerFactory = TransformerFactory.newInstance(); - static { - trySetFeature(transformerFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true); - } - public static TransformerFactory getFactory() { - return transformerFactory; - } - - private static void trySetFeature(TransformerFactory tf, String feature, boolean enabled) { - try { - tf.setFeature(feature, enabled); - } catch (Exception e) { - logger.log(POILogger.WARN, "TransformerFactory Feature unsupported", feature, e); - } catch (AbstractMethodError ame) { - logger.log(POILogger.WARN, "Cannot set TransformerFactory feature because outdated XML parser in classpath", feature, ame); - } + return XMLHelper.getTransformerFactory(); } } diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java index 3c4dc6a238..af31eb3ab3 100644 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java +++ b/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java @@ -30,7 +30,8 @@ import javax.xml.transform.TransformerException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import org.apache.poi.ooxml.util.TransformerHelper; +import org.apache.poi.util.IOUtils; +import org.apache.poi.util.XMLHelper; import org.w3c.dom.Document; public final class StreamHelper { @@ -39,10 +40,6 @@ public final class StreamHelper { // Do nothing } - private static synchronized Transformer getIdentityTransformer() throws TransformerException { - return TransformerHelper.getFactory().newTransformer(); - } - /** * Save the document object in the specified output stream. * @@ -56,7 +53,7 @@ public final class StreamHelper { public static boolean saveXmlInStream(Document xmlContent, OutputStream outStream) { try { - Transformer trans = getIdentityTransformer(); + Transformer trans = XMLHelper.newTransformer(); Source xmlSource = new DOMSource(xmlContent); // prevent close of stream by transformer: Result outputTarget = new StreamResult(new FilterOutputStream( @@ -97,14 +94,10 @@ public final class StreamHelper { */ public static boolean copyStream(InputStream inStream, OutputStream outStream) { try { - byte[] buffer = new byte[1024]; - int bytesRead; - while ((bytesRead = inStream.read(buffer)) >= 0) { - outStream.write(buffer, 0, bytesRead); - } + IOUtils.copy(inStream, outStream); + return true; } catch (Exception e) { return false; } - return true; } } diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java index ec6a3f0e2d..c7fd85c468 100644 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java +++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java @@ -96,7 +96,7 @@ public class TSPTimeStampService implements TimeStampService { } } - @SuppressWarnings("unchecked") + @SuppressWarnings({"unchecked","squid:S2647"}) public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception { // digest the message diff --git a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java index 09191f9abf..17013e7333 100644 --- a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java +++ b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java @@ -18,18 +18,19 @@ package org.apache.poi.xssf.eventusermodel; import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; -import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.ArrayList; import java.util.List; +import javax.xml.parsers.ParserConfigurationException; + import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ooxml.util.SAXHelper; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.util.Removal; +import org.apache.poi.util.XMLHelper; import org.apache.poi.xssf.model.SharedStrings; import org.apache.poi.xssf.usermodel.XSSFRelation; import org.apache.poi.xssf.usermodel.XSSFRichTextString; @@ -173,7 +174,7 @@ public class ReadOnlySharedStringsTable extends DefaultHandler implements Shared pis.unread(emptyTest); InputSource sheetSource = new InputSource(pis); try { - XMLReader sheetParser = SAXHelper.newXMLReader(); + XMLReader sheetParser = XMLHelper.newXMLReader(); sheetParser.setContentHandler(this); sheetParser.parse(sheetSource); } catch(ParserConfigurationException e) { diff --git a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFReader.java b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFReader.java index 8d1ce1a949..b239951c43 100644 --- a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFReader.java +++ b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFReader.java @@ -16,7 +16,6 @@ ==================================================================== */ package org.apache.poi.xssf.eventusermodel; -import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -30,6 +29,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import javax.xml.parsers.ParserConfigurationException; + import org.apache.poi.ooxml.POIXMLException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; @@ -42,7 +43,7 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.apache.poi.ooxml.util.SAXHelper; +import org.apache.poi.util.XMLHelper; import org.apache.poi.xssf.model.CommentsTable; import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.model.StylesTable; @@ -253,7 +254,7 @@ public class XSSFReader { XMLSheetRefReader xmlSheetRefReader = new XMLSheetRefReader(); XMLReader xmlReader; try { - xmlReader = SAXHelper.newXMLReader(); + xmlReader = XMLHelper.newXMLReader(); } catch (ParserConfigurationException | SAXException e) { throw new POIXMLException(e); } diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java index 526812183d..998037b59b 100644 --- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java +++ b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java @@ -16,7 +16,6 @@ ==================================================================== */ package org.apache.poi.xssf.extractor; -import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; @@ -24,6 +23,8 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import javax.xml.parsers.ParserConfigurationException; + import org.apache.poi.ooxml.POIXMLProperties; import org.apache.poi.ooxml.POIXMLProperties.CoreProperties; import org.apache.poi.ooxml.POIXMLProperties.CustomProperties; @@ -34,12 +35,15 @@ import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.apache.poi.ooxml.util.SAXHelper; +import org.apache.poi.util.XMLHelper; import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler; -import org.apache.poi.xssf.model.*; +import org.apache.poi.xssf.model.Comments; +import org.apache.poi.xssf.model.SharedStrings; +import org.apache.poi.xssf.model.Styles; +import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.usermodel.XSSFComment; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSimpleShape; @@ -244,7 +248,7 @@ public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor InputSource sheetSource = new InputSource(sheetInputStream); try { - XMLReader sheetParser = SAXHelper.newXMLReader(); + XMLReader sheetParser = XMLHelper.newXMLReader(); ContentHandler handler = new XSSFSheetXMLHandler( styles, comments, strings, sheetContentsExtractor, formatter, formulasNotResults); sheetParser.setContentHandler(handler); diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java index e870349b4d..3904b9fd19 100644 --- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java +++ b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java @@ -28,7 +28,6 @@ import java.util.Locale; import java.util.Map; import java.util.Vector; -import javax.xml.XMLConstants; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; @@ -40,12 +39,12 @@ import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.apache.poi.ooxml.util.DocumentHelper; -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.util.LocaleUtil; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; +import org.apache.poi.util.XMLHelper; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFMap; import org.apache.poi.xssf.usermodel.XSSFRow; @@ -225,7 +224,7 @@ public class XSSFExportToXml implements Comparator<String>{ //Output the XML //set up a transformer - Transformer trans = TransformerHelper.getFactory().newTransformer(); + Transformer trans = XMLHelper.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.ENCODING, encoding); @@ -250,10 +249,7 @@ public class XSSFExportToXml implements Comparator<String>{ @SuppressWarnings({"squid:S2755"}) private boolean isValid(Document xml) throws SAXException{ try { - SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - trySet(XMLConstants.FEATURE_SECURE_PROCESSING, (n) -> factory.setFeature(n, true)); - trySet(XMLConstants.ACCESS_EXTERNAL_DTD, (n) -> factory.setProperty(n,"")); - trySet(XMLConstants.ACCESS_EXTERNAL_SCHEMA, (n) -> factory.setProperty(n,"")); + SchemaFactory factory = XMLHelper.getSchemaFactory(); Source source = new DOMSource(map.getSchema()); Schema schema = factory.newSchema(source); @@ -407,7 +403,7 @@ public class XSSFExportToXml implements Comparator<String>{ String[] rightTokens = rightXpath.split("/"); String samePath = ""; - int minLength = leftTokens.length< rightTokens.length? leftTokens.length : rightTokens.length; + int minLength = Math.min(leftTokens.length, rightTokens.length); Node localComplexTypeRootNode = xmlSchema; diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java index 36a3840223..2ba065b766 100644 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java +++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBuiltinTableStyle.java @@ -25,22 +25,24 @@ import java.nio.charset.StandardCharsets; import java.util.EnumMap; import java.util.Map; -import org.apache.poi.ooxml.util.TransformerHelper; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.poi.ooxml.util.DocumentHelper; import org.apache.poi.ss.usermodel.DifferentialStyleProvider; import org.apache.poi.ss.usermodel.TableStyle; import org.apache.poi.ss.usermodel.TableStyleType; -import org.apache.poi.ooxml.util.DocumentHelper; import org.apache.poi.util.IOUtils; +import org.apache.poi.util.XMLHelper; import org.apache.poi.xssf.model.StylesTable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import javax.xml.transform.*; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - /** * Table style names defined in the OOXML spec. * The actual styling is defined in presetTableStyles.xml @@ -440,9 +442,8 @@ public enum XSSFBuiltinTableStyle { } private static String writeToString(Node node) throws IOException, TransformerException { - TransformerFactory tf = TransformerHelper.getFactory(); try (StringWriter sw = new StringWriter()){ - Transformer transformer = tf.newTransformer(); + Transformer transformer = XMLHelper.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), new StreamResult(sw)); return sw.toString(); |