cucumber.table.TableConverter Maven / Gradle / Ivy
package cucumber.table;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import cucumber.runtime.CucumberException;
import cucumber.runtime.converters.LocalizedXStreams;
import cucumber.table.xstream.DataTableWriter;
import cucumber.table.xstream.ListOfListOfSingleValueReader;
import cucumber.table.xstream.ListOfListOfSingleValueWriter;
import cucumber.table.xstream.ListOfMapReader;
import cucumber.table.xstream.ListOfObjectReader;
import cucumber.table.xstream.ListOfObjectWriter;
import gherkin.util.Mapper;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static gherkin.util.FixJava.map;
public class TableConverter {
private final LocalizedXStreams.LocalizedXStream xStream;
private final String dateFormat;
public TableConverter(LocalizedXStreams.LocalizedXStream xStream, String dateFormat) {
this.xStream = xStream;
this.dateFormat = dateFormat;
}
/**
* Converts a DataTable to a List of objects.
*/
public List toList(Type itemType, DataTable dataTable) {
HierarchicalStreamReader reader;
ensureNotNonGenericMap(itemType);
Class listOfListType = listOfListType(itemType);
if (listOfListType != null) {
reader = new ListOfListOfSingleValueReader(listOfListType, dataTable.cells(0));
} else if (isMapOfStringToStringAssignable(itemType)) {
reader = new ListOfMapReader(dataTable.topCells(), dataTable.cells(1));
} else {
reader = new ListOfObjectReader(itemType, convertedAttributeNames(dataTable), dataTable.cells(1));
}
try {
xStream.setDateFormat(dateFormat);
return Collections.unmodifiableList((List) xStream.unmarshal(reader));
} catch (AbstractReflectionConverter.UnknownFieldException e) {
throw new CucumberException(e.getShortMessage());
} catch (ConversionException e) {
throw new CucumberException(String.format("Can't assign null value to one of the primitive fields in %s. Please use boxed types.", e.get("class")));
} finally {
xStream.unsetDateFormat();
}
}
/**
* Converts a List of objects to a DataTable.
*
* @param objects the objects to convert
* @param columnNames an explicit list of column names (currently not used)
* @return a DataTable
*/
public DataTable toTable(List> objects, String... columnNames) {
// Need to wrap the list to be sure xStream behaves well
// It doesn't like unmodifiable lists etc.
objects = new ArrayList