Merge pull request #1062 from Fahmida-Hossain-Charu/pr/refactor-cdl-row-serialization

Refactor CDL row serialization for readability
This commit is contained in:
Sean Leary
2026-06-21 07:09:27 -05:00
committed by GitHub
+60 -18
View File
@@ -183,29 +183,71 @@ public class CDL {
sb.append(delimiter);
}
Object object = ja.opt(i);
if (object != null) {
String string = object.toString();
if (!string.isEmpty() && (string.indexOf(delimiter) >= 0 ||
string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
sb.append('"');
int length = string.length();
for (int j = 0; j < length; j += 1) {
char c = string.charAt(j);
if (c >= ' ' && c != '"') {
sb.append(c);
}
}
sb.append('"');
} else {
sb.append(string);
}
}
appendRowValue(sb, object, delimiter);
}
sb.append('\n');
return sb.toString();
}
/**
* Append a single row value, quoting it when required by the delimiter or
* content.
*
* @param sb the destination buffer
* @param object the value to append
* @param delimiter the delimiter used between row values
*/
private static void appendRowValue(StringBuilder sb, Object object, char delimiter) {
if (object == null) {
return;
}
String string = object.toString();
if (shouldQuoteValue(string, delimiter)) {
appendQuotedValue(sb, string);
} else {
sb.append(string);
}
}
/**
* Determine whether a row value should be quoted.
*
* @param value the row value to evaluate
* @param delimiter the delimiter used between row values
* @return {@code true} if the value should be quoted
*/
private static boolean shouldQuoteValue(String value, char delimiter) {
if (value.isEmpty()) {
return false;
}
boolean containsDelimiter = value.indexOf(delimiter) >= 0;
boolean containsNewline = value.indexOf('\n') >= 0;
boolean containsCarriageReturn = value.indexOf('\r') >= 0;
boolean containsNullCharacter = value.indexOf(0) >= 0;
boolean startsWithQuote = value.charAt(0) == '"';
return containsDelimiter || containsNewline || containsCarriageReturn ||
containsNullCharacter || startsWithQuote;
}
/**
* Append a row value surrounded by quotes, omitting characters that should
* not appear inside the quoted value.
*
* @param sb the destination buffer
* @param value the value to append
*/
private static void appendQuotedValue(StringBuilder sb, String value) {
sb.append('"');
int length = value.length();
for (int j = 0; j < length; j += 1) {
char c = value.charAt(j);
if (c >= ' ' && c != '"') {
sb.append(c);
}
}
sb.append('"');
}
/**
* Produce a JSONArray of JSONObjects from a comma delimited text string,
* using the first row as a source of names.