Skip to content

Instantly share code, notes, and snippets.

@stevenschlansker
Created May 4, 2016 00:05
Show Gist options
  • Save stevenschlansker/49563f1f57e9e429e485e3515eefc56b to your computer and use it in GitHub Desktop.
Save stevenschlansker/49563f1f57e9e429e485e3515eefc56b to your computer and use it in GitHub Desktop.
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class EclipseInference {
private final List<RowMapperFactory> rowFactories = new CopyOnWriteArrayList<>();
private final ConcurrentHashMap<Type, RowMapper<?>> rowCache = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
public Optional<RowMapper<?>> findRowMapperFor(Type type) {
return Optional.ofNullable(rowCache.computeIfAbsent(type, t ->
findFirstPresent(
() -> rowFactories.stream()
.flatMap(factory -> toStream(factory.build(t)))
.findFirst(),
() -> findColumnMapperFor(t)
.map(SingleColumnMapper::new))
.orElse(null)));
}
private Optional<ColumnMapper<?>> findColumnMapperFor(Type t) {
return Optional.empty();
}
@SafeVarargs
static <T> Optional<T> findFirstPresent(Supplier<Optional<T>>... suppliers) {
return Stream.of(suppliers)
.flatMap(supplier -> toStream(supplier.get()))
.findFirst();
}
static <T> Stream<T> toStream(Optional<T> optional) {
return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
}
}
class SingleColumnMapper<T> implements RowMapper<T> {
SingleColumnMapper(ColumnMapper<T> mapper) {
}
@Override
public T map(ResultSet r) {
return null;
}
}
@FunctionalInterface
interface RowMapper<T>
{
T map(ResultSet r);
}
@FunctionalInterface
interface ColumnMapper<T>
{
T map(ResultSet r, int columnNumber) throws SQLException;
}
@FunctionalInterface
interface RowMapperFactory
{
Optional<RowMapper<?>> build(Type type);
}
@FunctionalInterface
interface ColumnMapperFactory
{
Optional<ColumnMapper<?>> build(Type type);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment