diff --git a/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/ToXmlGenerator.java b/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/ToXmlGenerator.java index 2e5c8a552..886356e12 100644 --- a/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/ToXmlGenerator.java +++ b/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/ToXmlGenerator.java @@ -321,6 +321,11 @@ public JsonGenerator overrideFormatFeatures(int values, int mask) /********************************************************** */ + @Override + public StreamWriteConstraints streamWriteConstraints() { + return _ioContext.streamWriteConstraints(); + } + public ToXmlGenerator enable(Feature f) { _formatFeatures |= f.getMask(); return this; @@ -536,6 +541,7 @@ public final void writeStartArray() throws IOException { _verifyValueWrite("start an array"); _writeContext = _writeContext.createChildArrayContext(); + streamWriteConstraints().validateNestingDepth(_writeContext.getNestingDepth()); if (_cfgPrettyPrinter != null) { _cfgPrettyPrinter.writeStartArray(this); } else { @@ -562,6 +568,7 @@ public final void writeStartObject() throws IOException { _verifyValueWrite("start an object"); _writeContext = _writeContext.createChildObjectContext(); + streamWriteConstraints().validateNestingDepth(_writeContext.getNestingDepth()); if (_cfgPrettyPrinter != null) { _cfgPrettyPrinter.writeStartObject(this); } else { diff --git a/src/test/java/com/fasterxml/jackson/dataformat/xml/ser/dos/CyclicDataSerTest.java b/src/test/java/com/fasterxml/jackson/dataformat/xml/ser/dos/CyclicDataSerTest.java new file mode 100644 index 000000000..7c6be37ed --- /dev/null +++ b/src/test/java/com/fasterxml/jackson/dataformat/xml/ser/dos/CyclicDataSerTest.java @@ -0,0 +1,32 @@ +package com.fasterxml.jackson.dataformat.xml.ser.dos; + +import com.fasterxml.jackson.core.StreamWriteConstraints; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.fasterxml.jackson.dataformat.xml.XmlTestBase; + +import java.util.ArrayList; +import java.util.List; + +/** + * Simple unit tests to verify that we fail gracefully if you attempt to serialize + * data that is cyclic (eg a list that contains itself). + */ +public class CyclicDataSerTest extends XmlTestBase +{ + private final XmlMapper MAPPER = newMapper(); + + public void testListWithSelfReference() throws Exception { + List list = new ArrayList<>(); + list.add(list); + try { + MAPPER.writeValueAsString(list); + fail("expected JsonMappingException"); + } catch (JsonMappingException jmex) { + String exceptionPrefix = String.format("Document nesting depth (%d) exceeds the maximum allowed", + StreamWriteConstraints.DEFAULT_MAX_DEPTH + 1); + assertTrue("JsonMappingException message is as expected?", + jmex.getMessage().startsWith(exceptionPrefix)); + } + } +}