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

The following examples show how to use io.micronaut.core.async.publisher.Publishers#convertPublisher() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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);
    }
}
 
Example 13
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 14
Source File: DefaultSaveEntityReactiveInterceptor.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Publisher<Object> publisher = reactiveOperations.persist(getInsertOperation(context));
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}
 
Example 15
Source File: DefaultUpdateEntityReactiveInterceptor.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) {
    Publisher<Object> publisher = reactiveOperations.update(getUpdateOperation(context));
    return Publishers.convertPublisher(publisher, context.getReturnType().getType());
}