All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.simpleflatmapper.map.mapper.DynamicSourceFieldMapper Maven / Gradle / Ivy

Go to download

Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.

There is a newer version: 9.0.2
Show newest version
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 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 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;
	}


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy