package io.ljunggren.csv.parser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PushbackReader;
import java.io.Reader;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.reflect.FieldUtils;
import io.ljunggren.csv.parser.annotation.CSVColumn;
import io.ljunggren.csv.parser.exception.CsvParseException;
import io.ljunggren.csv.parser.mapper.CatchAllMapper;
import io.ljunggren.csv.parser.mapper.DateMapper;
import io.ljunggren.csv.parser.mapper.MapperChain;
import io.ljunggren.csv.parser.utils.ParserUtils;
/**
* Fluent CSV parser that maps CSV rows to either raw {@code List<String>}
* rows, single-column {@code String} lists, or arbitrary user types whose
* fields are annotated with {@link CSVColumn}.
*
* <p>Typical usage:</p>
* <pre>{@code
* Parser parser = new Parser().firstRowIsHeader().delimiter(',');
* List<MyClass> rows = parser.parse(file, MyClass.class);
* }</pre>
*
* <p><strong>Thread safety:</strong> instances of {@code Parser} are
* <em>not</em> thread-safe. Each thread should construct its own
* {@code Parser}. The {@link #parse(File, Class)} family of methods may
* however be safely invoked sequentially on the same instance.</p>
*/
public class Parser {
private char delimiter = ',';
private boolean firstRowIsHeader;
private Map<String, String> columnMap;
/**
* Set the field delimiter. Defaults to comma.
*
* @param delimiter the character separating columns
* @return this parser for fluent chaining
*/
public Parser delimiter(char delimiter) {
this.delimiter = delimiter;
return this;
}
/**
* Treat the first row of the input as a header row that will be skipped.
*
* @return this parser for fluent chaining
*/
public Parser firstRowIsHeader() {
this.firstRowIsHeader = true;
return this;
}
/**
* Provide a column mapping that translates the {@link CSVColumn} value
* declared on the target POJO to the actual column reference in the CSV
* file. A defensive copy of the supplied map is taken.
*
* @param columnMap source-to-target column mapping; may be {@code null}
* @return this parser for fluent chaining
*/
public Parser columnMap(Map<String, String> columnMap) {
this.columnMap = columnMap == null ? null : new HashMap<>(columnMap);
return this;
}
/**
* @return the configured delimiter
*/
public char getDelimiter() {
return delimiter;
}
/**
* @return whether the first row of the input is treated as a header
*/
public boolean isFirstRowIsHeader() {
return firstRowIsHeader;
}
/**
* @return an unmodifiable view of the configured column map, or {@code null}
* if no map has been set
*/
public Map<String, String> getColumnMap() {
return columnMap == null ? null : Collections.unmodifiableMap(columnMap);
}
/**
* Parse the file as raw rows of strings.
*
* @param file the CSV file to parse; must not be null
* @return a list of rows, each row a list of cell values
* @throws CsvParseException if the file cannot be read or parsed
*/
public List<List<String>> parse(File file) {
Objects.requireNonNull(file, "file must not be null");
try (Reader reader = getReader(file);
CSVParser parser = createCSVParser(reader)) {
return parse(parser);
} catch (IOException e) {
throw new CsvParseException("Failed to read CSV file: " + file, e);
}
}
/**
* Parse the file and map each row to a new instance of {@code clazz}.
*
* <p>If {@code clazz} is {@link String}, returns the values from the
* first column. Otherwise the fields of {@code clazz} that are annotated
* with {@link CSVColumn} are populated.</p>
*
* @param file the CSV file to parse; must not be null
* @param clazz the target type; must not be null and must have an
* accessible no-args constructor (unless it is {@link String})
* @param <T> the target type
* @return the parsed list
* @throws CsvParseException if the file cannot be read, parsed or mapped
*/
public <T> List<T> parse(File file, Class<T> clazz) {
Objects.requireNonNull(file, "file must not be null");
Objects.requireNonNull(clazz, "clazz must not be null");
try (Reader reader = getReader(file);
CSVParser parser = createCSVParser(reader)) {
return generateListFromParser(parser, clazz);
} catch (IOException e) {
throw new CsvParseException("Failed to read CSV file: " + file, e);
} catch (CsvParseException e) {
throw e;
} catch (Exception e) {
throw new CsvParseException("Failed to map CSV rows to " + clazz.getName(), e);
}
}
/**
* Read just the header names from the file. Requires that
* {@link #firstRowIsHeader()} has been set; otherwise an empty list is
* returned.
*
* @param file the CSV file to inspect; must not be null
* @return the header names in declaration order
* @throws CsvParseException if the file cannot be read
*/
public List<String> parseHeaders(File file) {
Objects.requireNonNull(file, "file must not be null");
try (Reader reader = getReader(file);
CSVParser parser = createCSVParser(reader)) {
return parser.getHeaderNames();
} catch (IOException e) {
throw new CsvParseException("Failed to read CSV file: " + file, e);
}
}
private Reader getReader(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
BufferedReader buffered = new BufferedReader(isr);
return stripBom(buffered);
}
/**
* Wrap the supplied reader and discard a leading UTF-8 BOM character
* if one is present. Visible for unit testing.
*/
static Reader stripBom(Reader reader) throws IOException {
PushbackReader pushback = new PushbackReader(reader, 1);
int first = pushback.read();
if (first == -1) {
return pushback;
}
// The UTF-8 BOM decodes as a single character.
if (first != 0xFEFF) {
pushback.unread(first);
}
return pushback;
}
private CSVParser createCSVParser(Reader reader) throws IOException {
CSVFormat format = CSVFormat.DEFAULT.withDelimiter(delimiter);
if (firstRowIsHeader) {
format = format.withFirstRecordAsHeader();
}
return format.parse(reader);
}
private List<List<String>> parse(CSVParser parser) {
List<List<String>> data = new ArrayList<>();
for (CSVRecord csvRecord : parser) {
List<String> rowData = new ArrayList<>(csvRecord.size());
for (String cell : csvRecord) {
rowData.add(cell);
}
data.add(rowData);
}
return data;
}
private <T> List<T> generateListFromParser(CSVParser parser, Class<T> clazz) throws Exception {
if (clazz == String.class) {
return generateFromColumn(parser, clazz, 0);
}
List<T> data = new ArrayList<>();
List<Field> fields = getAnnotatedFields(clazz);
MapperChain mapperChain = buildMapperChain();
for (CSVRecord csvRecord : parser) {
T object = clazz.getDeclaredConstructor().newInstance();
for (Field field : fields) {
String column = getColumnFromField(field);
String mappedColumn = getMappedColumn(column);
Object value = getValueFromRecord(field, csvRecord, mappedColumn, mapperChain);
setValue(field, object, value);
}
data.add(object);
}
return data;
}
@SuppressWarnings("unchecked")
private <T> List<T> generateFromColumn(CSVParser parser, Class<T> clazz, int column) {
if (clazz != String.class) {
throw new CsvParseException(
"generateFromColumn only supports String.class, got " + clazz.getName());
}
List<T> data = new ArrayList<>();
for (CSVRecord csvRecord : parser) {
data.add((T) csvRecord.get(column));
}
return data;
}
private List<Field> getAnnotatedFields(Class<?> clazz) {
return FieldUtils.getFieldsListWithAnnotation(clazz, CSVColumn.class);
}
private String getColumnFromField(Field field) {
return field.getAnnotation(CSVColumn.class).value();
}
private String getMappedColumn(String column) {
if (columnMap == null) {
return column;
}
String mappedColumn = columnMap.get(column);
return mappedColumn == null ? column : mappedColumn;
}
private Object getValueFromRecord(Field field, CSVRecord csvRecord, String column,
MapperChain mapperChain) {
int index = ParserUtils.columnToInt(column);
String value = csvRecord.get(index);
try {
return mapperChain.map(field, value);
} catch (Exception e) {
throw new CsvParseException(
String.format("[Column %s: Row %d] Unable to cast %s to %s",
column, csvRecord.getRecordNumber(), value, field.getType().getName()),
e);
}
}
private void setValue(Field field, Object object, Object value) throws IllegalAccessException {
FieldUtils.writeField(field, object, value, true);
}
private MapperChain buildMapperChain() {
DateMapper head = new DateMapper();
head.nextChain(new CatchAllMapper());
return head;
}
}