io.magentys.cinnamon.webdriver.elements.ColumnHeadingToClassFieldMappingAdapter Maven / Gradle / Ivy
package io.magentys.cinnamon.webdriver.elements;
import io.magentys.cinnamon.converter.CamelCaseFieldNameConverter;
import io.magentys.cinnamon.converter.CollectionsToMapConverter;
import io.magentys.cinnamon.converter.ListConverter;
import io.magentys.cinnamon.converter.MapToObjectReflectionConverter;
import io.magentys.cinnamon.webdriver.elements.Table.RowAdapter;
import org.openqa.selenium.WebElement;
import java.util.List;
import java.util.Map;
import static io.magentys.cinnamon.webdriver.elements.WebElementConverter.elementConverter;
/**
* Adapter to convert a row of cells into an object based perform the column headings.
*
* Each column heading shall be converted into a camel case field name. The given AdaptedType should contain String
* fields for each of the converted column headers. Any converted field names not found shall be ignored. The conversion
* process uses reflection to set the properties.
*/
final class ColumnHeadingToClassFieldMappingAdapter implements RowAdapter {
private final Class type;
private final ListConverter columnHeaderToFieldNameConverter;
private List fieldNames;
ColumnHeadingToClassFieldMappingAdapter(final Class type) {
this.type = type;
columnHeaderToFieldNameConverter = new ListConverter<>(new CamelCaseFieldNameConverter());
}
@Override
public AdaptedType adapt(final List columnHeaderElements, final List cells) {
convertColumnHeadersOnceOnly(columnHeaderElements);
final List cellTexts = elementConverter().getTextsFrom(cells);
final Map map = new CollectionsToMapConverter().convert(fieldNames, cellTexts);
final MapToObjectReflectionConverter converter = new MapToObjectReflectionConverter<>(type);
return converter.convert(map);
}
private void convertColumnHeadersOnceOnly(final List columnHeaderElements) {
// Lazily convert the column headers - they should always be the same
if (fieldNames == null) {
final List columnHeaders = elementConverter().getTextsFrom(columnHeaderElements);
fieldNames = columnHeaderToFieldNameConverter.convert(columnHeaders);
}
}
}