From bcd3785d7d3e5fe9eb9c92cfc5e1abc0a21b6c65 Mon Sep 17 00:00:00 2001 From: Dominik Stadler Date: Mon, 30 Jan 2023 12:19:37 +0000 Subject: [PATCH] Use an error-handler to use logging also for XML parsing errors Otherwise this output is done to stdout/stderr which we would like to avoid. Keep the format as one line and do not include a full exception stacktrace to not introduce lots of exception-stacktraces for some slightly broken input files git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1907108 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/poi/util/XMLHelper.java | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/poi/src/main/java/org/apache/poi/util/XMLHelper.java b/poi/src/main/java/org/apache/poi/util/XMLHelper.java index 5eb218ecd4..7ad8e3f0b0 100644 --- a/poi/src/main/java/org/apache/poi/util/XMLHelper.java +++ b/poi/src/main/java/org/apache/poi/util/XMLHelper.java @@ -47,6 +47,7 @@ import javax.xml.transform.TransformerFactory; import javax.xml.validation.SchemaFactory; import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogBuilder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.xml.sax.ErrorHandler; @@ -139,7 +140,7 @@ public final class XMLHelper { try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver(XMLHelper::ignoreEntity); - documentBuilder.setErrorHandler(new DocHelperErrorHandler()); + documentBuilder.setErrorHandler(new DocHelperErrorHandler(true)); return documentBuilder; } catch (ParserConfigurationException e) { throw new IllegalStateException("cannot create a DocumentBuilder", e); @@ -176,6 +177,7 @@ public final class XMLHelper { public static XMLReader newXMLReader() throws SAXException, ParserConfigurationException { XMLReader xmlReader = saxFactory.newSAXParser().getXMLReader(); xmlReader.setEntityResolver(XMLHelper::ignoreEntity); + xmlReader.setErrorHandler(new DocHelperErrorHandler(false)); trySet(xmlReader::setFeature, FEATURE_SECURE_PROCESSING, true); trySet(xmlReader::setFeature, FEATURE_EXTERNAL_ENTITIES, false); Object manager = getXercesSecurityManager(); @@ -309,6 +311,11 @@ public final class XMLHelper { } private static class DocHelperErrorHandler implements ErrorHandler { + private final boolean logException; + + public DocHelperErrorHandler(boolean logException) { + this.logException = logException; + } public void warning(SAXParseException exception) { printError(Level.WARN, exception); @@ -339,7 +346,13 @@ public final class XMLHelper { ':' + ex.getColumnNumber() + ':' + ex.getMessage(); - LOG.atLevel(type).withThrowable(ex).log(message); + LogBuilder builder = LOG.atLevel(type); + + if (logException) { + builder = builder.withThrowable(ex); + } + + builder.log(message); } }