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();