Java Code Examples for io.micronaut.core.type.Argument#getType()

The following examples show how to use io.micronaut.core.type.Argument#getType() . 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: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, ByteBuffer<?> buffer) throws CodecException {
    try {
        if (type.getType() == byte[].class) {
            return (T) buffer.toByteArray();
        } else {
            Message.Builder builder = getBuilder(type)
                    .orElseThrow(() -> new CodecException("Unable to create builder"));
            if (type.hasTypeVariables()) {
                throw new IllegalStateException("Generic type arguments are not supported");
            } else {
                builder.mergeFrom(buffer.toByteArray(), extensionRegistry);
                return type.getType().cast(builder.build());
            }
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff bytes for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example 2
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, byte[] bytes) throws CodecException {
    try {
        if (type.getType() == byte[].class) {
            return (T) bytes;
        } else {
            Message.Builder builder = getBuilder(type)
                    .orElseThrow(() -> new CodecException("Unable to create builder"));
            if (type.hasTypeVariables()) {
                throw new IllegalStateException("Generic type arguments are not supported");
            } else {
                builder.mergeFrom(bytes, extensionRegistry);
                return type.getType().cast(builder.build());
            }
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff bytes for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example 3
Source File: SerdeRegistry.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Picks the most appropriate {@link Deserializer} for the given argument.
 *
 * @param argument The argument
 * @param <T> The generic type
 * @return The {@link Deserializer}
 */
@SuppressWarnings("unchecked")
default <T> Deserializer<T> pickDeserializer(Argument<T> argument) {
    Class<T> type = argument.getType();

    if (Publishers.isConvertibleToPublisher(type) || Future.class.isAssignableFrom(type)) {
        Optional<Argument<?>> typeArg = argument.getFirstTypeVariable();

        if (typeArg.isPresent()) {
            type = (Class<T>) typeArg.get().getType();
        } else {
            return (Deserializer<T>) new ByteArrayDeserializer();
        }
    }

    return getDeserializer(type);
}
 
Example 4
Source File: SerdeRegistry.java    From micronaut-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Picks the most appropriate {@link Deserializer} for the given argument.
 *
 * @param argument The argument
 * @param <T> The generic type
 * @return The {@link Deserializer}
 */
@SuppressWarnings("unchecked")
default <T> Serializer<T> pickSerializer(Argument<T> argument) {
    Class<T> type = argument.getType();

    if (Publishers.isConvertibleToPublisher(type) || Future.class.isAssignableFrom(type)) {
        Optional<Argument<?>> typeArg = argument.getFirstTypeVariable();

        if (typeArg.isPresent()) {
            type = (Class<T>) typeArg.get().getType();
        } else {
            return (Serializer<T>) new ByteArrayDeserializer();
        }
    }

    return getSerializer(type);
}
 
Example 5
Source File: AbstractQueryInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a number argument if necessary.
 * @param number The number
 * @param argument The argument
 * @return The result
 */
protected @Nullable Number convertNumberArgumentIfNecessary(Number number, Argument<?> argument) {
    Argument<?> firstTypeVar = argument.getFirstTypeVariable().orElse(Argument.of(Long.class));
    Class<?> type = firstTypeVar.getType();
    if (type == Object.class || type == Void.class) {
        return null;
    }
    if (number == null) {
        number = 0;
    }
    if (!type.isInstance(number)) {
        return (Number) ConversionService.SHARED.convert(number, firstTypeVar)
                .orElseThrow(() -> new IllegalStateException("Unsupported number type for return type: " + firstTypeVar));
    } else {
        return number;
    }
}
 
Example 6
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, ByteBuffer<?> buffer) throws CodecException {
    try {
        if (type.getType() == byte[].class) {
            return (T) buffer.toByteArray();
        } else {
            Message.Builder builder = getBuilder(type)
                    .orElseThrow(() -> new CodecException("Unable to create builder"));
            if (type.hasTypeVariables()) {
                throw new IllegalStateException("Generic type arguments are not supported");
            } else {
                builder.mergeFrom(buffer.toByteArray(), extensionRegistry);
                return type.getType().cast(builder.build());
            }
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff bytes for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example 7
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T decode(Argument<T> type, byte[] bytes) throws CodecException {
    try {
        if (type.getType() == byte[].class) {
            return (T) bytes;
        } else {
            Message.Builder builder = getBuilder(type)
                    .orElseThrow(() -> new CodecException("Unable to create builder"));
            if (type.hasTypeVariables()) {
                throw new IllegalStateException("Generic type arguments are not supported");
            } else {
                builder.mergeFrom(bytes, extensionRegistry);
                return type.getType().cast(builder.build());
            }
        }
    } catch (Exception e) {
        throw new CodecException("Error decoding Protobuff bytes for type [" + type.getName() + "]: " + e.getMessage(), e);
    }
}
 
Example 8
Source File: MicronautLambdaContainerHandler.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private void decodeRequestBody(MicronautAwsProxyRequest<?> containerRequest, MethodBasedRouteMatch<Object, Object> finalRoute) {
    final boolean permitsRequestBody = HttpMethod.permitsRequestBody(containerRequest.getMethod());
    if (permitsRequestBody) {
        final MediaType requestContentType = containerRequest.getContentType().orElse(null);
        if (requestContentType != null && requestContentType.getExtension().equalsIgnoreCase("json")) {
            final MediaType[] expectedContentType = finalRoute.getAnnotationMetadata().getValue(Consumes.class, MediaType[].class).orElse(null);
            if (expectedContentType == null || Arrays.stream(expectedContentType).anyMatch(ct -> ct.getExtension().equalsIgnoreCase("json"))) {
                final Optional<String> body = containerRequest.getBody(String.class);
                if (body.isPresent()) {

                    Argument<?> bodyArgument = finalRoute.getBodyArgument().orElse(null);
                    if (bodyArgument == null) {
                        bodyArgument = Arrays.stream(finalRoute.getArguments()).filter(arg -> HttpRequest.class.isAssignableFrom(arg.getType()))
                            .findFirst()
                            .flatMap(TypeVariableResolver::getFirstTypeVariable).orElse(null);
                    }

                    if (bodyArgument != null) {
                        final Class<?> rawType = bodyArgument.getType();
                        if (Publishers.isConvertibleToPublisher(rawType) || HttpRequest.class.isAssignableFrom(rawType)) {
                            bodyArgument = bodyArgument.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
                        }
                        final Object decoded = lambdaContainerEnvironment.getJsonCodec().decode(bodyArgument, body.get());
                        ((MicronautAwsProxyRequest) containerRequest)
                            .setDecodedBody(decoded);
                    } else {
                        final JsonNode jsonNode = lambdaContainerEnvironment.getJsonCodec().decode(JsonNode.class, body.get());
                        ((MicronautAwsProxyRequest) containerRequest)
                            .setDecodedBody(jsonNode);
                    }
                }
            }
        }
    }
}
 
Example 9
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 10
Source File: GoogleFunctionHttpRequest.java    From micronaut-gcp with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public <T> Optional<T> getBody(@Nonnull Argument<T> arg) {
    if (arg != null) {
        final Class<T> type = arg.getType();
        final MediaType contentType = getContentType().orElse(MediaType.APPLICATION_JSON_TYPE);
        if (body == null) {

            if (isFormSubmission(contentType)) {
                body = getParameters();
                if (ConvertibleValues.class == type) {
                    return (Optional<T>) Optional.of(body);
                } else {
                    return Optional.empty();
                }
            } else {

                final MediaTypeCodec codec = codecRegistry.findCodec(contentType, type).orElse(null);
                if (codec != null) {
                    try (InputStream inputStream = googleRequest.getInputStream()) {
                        if (ConvertibleValues.class == type) {
                            final Map map = codec.decode(Map.class, inputStream);
                            body = ConvertibleValues.of(map);
                            return (Optional<T>) Optional.of(body);
                        } else {
                            final T value = codec.decode(arg, inputStream);
                            body = value;
                            return Optional.ofNullable(value);
                        }
                    } catch (IOException e) {
                        throw new CodecException("Error decoding request body: " + e.getMessage(), e);
                    }

                }
            }
        } else {
            if (type.isInstance(body)) {
                return (Optional<T>) Optional.of(body);
            } else {
                if (body != httpParameters) {
                    final T result = ConversionService.SHARED.convertRequired(body, arg);
                    return Optional.ofNullable(result);
                }
            }

        }
    }
    return Optional.empty();
}
 
Example 11
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Optional<Message.Builder> getBuilder(Argument<T> type) {
    Class<? extends Message> clazz = (Class<? extends Message>) type.getType();
    return getMessageBuilder(clazz);
}
 
Example 12
Source File: KafkaClientIntroductionAdvice.java    From micronaut-kafka with Apache License 2.0 4 votes vote down vote up
private Flowable<Object> buildSendFlowable(
        MethodInvocationContext<Object, Object> context,
        String topic,
        Producer kafkaProducer,
        List<Header> kafkaHeaders,
        Argument<?> returnType,
        Object key,
        Object value,
        Long timestamp,
        Duration maxBlock) {
    Flowable<?> valueFlowable = Publishers.convertPublisher(value, Flowable.class);
    Class<?> javaReturnType = returnType.getType();

    if (Iterable.class.isAssignableFrom(javaReturnType)) {
        javaReturnType = returnType.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT).getType();
    }

    Class<?> finalJavaReturnType = javaReturnType;
    Flowable<Object> sendFlowable = valueFlowable.flatMap(o -> {
        ProducerRecord record = buildProducerRecord(topic, kafkaHeaders, key, o, timestamp);

        if (LOG.isTraceEnabled()) {
            LOG.trace("@KafkaClient method [" + context + "] Sending producer record: " + record);
        }

        //noinspection unchecked
        return Flowable.create(emitter -> kafkaProducer.send(record, (metadata, exception) -> {
            if (exception != null) {
                emitter.onError(wrapException(context, exception));
            } else {
                if (RecordMetadata.class.isAssignableFrom(finalJavaReturnType)) {
                    emitter.onNext(metadata);
                } else if (finalJavaReturnType.isInstance(o)) {
                    emitter.onNext(o);
                } else {
                    Optional converted = conversionService.convert(metadata, finalJavaReturnType);
                    if (converted.isPresent()) {
                        emitter.onNext(converted.get());
                    }
                }

                emitter.onComplete();
            }
        }), BackpressureStrategy.BUFFER);
    });

    if (maxBlock != null) {
        sendFlowable = sendFlowable.timeout(maxBlock.toMillis(), TimeUnit.MILLISECONDS);
    }
    return sendFlowable;
}
 
Example 13
Source File: KafkaClientScope.java    From micronaut-kafka with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T getKafkaProducer(@Nullable String id, Argument<?> keyType, Argument<?> valueType) {
    ClientKey key = new ClientKey(
            id,
            keyType.getType(),
            valueType.getType()
    );

    return (T) clients.computeIfAbsent(key, clientKey -> {
        Supplier<AbstractKafkaProducerConfiguration> defaultResolver = () -> beanContext.getBean(AbstractKafkaProducerConfiguration.class);
        AbstractKafkaProducerConfiguration config;
        boolean hasId = StringUtils.isNotEmpty(id);
        if (hasId) {
            config = beanContext.findBean(
                    AbstractKafkaProducerConfiguration.class,
                    Qualifiers.byName(id)
            ).orElseGet(defaultResolver);
        } else {
            config = defaultResolver.get();
        }

        DefaultKafkaProducerConfiguration newConfig = new DefaultKafkaProducerConfiguration(config);

        Properties properties = newConfig.getConfig();
        if (!properties.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) {
            Serializer<?> keySerializer = serdeRegistry.pickSerializer(keyType);
            newConfig.setKeySerializer(keySerializer);
        }

        if (!properties.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) {
            Serializer<?> valueSerializer = serdeRegistry.pickSerializer(valueType);
            newConfig.setValueSerializer(valueSerializer);
        }


        if (hasId) {
            properties.putIfAbsent(ProducerConfig.CLIENT_ID_CONFIG, id);
        }
        return beanContext.createBean(Producer.class, newConfig);
    });
}
 
Example 14
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Optional<Message.Builder> getBuilder(Argument<T> type) {
    Class<? extends Message> clazz = (Class<? extends Message>) type.getType();
    return getMessageBuilder(clazz);
}