Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support @CsvBindByName in new strategy #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.joehxblog.opencsv;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.RecordComponent;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.opencsv.exceptions.CsvBeanIntrospectionException;
import com.opencsv.exceptions.CsvChainedException;
import com.opencsv.exceptions.CsvConstraintViolationException;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvFieldAssignmentException;
import com.opencsv.exceptions.CsvRuntimeException;

public class AnnotatedRecordMappingStrategy<T extends Record> extends HeaderColumnNameMappingStrategy<T> {

public AnnotatedRecordMappingStrategy(Class<T> type) {
setType(type);
}

@Override
public T populateNewBean(String[] line) throws CsvBeanIntrospectionException, CsvFieldAssignmentException, CsvChainedException {
RecordComponent[] recordComponents = type.getRecordComponents();
if (recordComponents.length != line.length) {
throw new CsvRuntimeException("Mismatch between line values and record components");
}

Map<String, Object> valuesByRecordComponentName = createValuesMap(line);
Object[] initArgs = Stream.of(recordComponents)
.map(recordComponent -> valuesByRecordComponentName.get(recordComponent.getName()))
.toArray();

try {
Class<?>[] array = Arrays.stream(recordComponents).map(RecordComponent::getType).toArray(Class[]::new);
return type.getConstructor(array).newInstance(initArgs);
}
catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new CsvRuntimeException("Error creating instance of record", e);
}
}

private Map<String, Object> createValuesMap(String[] line) throws CsvConstraintViolationException, CsvDataTypeMismatchException {
Map<String, Object> valuesByRecordComponentName = new HashMap<>();

for (int i = 0; i < line.length; i++) {
Field field = findField(i).getField();
valuesByRecordComponentName.put(
field.getName(),
determineConverter(field, field.getType(), null, null, null).convertToRead(line[i]));
}

return valuesByRecordComponentName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.joehxblog.opencsv;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;

import org.junit.jupiter.api.Test;

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;

class AnnotatedRecordMappingStrategyTest {

public record TestRecord(@CsvBindByName(column = "my_str") String string,
@CsvBindByName(column = "my_int") int integer) {}

@Test
void testParse() throws IOException {
StringReader stringReader = new StringReader("my_int,my_str\n123,hello_world");
CSVReader csvReader = new CSVReader(stringReader);

List<TestRecord> actualList = new CsvToBeanBuilder<TestRecord>(csvReader)
.withMappingStrategy(new AnnotatedRecordMappingStrategy<>(TestRecord.class))
.build()
.parse();

csvReader.close();

List<TestRecord> expectedList = List.of(new TestRecord("hello_world", 123));
assertEquals(expectedList, actualList);
}

@Test
void testWrite() throws Exception {
StringWriter stringWriter = new StringWriter();

new StatefulBeanToCsvBuilder<TestRecord>(stringWriter)
.withQuotechar('\'')
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withMappingStrategy(new AnnotatedRecordMappingStrategy<>(TestRecord.class))
.build()
.write(List.of(new TestRecord("one", 1)));

assertEquals("'MY_INT','MY_STR'\n'1','one'\n", stringWriter.toString());
}

@Test
void testWriteThenRead() throws Exception {
// Read
StringWriter stringWriter = new StringWriter();
StatefulBeanToCsv<TestRecord> csvWriter = new StatefulBeanToCsvBuilder<TestRecord>(stringWriter)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withMappingStrategy(new AnnotatedRecordMappingStrategy<>(TestRecord.class))
.build();

List<TestRecord> originalList = List.of(new TestRecord("one", 1));
csvWriter.write(originalList);

// Write
CSVReader csvReader = new CSVReader(new StringReader(stringWriter.toString()));
CsvToBeanBuilder<TestRecord> csvToBeanBuilder = new CsvToBeanBuilder<TestRecord>(csvReader)
.withType(TestRecord.class)
.withMappingStrategy(new AnnotatedRecordMappingStrategy<>(TestRecord.class));

List<TestRecord> actualList = csvToBeanBuilder.build().parse();
assertEquals(originalList, actualList);

csvReader.close();
}
}