org.simpleflatmapper.map.mapper.DynamicSourceFieldMapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sfm-map Show documentation
Show all versions of sfm-map Show documentation
Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.
package org.simpleflatmapper.map.mapper;
import org.simpleflatmapper.map.ContextualSourceFieldMapper;
import org.simpleflatmapper.map.FieldKey;
import org.simpleflatmapper.map.MappingContext;
import org.simpleflatmapper.map.MappingException;
import org.simpleflatmapper.util.ErrorHelper;
import org.simpleflatmapper.util.UnaryFactory;
import org.simpleflatmapper.util.UnaryFactoryWithException;
public class DynamicSourceFieldMapper, E extends Exception> implements ContextualSourceFieldMapper {
private final MapperCache> mapperCache;
private final UnaryFactory, ContextualSourceFieldMapper> mapperFactory;
private final UnaryFactoryWithException, E> mapperKeyFromRow;
public DynamicSourceFieldMapper(
UnaryFactory,ContextualSourceFieldMapper> mapperFactory,
UnaryFactoryWithException, E> mapperKeyFromRow,
MapperKeyComparator keyComparator) {
this.mapperFactory = mapperFactory;
this.mapperKeyFromRow = mapperKeyFromRow;
this.mapperCache = new MapperCache>(keyComparator);
}
@Override
public T map(ROW row) throws MappingException {
try {
return getMapperFromRow(row).map(row);
} catch(Exception e) {
return ErrorHelper.rethrow(e);
}
}
@Override
public final T map(ROW row, MappingContext super ROW> context) throws MappingException {
try {
return getMapperFromRow(row).map(row, context);
} catch(Exception e) {
return ErrorHelper.rethrow(e);
}
}
@Override
public void mapTo(ROW row, T target, MappingContext super ROW> context) throws Exception {
try {
getMapperFromRow(row).mapTo(row, target,context);
} catch(Exception e) {
ErrorHelper.rethrow(e);
}
}
@Override
public String toString() {
return "DynamicMapper{mapperFactory=" + mapperFactory
+ ", " + mapperCache +
'}';
}
private ContextualSourceFieldMapper getMapperFromRow(ROW row) throws E {
return getMapper(mapperKeyFromRow.newInstance(row));
}
public ContextualSourceFieldMapper getMapper(MapperKey key) {
ContextualSourceFieldMapper mapper = mapperCache.get(key);
if (mapper == null) {
mapper = mapperFactory.newInstance(key);
mapperCache.add(key, mapper);
}
return mapper;
}
}