org.simpleflatmapper.map.mapper.DiscriminatorMapper 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.
The newest version!
package org.simpleflatmapper.map.mapper;
import org.simpleflatmapper.map.ContextualSourceFieldMapper;
import org.simpleflatmapper.map.MappingException;
import org.simpleflatmapper.map.ConsumerErrorHandler;
import org.simpleflatmapper.map.context.MappingContextFactoryFromRows;
import org.simpleflatmapper.util.Enumerable;
import org.simpleflatmapper.util.Function;
import org.simpleflatmapper.util.Predicate;
import org.simpleflatmapper.util.UnaryFactory;
import java.util.List;
public class DiscriminatorMapper extends AbstractEnumerableDelegateMapper {
private final List> mappers;
private final Function errorConverter;
private final UnaryFactory> rowEnumerableFactory;
public DiscriminatorMapper(List> mappers,
UnaryFactory> rowEnumerableFactory,
Function errorConverter,
ConsumerErrorHandler consumerErrorHandler) {
super(consumerErrorHandler);
this.mappers = mappers;
this.errorConverter = errorConverter;
this.rowEnumerableFactory = rowEnumerableFactory;
}
@Override
protected ContextualSourceFieldMapper getMapper(final ROW row) throws MappingException {
for (PredicatedMapper tm : mappers) {
if (tm.getPredicate().test(row)) {
return tm.getMapper();
}
}
throw new MappingException("No mapper found for " + errorConverter.apply(row));
}
@SuppressWarnings("unchecked")
@Override
public DiscriminatorEnumerable enumerate(ROWS rows) throws EX {
DiscriminatorEnumerable.PredicatedMapperWithContext[] mapperDiscriminators =
new DiscriminatorEnumerable.PredicatedMapperWithContext[this.mappers.size()];
for(int i = 0; i < mapperDiscriminators.length; i++) {
PredicatedMapper predicatedMapper = mappers.get(i);
mapperDiscriminators[i] =
new DiscriminatorEnumerable.PredicatedMapperWithContext(
predicatedMapper.getPredicate(),
predicatedMapper.getMapper(),
predicatedMapper.getMappingContextFactory().newMappingContext(rows));
}
return new DiscriminatorEnumerable(
mapperDiscriminators,
rowEnumerableFactory.newInstance(rows),
errorConverter);
}
public static class PredicatedMapper {
private final Predicate predicate;
private final ContextualSourceFieldMapper mapper;
private final MappingContextFactoryFromRows mappingContextFactory;
public PredicatedMapper(Predicate predicate,
ContextualSourceFieldMapper mapper,
MappingContextFactoryFromRows mappingContextFactory) {
this.predicate = predicate;
this.mapper = mapper;
this.mappingContextFactory = mappingContextFactory;
}
public Predicate getPredicate() {
return predicate;
}
public ContextualSourceFieldMapper getMapper() {
return mapper;
}
public MappingContextFactoryFromRows getMappingContextFactory() {
return mappingContextFactory;
}
}
}