|
| 1 | +package tools.jackson.dataformat.xml.dos; |
| 2 | + |
| 3 | +import tools.jackson.core.JsonParser; |
| 4 | +import tools.jackson.core.StreamReadConstraints; |
| 5 | +import tools.jackson.core.exc.StreamConstraintsException; |
| 6 | +import tools.jackson.dataformat.xml.XmlFactory; |
| 7 | +import tools.jackson.dataformat.xml.XmlMapper; |
| 8 | +import tools.jackson.dataformat.xml.XmlTestBase; |
| 9 | + |
| 10 | +public class TokenCountTest extends XmlTestBase |
| 11 | +{ |
| 12 | + final XmlMapper XML_MAPPER; |
| 13 | + { |
| 14 | + final XmlFactory factory = XmlFactory.builder() |
| 15 | + // token count is only checked when maxTokenCount is set |
| 16 | + .streamReadConstraints(StreamReadConstraints.builder() |
| 17 | + .maxTokenCount(1000) |
| 18 | + .build()) |
| 19 | + .build(); |
| 20 | + XML_MAPPER = mapperBuilder(factory).build(); |
| 21 | + } |
| 22 | + |
| 23 | + public void testTokenCount10() throws Exception |
| 24 | + { |
| 25 | + final String XML = createDeepNestedDoc(10); |
| 26 | + try (JsonParser p = XML_MAPPER.createParser(XML)) { |
| 27 | + while (p.nextToken() != null) { } |
| 28 | + assertEquals(31, p.currentTokenCount()); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + public void testTokenCount100() throws Exception |
| 33 | + { |
| 34 | + final String XML = createDeepNestedDoc(100); |
| 35 | + try (JsonParser p = XML_MAPPER.createParser(XML)) { |
| 36 | + while (p.nextToken() != null) { } |
| 37 | + assertEquals(301, p.currentTokenCount()); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + public void testDeepDoc() throws Exception |
| 42 | + { |
| 43 | + final String XML = createDeepNestedDoc(1000); |
| 44 | + try (JsonParser p = XML_MAPPER.createParser(XML)) { |
| 45 | + while (p.nextToken() != null) { } |
| 46 | + fail("expected StreamReadException"); |
| 47 | + } catch (StreamConstraintsException e) { |
| 48 | + assertTrue(e.getMessage().contains("Token count (1001) exceeds the maximum allowed")); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private String createDeepNestedDoc(final int depth) { |
| 53 | + StringBuilder sb = new StringBuilder(); |
| 54 | + sb.append("<a>"); |
| 55 | + for (int i = 0; i < depth; i++) { |
| 56 | + sb.append("<a>"); |
| 57 | + } |
| 58 | + sb.append("a"); |
| 59 | + for (int i = 0; i < depth; i++) { |
| 60 | + sb.append("</a>"); |
| 61 | + } |
| 62 | + sb.append("</a>"); |
| 63 | + return sb.toString(); |
| 64 | + } |
| 65 | +} |
0 commit comments