Search in sources :

Example 6 with Unchecked

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

the class AnnotationFactory method create.

public static <T extends Annotation> T create(Class<T> annotationType, Map<String, ?> values) {
    Arrays.stream(annotationType.getDeclaredMethods()).filter(m -> m.getDefaultValue() == null).filter(m -> !values.containsKey(m.getName())).findAny().ifPresent(m -> {
        throw new IllegalArgumentException(String.format("Cannot synthesize annotation @%s from %s.class because it has attribute " + m.getName() + " without a default or specified value", annotationType.getSimpleName(), annotationType.getSimpleName()));
    });
    Class<?>[] interfaces = { annotationType };
    InvocationHandler invocationHandler = getInvocationHandler(annotationType, values);
    @SuppressWarnings("unchecked") T annotation = (T) Proxy.newProxyInstance(Optional.ofNullable(annotationType.getClassLoader()).orElseGet(Thread.currentThread()::getContextClassLoader), interfaces, invocationHandler);
    return annotation;
}
Also used : Arrays(java.util.Arrays) Proxy(java.lang.reflect.Proxy) MethodHandles(java.lang.invoke.MethodHandles) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Unchecked(org.jdbi.v3.core.internal.exceptions.Unchecked) MethodType(java.lang.invoke.MethodType) Map(java.util.Map) Annotation(java.lang.annotation.Annotation) Entry(java.util.Map.Entry) Optional(java.util.Optional) InvocationHandler(java.lang.reflect.InvocationHandler) Comparator(java.util.Comparator) Method(java.lang.reflect.Method) Collections(java.util.Collections) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 7 with Unchecked

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

the class SqlArrayMapperFactory method build.

@Override
@SuppressWarnings("unchecked")
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) {
    final Class<?> erasedType = GenericTypes.getErasedType(type);
    if (erasedType.isArray()) {
        Class<?> elementType = erasedType.getComponentType();
        return elementTypeMapper(elementType, config).map(elementMapper -> new ArrayColumnMapper(elementMapper, elementType));
    }
    JdbiCollectors collectorRegistry = config.get(JdbiCollectors.class);
    return (Optional) collectorRegistry.findFor(type).flatMap(collector -> collectorRegistry.findElementTypeFor(type).flatMap(elementType -> elementTypeMapper(elementType, config)).map(elementMapper -> new CollectorColumnMapper(elementMapper, collector)));
}
Also used : JdbiCollectors(org.jdbi.v3.core.collector.JdbiCollectors) Type(java.lang.reflect.Type) ColumnMappers(org.jdbi.v3.core.mapper.ColumnMappers) ColumnMapper(org.jdbi.v3.core.mapper.ColumnMapper) Optional(java.util.Optional) GenericTypes(org.jdbi.v3.core.generic.GenericTypes) ColumnMapperFactory(org.jdbi.v3.core.mapper.ColumnMapperFactory) ConfigRegistry(org.jdbi.v3.core.config.ConfigRegistry) Optional(java.util.Optional) JdbiCollectors(org.jdbi.v3.core.collector.JdbiCollectors)

Example 8 with Unchecked

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

the class MessageFieldArgument method apply.

@Override
@SuppressWarnings("unchecked")
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
    if (message.has(field)) {
        switch(field.getType()) {
            case BOOL:
                {
                    boolean value = message.get(field);
                    if (type == Types.BOOLEAN || type == Types.BIT) {
                        statement.setBoolean(position, value);
                    } else {
                        statement.setInt(position, value ? 1 : 0);
                    }
                    break;
                }
            case BYTE:
                {
                    statement.setByte(position, message.get(field));
                    break;
                }
            case I16:
                {
                    statement.setShort(position, message.get(field));
                    break;
                }
            case I32:
                {
                    if (type == Types.TIMESTAMP) {
                        Timestamp timestamp = new Timestamp(1000L * (int) message.get(field));
                        statement.setTimestamp(position, timestamp);
                    } else {
                        statement.setInt(position, message.get(field));
                    }
                    break;
                }
            case I64:
                {
                    if (type == Types.TIMESTAMP) {
                        Timestamp timestamp = new Timestamp(message.get(field));
                        statement.setTimestamp(position, timestamp);
                    } else {
                        statement.setLong(position, message.get(field));
                    }
                    break;
                }
            case DOUBLE:
                {
                    statement.setDouble(position, message.get(field));
                    break;
                }
            case STRING:
                {
                    statement.setString(position, message.get(field));
                    break;
                }
            case BINARY:
                {
                    Binary binary = message.get(field);
                    switch(type) {
                        case Types.BINARY:
                        case Types.VARBINARY:
                            {
                                statement.setBytes(position, binary.get());
                                break;
                            }
                        case Types.BLOB:
                            {
                                statement.setBlob(position, binary.getInputStream());
                                break;
                            }
                        case Types.CHAR:
                        case Types.VARCHAR:
                        case Types.NCHAR:
                        case Types.NVARCHAR:
                            {
                                statement.setString(position, binary.toBase64());
                                break;
                            }
                        default:
                            throw new ResultSetException("Unknown binary field type: " + type + " for " + field, null, ctx);
                    }
                    break;
                }
            case ENUM:
                {
                    PEnumValue value = message.get(field);
                    statement.setInt(position, value.asInteger());
                    break;
                }
            case MESSAGE:
                {
                    PMessage value = message.get(field);
                    switch(type) {
                        case Types.BINARY:
                        case Types.VARBINARY:
                            {
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                try {
                                    BINARY.serialize(out, value);
                                    statement.setBytes(position, out.toByteArray());
                                } catch (IOException e) {
                                    throw new ResultSetException(e.getMessage(), e, ctx);
                                }
                                break;
                            }
                        case Types.BLOB:
                            {
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                try {
                                    BINARY.serialize(out, value);
                                    statement.setBlob(position, new ByteArrayInputStream(out.toByteArray()));
                                } catch (IOException e) {
                                    throw new ResultSetException(e.getMessage(), e, ctx);
                                }
                                break;
                            }
                        case Types.CHAR:
                        case Types.VARCHAR:
                        case Types.NCHAR:
                        case Types.NVARCHAR:
                            {
                                StringWriter writer = new StringWriter();
                                try {
                                    JSON.serialize(new PrintWriter(writer), value);
                                    statement.setString(position, writer.getBuffer().toString());
                                } catch (IOException e) {
                                    throw new ResultSetException(e.getMessage(), e, ctx);
                                }
                                break;
                            }
                        case Types.CLOB:
                            {
                                StringWriter writer = new StringWriter();
                                try {
                                    JSON.serialize(new PrintWriter(writer), value);
                                    statement.setClob(position, new StringReader(writer.getBuffer().toString()));
                                } catch (IOException e) {
                                    throw new ResultSetException(e.getMessage(), e, ctx);
                                }
                                break;
                            }
                        default:
                            throw new ResultSetException("Unknown message field type: " + type + " for " + field, null, ctx);
                    }
                    break;
                }
            default:
                throw new ResultSetException("Unhandled field type in SQL: " + field, null, ctx);
        }
    } else {
        statement.setNull(position, type);
    }
}
Also used : ResultSetException(org.jdbi.v3.core.result.ResultSetException) StringWriter(java.io.StringWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) PMessage(net.morimekta.providence.PMessage) StringReader(java.io.StringReader) PEnumValue(net.morimekta.providence.PEnumValue) Binary(net.morimekta.util.Binary) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Timestamp(java.sql.Timestamp) PrintWriter(java.io.PrintWriter)

Example 9 with Unchecked

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

the class MessageNamedArgumentFinder method find.

@Nonnull
@Override
@SuppressWarnings("unchecked")
public Optional<Argument> find(String name, StatementContext ctx) {
    if (!prefix.isEmpty()) {
        if (name.startsWith(prefix)) {
            name = name.substring(prefix.length());
        } else {
            return Optional.empty();
        }
    }
    String[] parts = name.split("[.]");
    PMessage leaf = message;
    PMessageDescriptor leafDescriptor = message.descriptor();
    for (int i = 0; i < parts.length - 1; ++i) {
        String part = parts[i];
        PField field = leafDescriptor.findFieldByName(part);
        if (field == null)
            return Optional.empty();
        if (field.getType() != PType.MESSAGE) {
            throw new IllegalArgumentException("");
        }
        leafDescriptor = (PMessageDescriptor) field.getDescriptor();
        if (leaf != null) {
            leaf = (PMessage) leaf.get(field.getId());
        }
    }
    String leafName = parts[parts.length - 1];
    PField field = leafDescriptor.findFieldByName(leafName);
    if (field != null) {
        if (leaf != null) {
            return Optional.of(new MessageFieldArgument(leaf, field, getColumnType(field)));
        }
        return Optional.of(new NullArgument(getColumnType(field)));
    }
    return Optional.empty();
}
Also used : PField(net.morimekta.providence.descriptor.PField) PMessage(net.morimekta.providence.PMessage) PMessageDescriptor(net.morimekta.providence.descriptor.PMessageDescriptor) NullArgument(org.jdbi.v3.core.argument.NullArgument) Nonnull(javax.annotation.Nonnull)

Example 10 with Unchecked

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

the class FieldMapper method specialize0.

private Optional<RowMapper<T>> specialize0(StatementContext ctx, List<String> columnNames, List<ColumnNameMatcher> columnNameMatchers, List<String> unmatchedColumns) {
    final List<FieldData> fields = new ArrayList<>();
    for (Class<?> aType = type; aType != null; aType = aType.getSuperclass()) {
        for (Field field : aType.getDeclaredFields()) {
            Nested anno = field.getAnnotation(Nested.class);
            if (anno == null) {
                String paramName = prefix + paramName(field);
                findColumnIndex(paramName, columnNames, columnNameMatchers, () -> debugName(field)).ifPresent(index -> {
                    QualifiedType<?> fieldType = QualifiedType.of(field.getGenericType()).withAnnotations(ctx.getConfig(Qualifiers.class).findFor(field));
                    @SuppressWarnings("unchecked") ColumnMapper<?> mapper = ctx.findColumnMapperFor(fieldType).orElse((ColumnMapper) (r, n, c) -> r.getObject(n));
                    fields.add(new FieldData(field, new SingleColumnMapper<>(mapper, index + 1)));
                    unmatchedColumns.remove(columnNames.get(index));
                });
            } else {
                String nestedPrefix = prefix + anno.value().toLowerCase();
                if (anyColumnsStartWithPrefix(columnNames, nestedPrefix, columnNameMatchers)) {
                    nestedMappers.computeIfAbsent(field, f -> new FieldMapper<>(field.getType(), nestedPrefix)).specialize0(ctx, columnNames, columnNameMatchers, unmatchedColumns).ifPresent(mapper -> fields.add(new FieldData(field, mapper)));
                }
            }
        }
    }
    if (fields.isEmpty() && !columnNames.isEmpty()) {
        return Optional.empty();
    }
    Collections.sort(fields, Comparator.comparing(f -> f.propagateNull ? 1 : 0));
    final Optional<String> nullMarkerColumn = Optional.ofNullable(type.getAnnotation(PropagateNull.class)).map(PropagateNull::value);
    return Optional.of((r, c) -> {
        if (PojoMapper.propagateNull(r, nullMarkerColumn)) {
            return null;
        }
        T obj = construct();
        for (FieldData f : fields) {
            Object value = f.mapper.map(r, ctx);
            if (f.propagateNull && (value == null || (f.isPrimitive && r.wasNull()))) {
                return null;
            }
            writeField(obj, f.field, value);
        }
        return obj;
    });
}
Also used : RowMapperFactory(org.jdbi.v3.core.mapper.RowMapperFactory) ReflectionMapperUtil.getColumnNames(org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.getColumnNames) PropagateNull(org.jdbi.v3.core.mapper.PropagateNull) PojoMapper(org.jdbi.v3.core.mapper.reflect.internal.PojoMapper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Nested(org.jdbi.v3.core.mapper.Nested) Field(java.lang.reflect.Field) SingleColumnMapper(org.jdbi.v3.core.mapper.SingleColumnMapper) String.format(java.lang.String.format) ArrayList(java.util.ArrayList) StatementContext(org.jdbi.v3.core.statement.StatementContext) SQLException(java.sql.SQLException) List(java.util.List) ResultSet(java.sql.ResultSet) Map(java.util.Map) ColumnMapper(org.jdbi.v3.core.mapper.ColumnMapper) ReflectionMapperUtil.findColumnIndex(org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.findColumnIndex) Optional(java.util.Optional) Qualifiers(org.jdbi.v3.core.qualifier.Qualifiers) QualifiedType(org.jdbi.v3.core.qualifier.QualifiedType) ReflectionMapperUtil.anyColumnsStartWithPrefix(org.jdbi.v3.core.mapper.reflect.ReflectionMapperUtil.anyColumnsStartWithPrefix) Comparator(java.util.Comparator) Collections(java.util.Collections) RowMapper(org.jdbi.v3.core.mapper.RowMapper) SingleColumnMapper(org.jdbi.v3.core.mapper.SingleColumnMapper) ArrayList(java.util.ArrayList) Nested(org.jdbi.v3.core.mapper.Nested) Field(java.lang.reflect.Field) PropagateNull(org.jdbi.v3.core.mapper.PropagateNull)

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