Improve comment parsing in DTD/XSD detection algorithm

Prior to this commit, XmlValidationModeDetector did not properly parse
all categories of comments (described below). When such categories of
comments were encountered XmlValidationModeDetector may have
incorrectly detected that an XML file used a DTD when it used an XSD,
or vice versa.

This commit revises the parsing algorithm in XmlValidationModeDetector
so that multi-line comments and multiple comments on a single line are
properly recognized.

Specifically, with this commit the following categories of comments are
now handled properly.

- Multiple comments on a single line
- Multi-line comment: beginning on one line and then ending on another
  line with an additional comment following on that same line.
- Multi-line comment: beginning at the end of XML content on one line
  and then spanning multiple lines.

Closes gh-27915
This commit is contained in:
Sam Brannen
2022-01-13 14:44:05 +01:00
parent 9e8b6feb54
commit 4b1b25496b
8 changed files with 75 additions and 13 deletions

View File

@@ -24,6 +24,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.util.xml.XmlValidationModeDetector.VALIDATION_DTD;
import static org.springframework.util.xml.XmlValidationModeDetector.VALIDATION_XSD;
/**
* Unit tests for {@link XmlValidationModeDetector}.
@@ -37,12 +38,29 @@ class XmlValidationModeDetectorTests {
@ParameterizedTest
@ValueSource(strings = { "dtdWithTrailingComment.xml", "dtdWithLeadingComment.xml", "dtdWithCommentOnNextLine.xml",
"dtdWithMultipleComments.xml" })
@ValueSource(strings = {
"dtdWithNoComments.xml",
"dtdWithLeadingComment.xml",
"dtdWithTrailingComment.xml",
"dtdWithTrailingCommentAcrossMultipleLines.xml",
"dtdWithCommentOnNextLine.xml",
"dtdWithMultipleComments.xml"
})
void dtdDetection(String fileName) throws Exception {
assertValidationMode(fileName, VALIDATION_DTD);
}
@ParameterizedTest
@ValueSource(strings = {
"xsdWithNoComments.xml",
"xsdWithMultipleComments.xml",
"xsdWithDoctypeInComment.xml",
"xsdWithDoctypeInOpenCommentWithAdditionalCommentOnSameLine.xml"
})
void xsdDetection(String fileName) throws Exception {
assertValidationMode(fileName, VALIDATION_XSD);
}
private void assertValidationMode(String fileName, int expectedValidationMode) throws IOException {
try (InputStream inputStream = getClass().getResourceAsStream(fileName)) {