Skip to content

Commit

Permalink
Expose CSVParser with builder
Browse files Browse the repository at this point in the history
  • Loading branch information
seadowg committed Aug 16, 2024
1 parent 807a5e5 commit 871b885
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,31 +1,26 @@
package org.javarosa.core.model.instance;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.input.BOMInputStream;
import org.javarosa.core.model.data.UncastData;
import org.javarosa.xform.parse.ExternalInstanceParser;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class CsvExternalInstance implements ExternalInstanceParser.FileInstanceParser {

public TreeElement parse(@NotNull String instanceId, @NotNull String path) throws IOException {
final TreeElement root = new TreeElement("root", 0);
root.setInstanceName(instanceId);

final CSVFormat csvFormat = CSVFormat.DEFAULT
.withDelimiter(getDelimiter(path))
.withFirstRecordAsHeader();
Reader reader = new InputStreamReader(new BOMInputStream(new FileInputStream(path)));
try (final CSVParser csvParser = new CSVParser(reader, csvFormat)) {
try (
final CSVParser csvParser = new SecondaryInstanceCSVParserBuilder()
.path(path)
.build()
) {
final String[] fieldNames = csvParser.getHeaderMap().keySet().toArray(new String[0]);
int multiplicity = 0;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package org.javarosa.core.model.instance;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.io.input.BOMInputStream;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class SecondaryInstanceCSVParserBuilder {

private String path;

public SecondaryInstanceCSVParserBuilder path(String path) {
this.path = path;
return this;
}

public CSVParser build() throws IOException {
final CSVFormat csvFormat = CSVFormat.DEFAULT
.withDelimiter(getDelimiter(path))
.withFirstRecordAsHeader();
Reader reader = new InputStreamReader(new BOMInputStream(new FileInputStream(path)));
return new CSVParser(reader, csvFormat);
}

private static char getDelimiter(String path) throws IOException {
char delimiter = ',';
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String header = reader.readLine();

if (header.contains(";")) {
delimiter = ';';
}
}
return delimiter;
}
}

0 comments on commit 871b885

Please sign in to comment.