io.micronaut.core.convert.ConversionContext Java Examples

The following examples show how to use io.micronaut.core.convert.ConversionContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MicronautRequestHandler.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the input the required type. Subclasses can override to provide custom conversion.
 *
 * @param input The input
 * @return The converted input
 * @throws IllegalArgumentException If input cannot be converted
 */
protected I convertInput(Object input)  {
    final ArgumentConversionContext<I> cc = ConversionContext.of(inputType);
    final Optional<I> converted = applicationContext.getConversionService().convert(
            input,
            cc
    );
    return converted.orElseThrow(() ->
            new IllegalArgumentException("Unconvertible input: " + input, cc.getLastError().map(ConversionError::getCause).orElse(null))
    );
}
 
Example #2
Source File: BatchConsumerRecordsBinderRegistry.java    From micronaut-kafka with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> Optional<ArgumentBinder<T, ConsumerRecords<?, ?>>> findArgumentBinder(Argument<T> argument, ConsumerRecords<?, ?> source) {
    Class<T> argType = argument.getType();
    if (Iterable.class.isAssignableFrom(argType) || argType.isArray() || Publishers.isConvertibleToPublisher(argType)) {
        Argument<?> batchType = argument.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
        List bound = new ArrayList();

        return Optional.of((context, consumerRecords) -> {
            for (ConsumerRecord<?, ?> consumerRecord : consumerRecords) {
                Optional<ArgumentBinder<?, ConsumerRecord<?, ?>>> binder = consumerRecordBinderRegistry.findArgumentBinder((Argument) argument, consumerRecord);
                binder.ifPresent(b -> {
                    Argument<?> newArg = Argument.of(batchType.getType(), argument.getName(), argument.getAnnotationMetadata(), batchType.getTypeParameters());
                    ArgumentConversionContext conversionContext = ConversionContext.of(newArg);
                    ArgumentBinder.BindingResult<?> result = b.bind(
                            conversionContext,
                            consumerRecord);
                    if (result.isPresentAndSatisfied()) {
                        bound.add(result.get());
                    }

                });
            }
            return () -> {
                if (Publisher.class.isAssignableFrom(argument.getType())) {
                    return ConversionService.SHARED.convert(Flowable.fromIterable(bound), argument);
                } else {
                    return ConversionService.SHARED.convert(bound, argument);
                }
            };
        });
    }
    return Optional.empty();
}
 
Example #3
Source File: ByteBufToProtoMessageConverter.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<Message> convert(ByteBuf object, Class<Message> targetType, ConversionContext context) {
    return codec
            .getMessageBuilder(targetType)
            .flatMap(builder -> rehydrate(object, builder));
}
 
Example #4
Source File: ProtoMessageToByteBufConverter.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<ByteBuf> convert(Message object, Class<ByteBuf> targetType, ConversionContext context) {
    return conversionService.convert(object.toByteArray(), targetType, context);
}
 
Example #5
Source File: KafkaHeaderConverter.java    From micronaut-kafka with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<Object> convert(Header object, Class<Object> targetType, ConversionContext context) {
    byte[] v = object.value();
    return ConversionService.SHARED.convert(new String(v), targetType, context);
}
 
Example #6
Source File: BeanIntrospectionMapper.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
default @NonNull R map(@NonNull D object, @NonNull Class<R> type) throws InstantiationException {
    ArgumentUtils.requireNonNull("resultSet", object);
    ArgumentUtils.requireNonNull("type", type);
    try {
        BeanIntrospection<R> introspection = BeanIntrospection.getIntrospection(type);
        ConversionService<?> conversionService = getConversionService();
        Argument<?>[] arguments = introspection.getConstructorArguments();
        R instance;
        if (ArrayUtils.isEmpty(arguments)) {
            instance = introspection.instantiate();
        } else {
            Object[] args = new Object[arguments.length];
            for (int i = 0; i < arguments.length; i++) {
                Argument<?> argument = arguments[i];
                Object o = read(object, argument);
                if (o == null) {
                    args[i] = o;
                } else {
                    if (argument.getType().isInstance(o)) {
                        args[i] = o;
                    } else {
                        ArgumentConversionContext<?> acc = ConversionContext.of(argument);
                        args[i] = conversionService.convert(o, acc).orElseThrow(() -> {
                                    Optional<ConversionError> lastError = acc.getLastError();
                                    return lastError.<RuntimeException>map(conversionError -> new ConversionErrorException(argument, conversionError))
                                            .orElseGet(() ->
                                                    new IllegalArgumentException("Cannot convert object type " + o.getClass() + " to required type: " + argument.getType())
                                            );
                                }

                        );
                    }
                }
            }
            instance = introspection.instantiate(args);
        }
        Collection<BeanProperty<R, Object>> properties = introspection.getBeanProperties();
        for (BeanProperty<R, Object> property : properties) {
            if (property.isReadOnly()) {
                continue;
            }

            Object v = read(object, property.getName());
            if (property.getType().isInstance(v))  {
                property.set(instance, v);
            } else {
                property.convertAndSet(instance, v);
            }
        }

        return instance;
    } catch (IntrospectionException | InstantiationException e) {
        throw new DataAccessException("Error instantiating type [" + type.getName() + "] from introspection: " + e.getMessage(), e);
    }
}
 
Example #7
Source File: ByteBufToProtoMessageConverter.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<Message> convert(ByteBuf object, Class<Message> targetType, ConversionContext context) {
    return codec
            .getMessageBuilder(targetType)
            .flatMap(builder -> rehydrate(object, builder));
}
 
Example #8
Source File: ProtoMessageToByteBufConverter.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<ByteBuf> convert(Message object, Class<ByteBuf> targetType, ConversionContext context) {
    return conversionService.convert(object.toByteArray(), targetType, context);
}