io.micronaut.core.async.publisher.Publishers Java Examples

The following examples show how to use io.micronaut.core.async.publisher.Publishers. 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: DefaultGraphQLInvocation.java    From micronaut-graphql with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Publisher<ExecutionResult> invoke(GraphQLInvocationData invocationData, HttpRequest httpRequest) {
    ExecutionInput.Builder executionInputBuilder = ExecutionInput.newExecutionInput()
            .query(invocationData.getQuery())
            .operationName(invocationData.getOperationName())
            .variables(invocationData.getVariables());
    if (dataLoaderRegistry != null) {
        executionInputBuilder.dataLoaderRegistry(dataLoaderRegistry.get());
    }
    ExecutionInput executionInput = executionInputBuilder.build();
    return Flowable.fromPublisher(graphQLExecutionInputCustomizer.customize(executionInput, httpRequest))
            .flatMap(customizedExecutionInput -> Publishers.fromCompletableFuture(() -> {
                try {
                    return graphQL.executeAsync(customizedExecutionInput);
                } catch (Throwable e) {
                    CompletableFuture future = new CompletableFuture();
                    future.completeExceptionally(e);
                    return future;
                }
            }));
}
 
Example #2
Source File: DefaultCountReactiveInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, Long> preparedQuery = prepareQuery(methodKey, context, Long.class);
        return Publishers.convertPublisher(
                reactiveOperations.findAll(preparedQuery),
                context.getReturnType().getType()
        );
    } else {
        Publisher<Long> result = reactiveOperations.count(getPagedQuery(context));
        return Publishers.convertPublisher(
                result,
                context.getReturnType().getType()
        );
    }
}
 
Example #3
Source File: DefaultFindSliceReactiveInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context);
        Pageable pageable = preparedQuery.getPageable();

        Single<Slice<Object>> publisher = Flowable.fromPublisher(reactiveOperations.findAll(preparedQuery))
                .toList().map(objects -> Slice.of(objects, pageable));
        return Publishers.convertPublisher(publisher, context.getReturnType().getType());

    } else {
        PagedQuery<Object> pagedQuery = getPagedQuery(context);
        Single<? extends Slice<?>> result = Flowable.fromPublisher(reactiveOperations.findAll(pagedQuery))
                .toList().map(objects ->
                        Slice.of(objects, pagedQuery.getPageable())
                );
        return Publishers.convertPublisher(result, context.getReturnType().getType());
    }
}
 
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> 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 #5
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 #6
Source File: DefaultDeleteOneReactiveInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Object[] parameterValues = context.getParameterValues();
    if (parameterValues.length == 1) {
        Class<Object> rootEntity = (Class<Object>) getRequiredRootEntity(context);
        Object o = parameterValues[0];
        if (o != null) {
            BatchOperation<Object> batchOperation = getBatchOperation(context, rootEntity, Collections.singletonList(o));
            Publisher<Number> publisher = Publishers.map(reactiveOperations.deleteAll(batchOperation),
                    n -> convertNumberArgumentIfNecessary(n, context.getReturnType().asArgument())
            );
            return Publishers.convertPublisher(
                    publisher,
                    context.getReturnType().getType()
            );
        } else {
            throw new IllegalArgumentException("Entity to delete cannot be null");
        }
    } else {
        throw new IllegalStateException("Expected exactly one argument");
    }
}
 
Example #7
Source File: DefaultFindPageReactiveInterceptor.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Publisher<Page<Object>> publisher;
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context);
        PreparedQuery<?, Number> countQuery = prepareCountQuery(methodKey, context);

        publisher = Flowable.fromPublisher(reactiveOperations.findOne(countQuery))
                .flatMap(total -> {
                    Flowable<Object> resultList = Flowable.fromPublisher(reactiveOperations.findAll(preparedQuery));
                    return resultList.toList().map(list ->
                        Page.of(list, preparedQuery.getPageable(), total.longValue())
                    ).toFlowable();
                });
    } else {
        publisher = reactiveOperations.findPage(getPagedQuery(context));
    }
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}
 
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: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <T> Publisher<Number> deleteAll(BatchOperation<T> operation) {
    return Publishers.fromCompletableFuture(() ->
            asyncOperations.deleteAll(operation)
    );
}
 
Example #10
Source File: DefaultUpdateReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    PreparedQuery<?, Number> preparedQuery = (PreparedQuery<?, Number>) prepareQuery(methodKey, context);
    ReturnType<Object> returnType = context.getReturnType();
    Publisher<Number> publisher = Publishers.map(reactiveOperations.executeUpdate(preparedQuery),
            n -> convertNumberArgumentIfNecessary(n, returnType.asArgument())
    );
    return Publishers.convertPublisher(publisher, returnType.getType());
}
 
Example #11
Source File: DefaultFindByIdReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Class<?> rootEntity = getRequiredRootEntity(context);
    Object id = context.getParameterValues()[0];
    if (!(id instanceof Serializable)) {
        throw new IllegalArgumentException("Entity IDs must be serializable!");
    }
    Publisher<Object> publisher = reactiveOperations.findOne((Class<Object>) rootEntity, (Serializable) id);
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}
 
Example #12
Source File: DefaultFindOneReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context);
    Publisher<Object> publisher = reactiveOperations.findOptional(preparedQuery);
    Argument<Object> returnType = context.getReturnType().asArgument();
    Argument<?> type = returnType.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
    Publisher<Object> mappedPublisher = Publishers.map(publisher, o -> {
        if (!type.getType().isInstance(o)) {
            return ConversionService.SHARED.convert(o, type)
                    .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + o));
        }
        return o;
    });
    return Publishers.convertPublisher(mappedPublisher, returnType.getType());
}
 
Example #13
Source File: DefaultExistsByReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Class idType = context.classValue(DataMethod.class, DataMethod.META_MEMBER_ID_TYPE)
            .orElseGet(() -> getRequiredRootEntity(context));
    PreparedQuery<?, Boolean> preparedQuery = prepareQuery(methodKey, context, idType);
    return Publishers.convertPublisher(reactiveOperations.exists(preparedQuery), context.getReturnType().getType());
}
 
Example #14
Source File: DefaultSaveOneReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Class<?> rootEntity = getRequiredRootEntity(context);
    Map<String, Object> parameterValueMap = context.getParameterValueMap();

    Flowable<Object> publisher = Flowable.fromCallable(() -> {
        Object o = instantiateEntity(rootEntity, parameterValueMap);
        return getInsertOperation(context, o);
    }).flatMap(reactiveOperations::persist);
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}
 
Example #15
Source File: DefaultFindAllReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Publisher<?> publisher;
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context);
        publisher = reactiveOperations.findAll(preparedQuery);

    } else {
        publisher = reactiveOperations.findAll(getPagedQuery(context));
    }
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}
 
Example #16
Source File: DefaultSaveAllReactiveInterceptor.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Object[] parameterValues = context.getParameterValues();
    if (ArrayUtils.isNotEmpty(parameterValues) && parameterValues[0] instanceof Iterable) {
        //noinspection unchecked
        BatchOperation<Object> batchOperation = getBatchOperation(context, (Iterable<Object>) parameterValues[0]);
        Publisher<Object> publisher = reactiveOperations.persistAll(batchOperation);
        return Publishers.convertPublisher(publisher, context.getReturnType().getType());
    } else {
        throw new IllegalArgumentException("First argument should be an iterable");
    }
}
 
Example #17
Source File: FromCustomizer.java    From micronaut-graphql with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public Publisher<ExecutionInput> customize(ExecutionInput executionInput, HttpRequest httpRequest) {
    return Publishers.just(executionInput.transform(
            builder -> builder.context(httpRequest.getRemoteAddress().toString())
    ));
}
 
Example #18
Source File: GraphQLController.java    From micronaut-graphql with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the GraphQL request and returns the serialized {@link GraphQLResponseBody}.
 *
 * @param query         the GraphQL query
 * @param operationName the GraphQL operation name
 * @param variables     the GraphQL variables
 * @param httpRequest   the HTTP request
 * @return the serialized GraphQL response
 */
private Publisher<String> executeRequest(
        String query,
        String operationName,
        Map<String, Object> variables,
        HttpRequest httpRequest) {
    GraphQLInvocationData invocationData = new GraphQLInvocationData(query, operationName, variables);
    Publisher<ExecutionResult> executionResult = graphQLInvocation.invoke(invocationData, httpRequest);
    Publisher<GraphQLResponseBody> responseBody = graphQLExecutionResultHandler.handleExecutionResult(executionResult);
    return Publishers.map(responseBody, graphQLJsonSerializer::serialize);
}
 
Example #19
Source File: GraphQLWsController.java    From micronaut-graphql with Apache License 2.0 5 votes vote down vote up
private Publisher<GraphQLWsResponse> send(Publisher<GraphQLWsResponse> publisher, WebSocketSession session) {
    return Publishers.then(publisher, response -> {
        if (session.isOpen()) {
            session.sendSync(graphQLJsonSerializer.serialize(response));
        }
    });
}
 
Example #20
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <T> Publisher<T> findAll(PagedQuery<T> pagedQuery) {
    return Flowable.fromPublisher(Publishers.fromCompletableFuture(() ->
            asyncOperations.findAll(pagedQuery)
    )).flatMap(Flowable::fromIterable);
}
 
Example #21
Source File: Route53AutoNamingClient.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the services IDs returned for usage in MN.
 * @param listServicesResult service result returned from AWS
 * @return RXJava publisher of the service list
 */
private Publisher<List<String>> convertServiceIds(ListServicesResult listServicesResult) {
    List<ServiceSummary> services = listServicesResult.getServices();
    List<String> serviceIds = new ArrayList<>();

    for (ServiceSummary service : services) {
        serviceIds.add(service.getId());
    }
    return Publishers.just(
            serviceIds
    );

}
 
Example #22
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 #23
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <T> Publisher<T> findOne(@NonNull Class<T> type, @NonNull Serializable id) {
    return Publishers.fromCompletableFuture(() ->
            asyncOperations.findOne(type, id)
    );
}
 
Example #24
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <T, R> Publisher<R> findOne(@NonNull PreparedQuery<T, R> preparedQuery) {
    return Publishers.fromCompletableFuture(() ->
            asyncOperations.findOne(preparedQuery)
    );
}
 
Example #25
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <T> Publisher<T> findOptional(@NonNull Class<T> type, @NonNull Serializable id) {
    return Publishers.fromCompletableFuture(() ->
            asyncOperations.findOptional(type, id)
    );
}
 
Example #26
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <T, R> Publisher<R> findOptional(@NonNull PreparedQuery<T, R> preparedQuery) {
    return Publishers.fromCompletableFuture(() ->
            asyncOperations.findOptional(preparedQuery)
    );
}
 
Example #27
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <T> Publisher<Long> count(PagedQuery<T> pagedQuery) {
    return Publishers.fromCompletableFuture(() ->
            asyncOperations.count(pagedQuery)
    );
}
 
Example #28
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public Publisher<Number> executeUpdate(@NonNull PreparedQuery<?, Number> preparedQuery) {
    return Publishers.fromCompletableFuture(() ->
            asyncOperations.executeUpdate(preparedQuery)
    );
}
 
Example #29
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <R> Publisher<Page<R>> findPage(@NonNull PagedQuery<R> pagedQuery) {
    return Publishers.fromCompletableFuture(() ->
            asyncOperations.findPage(pagedQuery)
    );
}
 
Example #30
Source File: ExecutorReactiveOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <T, R> Publisher<R> findAll(@NonNull PreparedQuery<T, R> preparedQuery) {
    return Flowable.fromPublisher(Publishers.fromCompletableFuture(() ->
            asyncOperations.findAll(preparedQuery)
    )).flatMap(Flowable::fromIterable);
}