cucumber.table.TableConverter Maven / Gradle / Ivy
package cucumber.table;
import com.thoughtworks.xstream.XStream;
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.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.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static gherkin.util.FixJava.map;
public class TableConverter {
private final XStream xStream;
public TableConverter(XStream xStream) {
this.xStream = xStream;
}
/**
* 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 {
return (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")));
}
}
/**
* 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) {
DataTableWriter writer;
if (isListOfListOfSingleValue(objects)) {
objects = wrapLists((List>) objects);
writer = new ListOfListOfSingleValueWriter(this);
} else {
writer = new ListOfObjectWriter(this);
}
xStream.marshal(objects, writer);
return writer.getDataTable();
}
// This is a hack to prevent XStream from outputting weird-looking "XML" for Arrays.asList() - created lists.
private List> wrapLists(List> lists) {
List> result = new ArrayList>();
for (List> list : lists) {
List> resultList = new ArrayList