Skip to content
This repository has been archived by the owner on Jan 22, 2019. It is now read-only.

Commit

Permalink
Merge pull request #129 from ansell/issue-128-headers
Browse files Browse the repository at this point in the history
Fix issue #128 headers are not written if no rows are written
  • Loading branch information
cowtowncoder authored Aug 25, 2016
2 parents f0e663e + fa79ad4 commit 8c7213a
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,12 @@ public void close() throws IOException

// Let's mark row as closed, if we had any...
finishRow();

// Write the header if necessary, occurs when no rows written
if (_handleFirstLine) {
_handleFirstLine();
}

_writer.close(_ioContext.isResourceManaged() || isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.fasterxml.jackson.dataformat.csv.ser;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.SequenceWriter;
import com.fasterxml.jackson.dataformat.csv.*;

// Tests for verifying that headers are emitted
public class HeaderWriteTest extends ModuleTestBase
{
/*
/**********************************************************************
/* Test methods
/**********************************************************************
*/

private final CsvMapper MAPPER = mapperForCsv();

public void testNoLines() throws Exception
{
List<String> headers = Arrays.asList("TestHeader1", "TestHeader2");
List<List<String>> dataSource = Arrays.asList();
String result = runTest(headers, dataSource);

assertEquals("Headers should have been written even with no other data", "TestHeader1,TestHeader2\n", result);
}

public void testOneLine() throws Exception
{
List<String> headers = Arrays.asList("TestHeader1", "TestHeader2");
List<List<String>> dataSource = Arrays.asList(Arrays.asList("TestValue1", "TestValue2"));
String result = runTest(headers, dataSource);

assertEquals("Headers should have been written before line", "TestHeader1,TestHeader2\nTestValue1,TestValue2\n", result);
}

private String runTest(List<String> headers, List<List<String>> dataSource) throws IOException
{
StringWriter writer = new StringWriter();

CsvSchema.Builder builder = CsvSchema.builder();
for (String nextHeader : headers) {
builder = builder.addColumn(nextHeader);
}

CsvSchema schema = builder.setUseHeader(true).build();
try (SequenceWriter csvWriter = MAPPER.writerWithDefaultPrettyPrinter()
.with(schema)
.forType(List.class)
.writeValues(writer);) {
for(List<String> nextRow : dataSource) {
csvWriter.write(nextRow);
}
}

return writer.toString();
}
}

0 comments on commit 8c7213a

Please sign in to comment.