cucumber.table.TableConverter Maven / Gradle / Ivy
package cucumber.table;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.SingleValueConverter;
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;
private final String dateFormat;
public TableConverter(XStream 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));
}
return (List) xStream.unmarshal(reader);
}
/**
* Converts a List of objects to a DataTable.
*
* @param objects the objects to convers
* @return a DataTable
*/
public DataTable toTable(List> objects) {
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
© 2015 - 2024 Weber Informatics LLC | Privacy Policy