Search in sources :

Example 1 with Unchecked

use of org.jdbi.v3.core.internal.exceptions.Unchecked in project jdbi by jdbi.

the class BuiltInArgumentFactory method build.

@Override
@SuppressWarnings("unchecked")
public Optional<Argument> build(Type expectedType, Object value, ConfigRegistry config) {
    Class<?> expectedClass = getErasedType(expectedType);
    if (value != null && expectedClass == Object.class) {
        expectedClass = value.getClass();
    }
    @SuppressWarnings("rawtypes") ArgBuilder v = BUILDERS.get(expectedClass);
    if (v != null) {
        return Optional.of(v.build(value));
    }
    // Enums must be bound as VARCHAR.
    if (value instanceof Enum) {
        Enum<?> enumValue = (Enum<?>) value;
        return Optional.of(STR_BUILDER.build(enumValue.name()));
    }
    if (value instanceof Optional) {
        Object nestedValue = ((Optional<?>) value).orElse(null);
        Type nestedType = findOptionalType(expectedType, nestedValue);
        return config.get(Arguments.class).findFor(nestedType, nestedValue);
    }
    return value == null ? Optional.of(config.get(Arguments.class).getUntypedNullArgument()) : Optional.empty();
}
Also used : GenericTypes.getErasedType(org.jdbi.v3.core.generic.GenericTypes.getErasedType) Type(java.lang.reflect.Type) Optional(java.util.Optional)

Example 2 with Unchecked

use of org.jdbi.v3.core.internal.exceptions.Unchecked in project jdbi by jdbi.

the class TestGuavaCollectors method testMapCollector.

@SuppressWarnings("unchecked")
private <M extends Map<Long, String>> void testMapCollector(Class<? extends Map> erasedType, GenericType<M> genericType) {
    JdbiCollectors registry = h2Extension.getJdbi().getConfig(JdbiCollectors.class);
    assertThat(registry.findElementTypeFor(genericType.getType())).contains(new GenericType<Map.Entry<Long, String>>() {
    }.getType());
    Collector<Map.Entry<Long, String>, ?, M> collector = (Collector<Map.Entry<Long, String>, ?, M>) registry.findFor(genericType.getType()).orElseThrow(() -> new IllegalStateException("Missing collector for " + genericType));
    M map = Stream.of(entry(1L, "foo"), entry(2L, "bar")).collect(collector);
    assertThat(map).isInstanceOf(erasedType).containsExactly(entry(1L, "foo"), entry(2L, "bar"));
}
Also used : GenericType(org.jdbi.v3.core.generic.GenericType) JdbiCollectors(org.jdbi.v3.core.collector.JdbiCollectors) Collector(java.util.stream.Collector) Map(java.util.Map) BiMap(com.google.common.collect.BiMap) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 3 with Unchecked

use of org.jdbi.v3.core.internal.exceptions.Unchecked in project jdbi by jdbi.

the class TestRegisteredMappers method registerByGenericType.

@Test
public void registerByGenericType() {
    Jdbi db = h2Extension.getJdbi();
    @SuppressWarnings("unchecked") RowMapper<Iterable<Calendar>> mapper = mock(RowMapper.class);
    GenericType<Iterable<Calendar>> iterableOfCalendarType = new GenericType<Iterable<Calendar>>() {
    };
    db.registerRowMapper(iterableOfCalendarType, mapper);
    assertThat(db.getConfig(RowMappers.class).findFor(iterableOfCalendarType)).contains(mapper);
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) GenericType(org.jdbi.v3.core.generic.GenericType) Calendar(java.util.Calendar) Test(org.junit.jupiter.api.Test)

Example 4 with Unchecked

use of org.jdbi.v3.core.internal.exceptions.Unchecked in project jdbi by jdbi.

the class PojoMapper method specialize0.

private Optional<RowMapper<T>> specialize0(StatementContext ctx, List<String> columnNames, List<ColumnNameMatcher> columnNameMatchers, List<String> unmatchedColumns) {
    final List<PropertyData<T>> propList = new ArrayList<>();
    for (PojoProperty<T> property : getProperties(ctx.getConfig()).getProperties().values()) {
        Nested anno = property.getAnnotation(Nested.class).orElse(null);
        if (property.getAnnotation(Unmappable.class).map(Unmappable::value).orElse(false)) {
            continue;
        }
        if (anno == null) {
            String paramName = prefix + getName(property);
            findColumnIndex(paramName, columnNames, columnNameMatchers, () -> debugName(property)).ifPresent(index -> {
                @SuppressWarnings({ "unchecked", "rawtypes" }) ColumnMapper<?> mapper = ctx.findColumnMapperFor(property.getQualifiedType().mapType(GenericTypes::box)).orElseGet(() -> (ColumnMapper) defaultColumnMapper(property));
                propList.add(new PropertyData<>(property, new SingleColumnMapper<>(mapper, index + 1)));
                unmatchedColumns.remove(columnNames.get(index));
            });
        } else {
            String nestedPrefix = prefix + anno.value();
            if (anyColumnsStartWithPrefix(columnNames, nestedPrefix, columnNameMatchers)) {
                nestedMappers.computeIfAbsent(property, d -> createNestedMapper(ctx, d, nestedPrefix)).specialize0(ctx, columnNames, columnNameMatchers, unmatchedColumns).ifPresent(nestedMapper -> propList.add(new PropertyData<>(property, nestedMapper)));
            }
        }
    }
    if (propList.isEmpty() && !columnNames.isEmpty()) {
        return Optional.empty();
    }
    propList.sort(Comparator.comparing(p -> p.propagateNull ? 1 : 0));
    final Optional<String> nullMarkerColumn = Optional.ofNullable(GenericTypes.getErasedType(type).getAnnotation(PropagateNull.class)).map(PropagateNull::value);
    return Optional.of((r, c) -> {
        if (propagateNull(r, nullMarkerColumn)) {
            return null;
        }
        final PojoBuilder<T> pojo = getProperties(c.getConfig()).create();
        for (PropertyData<T> p : propList) {
            Object value = p.mapper.map(r, ctx);
            if (p.propagateNull && (value == null || (p.isPrimitive && r.wasNull()))) {
                return null;
            }
            if (value != null) {
                pojo.set(p.property, value);
            }
        }
        return pojo.build();
    });
}
Also used : PojoProperty(org.jdbi.v3.core.mapper.reflect.internal.PojoProperties.PojoProperty) PropagateNull(org.jdbi.v3.core.mapper.PropagateNull) ReflectionMappers(org.jdbi.v3.core.mapper.reflect.ReflectionMappers) Nested(org.jdbi.v3.core.mapper.Nested) SingleColumnMapper(org.jdbi.v3.core.mapper.SingleColumnMapper) ConfigRegistry(org.jdbi.v3.core.config.ConfigRegistry) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) ColumnName(org.jdbi.v3.core.mapper.reflect.ColumnName) UnableToProduceResultException(org.jdbi.v3.core.result.UnableToProduceResultException) ResultSet(java.sql.ResultSet) Map(java.util.Map) GenericTypes(org.jdbi.v3.core.generic.GenericTypes) RowMapper(org.jdbi.v3.core.mapper.RowMapper) ColumnNameMatcher(org.jdbi.v3.core.mapper.reflect.ColumnNameMatcher) ReflectionMapperUtil.getColumnNames(org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.getColumnNames) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) StatementContext(org.jdbi.v3.core.statement.StatementContext) Unchecked(org.jdbi.v3.core.internal.exceptions.Unchecked) PojoBuilder(org.jdbi.v3.core.mapper.reflect.internal.PojoProperties.PojoBuilder) List(java.util.List) Type(java.lang.reflect.Type) ColumnMapper(org.jdbi.v3.core.mapper.ColumnMapper) ReflectionMapperUtil.findColumnIndex(org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.findColumnIndex) Optional(java.util.Optional) NoSuchMapperException(org.jdbi.v3.core.mapper.NoSuchMapperException) ReflectionMapperUtil.anyColumnsStartWithPrefix(org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.anyColumnsStartWithPrefix) Comparator(java.util.Comparator) Unmappable(org.jdbi.v3.core.annotation.Unmappable) SingleColumnMapper(org.jdbi.v3.core.mapper.SingleColumnMapper) ArrayList(java.util.ArrayList) Nested(org.jdbi.v3.core.mapper.Nested) GenericTypes(org.jdbi.v3.core.generic.GenericTypes) PropagateNull(org.jdbi.v3.core.mapper.PropagateNull)

Example 5 with Unchecked

use of org.jdbi.v3.core.internal.exceptions.Unchecked in project jdbi by jdbi.

the class ResultBearing method collectInto.

/**
 * Collect the results into a container of the given type. A collector
 * must be registered for the container type, which knows the element type
 * for the container. A mapper must be registered for the element type.
 * <p>
 * This method is equivalent to {@code ResultBearing.mapTo(elementType).collect(containerCollector)}.
 * </p>
 *
 * @param containerType the container type into which results will be collected
 * @return a container into which result rows have been collected
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
default Object collectInto(Type containerType) {
    return scanResultSet((rs, ctx) -> {
        Collector collector = ctx.findCollectorFor(containerType).orElseThrow(() -> new NoSuchCollectorException("No collector registered for container type " + containerType));
        Type elementType = ctx.findElementTypeFor(containerType).orElseThrow(() -> new ElementTypeNotFoundException("Unknown element type for container type " + containerType));
        RowMapper<?> mapper = ctx.findMapperFor(elementType).orElseThrow(() -> new NoSuchMapperException("No mapper registered for element type " + elementType));
        return ResultIterable.of(rs, mapper, ctx).collect(collector);
    });
}
Also used : GenericType(org.jdbi.v3.core.generic.GenericType) Type(java.lang.reflect.Type) QualifiedType(org.jdbi.v3.core.qualifier.QualifiedType) ElementTypeNotFoundException(org.jdbi.v3.core.collector.ElementTypeNotFoundException) Collector(java.util.stream.Collector) NoSuchCollectorException(org.jdbi.v3.core.collector.NoSuchCollectorException) NoSuchMapperException(org.jdbi.v3.core.mapper.NoSuchMapperException)

Aggregations

Map (java.util.Map)5 Optional (java.util.Optional)5 Type (java.lang.reflect.Type)4 GenericType (org.jdbi.v3.core.generic.GenericType)4 Comparator (java.util.Comparator)3 Collector (java.util.stream.Collector)3 JdbiCollectors (org.jdbi.v3.core.collector.JdbiCollectors)3 ColumnMapper (org.jdbi.v3.core.mapper.ColumnMapper)3 BiMap (com.google.common.collect.BiMap)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 List (java.util.List)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 PMessage (net.morimekta.providence.PMessage)2 ConfigRegistry (org.jdbi.v3.core.config.ConfigRegistry)2 GenericTypes (org.jdbi.v3.core.generic.GenericTypes)2 Unchecked (org.jdbi.v3.core.internal.exceptions.Unchecked)2