Java Code Examples for io.micronaut.core.async.publisher.Publishers#isConvertibleToPublisher()

The following examples show how to use io.micronaut.core.async.publisher.Publishers#isConvertibleToPublisher() . 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: 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 2
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 3
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 4
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 5
Source File: MicronautLambdaContainerHandler.java    From micronaut-aws with Apache License 2.0 4 votes vote down vote up
private Publisher<MutableHttpResponse<?>> executeRoute(
        MicronautAwsProxyRequest<?> containerRequest,
        MicronautAwsProxyResponse<?> containerResponse,
        MethodBasedRouteMatch finalRoute) {
    final RouteMatch<?> boundRoute = requestArgumentSatisfier.fulfillArgumentRequirements(
            finalRoute,
            containerRequest,
            false
    );

    try {
        decodeRequestBody(containerRequest, finalRoute);
    } catch (Exception e) {
        return Flowable.error(e);
    }

    Object result = boundRoute.execute();

    if (result instanceof Optional) {
        Optional<?> optional = (Optional) result;
        result = optional.orElse(null);
    }
    if (!void.class.isAssignableFrom(boundRoute.getReturnType().getType()) && result == null) {
        applyRouteConfig(containerResponse, finalRoute);
        containerResponse.status(HttpStatus.NOT_FOUND);
        return Flowable.just(containerResponse);
    }
    if (Publishers.isConvertibleToPublisher(result)) {
        Single<?> single;
        if (Publishers.isSingle(result.getClass())) {
            single = Publishers.convertPublisher(result, Single.class);
        } else {
            single = Publishers.convertPublisher(result, Flowable.class).toList();
        }
        return single.map((Function<Object, MutableHttpResponse<?>>) o -> {
            if (!(o instanceof MicronautAwsProxyResponse)) {
                ((MutableHttpResponse) containerResponse).body(o);
            }
            applyRouteConfig(containerResponse, finalRoute);
            return containerResponse;
        }).toFlowable();
    } else {
        if (!(result instanceof MicronautAwsProxyResponse)) {
            applyRouteConfig(containerResponse, finalRoute);
            ((MutableHttpResponse) containerResponse).body(result);
        }
        return Flowable.just(containerResponse);
    }
}