Jackson deserialization for CsvExporter

This commit is contained in:
Antonin Delpeuch 2018-10-23 10:33:37 +01:00
parent 59f322d607
commit 52426b98a3
2 changed files with 38 additions and 9 deletions

View File

@ -43,9 +43,10 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.refine.browsing.Engine;
import com.google.refine.model.Project;
import com.google.refine.util.JSONUtilities;
import com.google.refine.util.ParsingUtilities;
import au.com.bytecode.opencsv.CSVWriter;
@ -62,26 +63,37 @@ public class CsvExporter implements WriterExporter{
public CsvExporter(char separator) {
this.separator = separator;
}
private static class Configuration {
@JsonProperty("separator")
protected String separator = null;
@JsonProperty("lineSeparator")
protected String lineSeparator = CSVWriter.DEFAULT_LINE_END;
@JsonProperty("quoteAll")
protected boolean quoteAll = false;
}
@Override
public void export(Project project, Properties params, Engine engine, final Writer writer)
throws IOException {
String optionsString = (params == null) ? null : params.getProperty("options");
JSONObject options = null;
Configuration options = new Configuration();
if (optionsString != null) {
try {
options = ParsingUtilities.evaluateJsonStringToObject(optionsString);
} catch (JSONException e) {
options = ParsingUtilities.mapper.readValue(optionsString, Configuration.class);
if (options.separator == null) {
options.separator = Character.toString(separator);
}
} catch (IOException e) {
// Ignore and keep options null.
e.printStackTrace();
}
}
final String separator = options == null ? Character.toString(this.separator) :
JSONUtilities.getString(options, "separator", Character.toString(this.separator));
final String lineSeparator = options == null ? CSVWriter.DEFAULT_LINE_END :
JSONUtilities.getString(options, "lineSeparator", CSVWriter.DEFAULT_LINE_END);
final boolean quoteAll = options == null ? false : JSONUtilities.getBoolean(options, "quoteAll", false);
final String separator = options.separator;
final String lineSeparator = options.lineSeparator;
final boolean quoteAll = options.quoteAll;
final boolean printColumnHeader =
(params != null && params.getProperty("printColumnHeader") != null) ?

View File

@ -125,6 +125,23 @@ public class CsvExporterTests extends RefineTest {
verify(options,times(2)).getProperty("printColumnHeader");
}
@Test
public void exportSimpleCsvCustomLineSeparator(){
CreateGrid(2, 2);
when(options.getProperty("options")).thenReturn("{\"lineSeparator\":\"X\"}");
try {
SUT.export(project, options, engine, writer);
} catch (IOException e) {
Assert.fail();
}
Assert.assertEquals(writer.toString(), "column0,column1X" +
"row0cell0,row0cell1X" +
"row1cell0,row1cell1X");
}
@Test
public void exportCsvWithLineBreaks(){