From ebc8975efd78c7f832068d7e0ef892083c99ec35 Mon Sep 17 00:00:00 2001 From: Shay Banon Date: Wed, 6 Nov 2013 01:10:58 +0100 Subject: [PATCH] NPE when closing XContentBuilder and using 'pretty' query parameter fixes #4100 --- .../xcontent/json/JsonXContentGenerator.java | 3 +++ .../builder/XContentBuilderTests.java | 20 ++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/elasticsearch/common/xcontent/json/JsonXContentGenerator.java b/src/main/java/org/elasticsearch/common/xcontent/json/JsonXContentGenerator.java index aa0bf321b3c..5e4fbfc5f5d 100644 --- a/src/main/java/org/elasticsearch/common/xcontent/json/JsonXContentGenerator.java +++ b/src/main/java/org/elasticsearch/common/xcontent/json/JsonXContentGenerator.java @@ -327,6 +327,9 @@ public class JsonXContentGenerator implements XContentGenerator { @Override public void close() throws IOException { + if (generator.isClosed()) { + return; + } if (writeLineFeedAtEnd) { flush(); generator.writeRaw(LF); diff --git a/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java b/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java index b70028a13af..c8bd9b2a1f8 100644 --- a/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java +++ b/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java @@ -33,7 +33,6 @@ import java.util.*; import static org.elasticsearch.common.xcontent.XContentBuilder.FieldCaseConversion.CAMELCASE; import static org.elasticsearch.common.xcontent.XContentBuilder.FieldCaseConversion.UNDERSCORE; -import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; /** @@ -41,6 +40,25 @@ import static org.hamcrest.Matchers.equalTo; */ public class XContentBuilderTests extends ElasticsearchTestCase { + @Test + public void testPrettyWithLfAtEnd() throws Exception { + FastCharArrayWriter writer = new FastCharArrayWriter(); + XContentGenerator generator = XContentFactory.xContent(XContentType.JSON).createGenerator(writer); + generator.usePrettyPrint(); + generator.usePrintLineFeedAtEnd(); + + generator.writeStartObject(); + generator.writeStringField("test", "value"); + generator.writeEndObject(); + generator.flush(); + + generator.close(); + // double close, and check there is no error... + generator.close(); + + assertThat(writer.unsafeCharArray()[writer.size() - 1], equalTo('\n')); + } + @Test public void verifyReuseJsonGenerator() throws Exception { FastCharArrayWriter writer = new FastCharArrayWriter();