Skip to content

Commit

Permalink
Refactor CSV quoting and escaping of strings
Browse files Browse the repository at this point in the history
Add tests
  • Loading branch information
breakbusyloop committed Dec 14, 2019
1 parent 34241ec commit 2c16a46
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.odk.collect.android.utilities;

import org.jetbrains.annotations.Contract;

public class CSVUtils {

private CSVUtils() {
Expand All @@ -9,11 +11,32 @@ private CSVUtils() {
/**
* Escapes quotes and then wraps in quotes for output to CSV.
*/
@Contract("null -> null")
public static String getEscapedValueForCsv(String value) {
if (value == null) {
return null;
}

if (value.contains("\"")) {
value = value.replaceAll("\"", "\"\"");
value = escapeDoubleQuote(value);
}

return quoteString(value);
}

@Contract("null -> null; !null -> !null")
public static String escapeDoubleQuote(String value) {
if (value == null) {
return null;
}
return value.replaceAll("\"", "\"\"");
}

@Contract(value = "null -> null; !null -> !null", pure = true)
public static String quoteString(String value) {
if (value == null) {
return null;
}
return "\"" + value + "\"";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package org.odk.collect.android.utilities;

import org.junit.Assert;
import org.junit.Test;

public class CSVUtilsTest {
@Test
public void testEscapeDoubleQuote() {
Assert.assertNull(CSVUtils.escapeDoubleQuote(null));
Assert.assertEquals("", CSVUtils.escapeDoubleQuote(""));
Assert.assertEquals("no quotes", CSVUtils.escapeDoubleQuote("no quotes"));
Assert.assertEquals("string with \"\"quotes\"\"", CSVUtils.escapeDoubleQuote("string with \"quotes\""));
}

@Test
public void testQuoteString() {
Assert.assertNull(CSVUtils.quoteString(null));
Assert.assertEquals("\"\"", CSVUtils.quoteString(""));
Assert.assertEquals("\"string\"", CSVUtils.quoteString("string"));
Assert.assertEquals("\"string with \"quotes\"\"", CSVUtils.quoteString("string with \"quotes\""));
}

@Test
public void testGetEscapedValueForCsv() {
Assert.assertNull(CSVUtils.getEscapedValueForCsv(null));
Assert.assertEquals("\"\"", CSVUtils.getEscapedValueForCsv(""));
Assert.assertEquals("\"string\"", CSVUtils.getEscapedValueForCsv("string"));
Assert.assertEquals("\"string with \"\"quotes\"\"\"", CSVUtils.getEscapedValueForCsv("string with \"quotes\""));
}
}

0 comments on commit 2c16a46

Please sign in to comment.