Java Code Examples for reactor.core.publisher.Mono#flatMapMany()

The following examples show how to use reactor.core.publisher.Mono#flatMapMany() . 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: RSocketBrokerResponderHandler.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
public Flux<Payload> requestChannel(Payload signal, Publisher<Payload> payloads) {
    BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(signal.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8));
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(signal.metadata());
        gsvRoutingMetadata = compositeMetadata.getRoutingMetaData();
        if (gsvRoutingMetadata == null) {
            return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
        }
    }
    Mono<RSocket> destination = findDestination(gsvRoutingMetadata);
    return destination.flatMapMany(rsocket -> {
        recordServiceInvoke(principal.getName(), gsvRoutingMetadata.gsv());
        metrics(gsvRoutingMetadata, "0x07");
        return rsocket.requestChannel(payloads);
    });
}
 
Example 2
Source File: UpstreamForwardRSocket.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
public @NotNull Flux<Payload> requestStream(@NotNull Payload payload) {
    BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(payload.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8));
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
        gsvRoutingMetadata = compositeMetadata.getRoutingMetaData();
        if (gsvRoutingMetadata == null) {
            return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
        }
    }
    Mono<RSocket> destination = findDestination(gsvRoutingMetadata);
    if (this.filterChain.isFiltersPresent()) {
        RSocketExchange requestContext = new RSocketExchange(FrameType.REQUEST_STREAM, gsvRoutingMetadata, payload, this.upstreamBrokerMetadata);
        destination = filterChain.filter(requestContext).then(destination);
    }
    return destination.flatMapMany(rsocket -> {
        metrics(gsvRoutingMetadata, "0x06");
        return rsocket.requestStream(payload);
    });
}
 
Example 3
Source File: UpstreamForwardRSocket.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
public Flux<Payload> requestChannel(Payload signal, Publisher<Payload> payloads) {
    BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(signal.metadata());
    GSVRoutingMetadata gsvRoutingMetadata;
    if (binaryRoutingMetadata != null) {
        gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8));
    } else {
        RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(signal.metadata());
        gsvRoutingMetadata = compositeMetadata.getRoutingMetaData();
        if (gsvRoutingMetadata == null) {
            return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
        }
    }
    Mono<RSocket> destination = findDestination(gsvRoutingMetadata);
    return destination.flatMapMany(rsocket -> {
        metrics(gsvRoutingMetadata, "0x07");
        return rsocket.requestChannel(payloads);
    });
}
 
Example 4
Source File: GrpcApiService.java    From staccato with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<ApiItemBytes> search(Mono<ApiRequest> request) {
    log.debug("Incoming gRPC api request.");

    return request
            //double[] bbox, String datetime, String query, Integer limit, Integer next, FieldsExtension fields, String[] ids, String[] collections, Object intersects
            .flatMapMany(r -> {
                        try {
                            return apiService.getItemsFlux(SearchRequestUtils.generateSearchRequest(Doubles.toArray(r.getBboxList()),
                                    r.getTime(), r.getSearch(), r.getLimit(), r.getNext(),
                                    mapper.readValue(r.getFields(), FieldsExtension.class),
                                    r.getIdsList().toArray(new String[r.getIdsCount()]),
                                    r.getCollectionsList().toArray(new String[r.getCollectionsCount()]),
                                    r.getIntersects(), null))
                                    .map(item -> SerializationUtils.serializeItem(item, mapper))
                                    .map(item -> ApiItemBytes.newBuilder().setItem(ByteString.copyFrom(item)).build());
                        } catch (IOException e) {
                            return Mono.error(new RuntimeException("Error deserializing fields property.", e));
                        }
                    }
            );
}
 
Example 5
Source File: ClientCalls.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Implements a unary → stream call as {@link Mono} → {@link Flux}, where the server responds with a
 * stream of messages.
 */
public static <TRequest, TResponse> Flux<TResponse> oneToMany(
        Mono<TRequest> monoSource,
        BiConsumer<TRequest, StreamObserver<TResponse>> delegate,
        CallOptions options) {
    try {

        final int prefetch = ReactorCallOptions.getPrefetch(options);
        final int lowTide = ReactorCallOptions.getLowTide(options);

        return monoSource
                .flatMapMany(request -> {
                    ReactorClientStreamObserverAndPublisher<TResponse> consumerStreamObserver =
                        new ReactorClientStreamObserverAndPublisher<>(null, null, prefetch, lowTide);

                    delegate.accept(request, consumerStreamObserver);

                    return consumerStreamObserver;
                });
    } catch (Throwable throwable) {
        return Flux.error(throwable);
    }
}
 
Example 6
Source File: EndToEndIntegrationTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Flux<HelloResponse> sayHelloRespStream(Mono<HelloRequest> reactorRequest) {
    return reactorRequest.flatMapMany(protoRequest -> Flux.just(
            greet("Hello", protoRequest),
            greet("Hi", protoRequest),
            greet("Greetings", protoRequest)));
}
 
Example 7
Source File: RedissonReactiveClusterServerCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<RedisClientInfo> getClientList(RedisClusterNode node) {
    MasterSlaveEntry entry = getEntry(node);
    Mono<List<String>> m = executorService.reactive(() -> {
        return executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
    });
    return m.flatMapMany(s -> Flux.fromIterable(CONVERTER.convert(s.toArray(new String[s.size()]))));
}
 
Example 8
Source File: RedissonReactiveSetCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ByteBuffer> sPop(SPopCommand command) {
    Assert.notNull(command.getKey(), "Key must not be null!");
    
    byte[] keyBuf = toByteArray(command.getKey());
    Mono<Set<byte[]>> m = write(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.SPOP, keyBuf, command.getCount());
    return m.flatMapMany(v -> Flux.fromIterable(v).map(e -> ByteBuffer.wrap(e)));
}
 
Example 9
Source File: RedissonReactiveClusterServerCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<RedisClientInfo> getClientList(RedisClusterNode node) {
    MasterSlaveEntry entry = getEntry(node);
    Mono<List<String>> m = executorService.reactive(() -> {
        return executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
    });
    return m.flatMapMany(s -> Flux.fromIterable(CONVERTER.convert(s.toArray(new String[s.size()]))));
}
 
Example 10
Source File: RedissonReactiveSetCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ByteBuffer> sPop(SPopCommand command) {
    Assert.notNull(command.getKey(), "Key must not be null!");
    
    byte[] keyBuf = toByteArray(command.getKey());
    Mono<Set<byte[]>> m = write(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.SPOP, keyBuf, command.getCount());
    return m.flatMapMany(v -> Flux.fromIterable(v).map(e -> ByteBuffer.wrap(e)));
}
 
Example 11
Source File: RedissonReactiveClusterServerCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<RedisClientInfo> getClientList(RedisClusterNode node) {
    MasterSlaveEntry entry = getEntry(node);
    Mono<List<String>> m = executorService.reactive(() -> {
        return executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
    });
    return m.flatMapMany(s -> Flux.fromIterable(CONVERTER.convert(s.toArray(new String[s.size()]))));
}
 
Example 12
Source File: RedissonReactiveSetCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ByteBuffer> sPop(SPopCommand command) {
    Assert.notNull(command.getKey(), "Key must not be null!");
    
    byte[] keyBuf = toByteArray(command.getKey());
    Mono<Set<byte[]>> m = write(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.SPOP, keyBuf, command.getCount());
    return m.flatMapMany(v -> Flux.fromIterable(v).map(e -> ByteBuffer.wrap(e)));
}
 
Example 13
Source File: RedissonReactiveClusterServerCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<RedisClientInfo> getClientList(RedisClusterNode node) {
    MasterSlaveEntry entry = getEntry(node);
    Mono<List<String>> m = executorService.reactive(() -> {
        return executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
    });
    return m.flatMapMany(s -> Flux.fromIterable(CONVERTER.convert(s.toArray(new String[s.size()]))));
}
 
Example 14
Source File: WebsocketFinalizer.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public <V> Flux<V> handle(BiFunction<? super WebsocketInbound, ? super WebsocketOutbound, ? extends Publisher<V>> receiver) {
	@SuppressWarnings("unchecked")
	Mono<WebsocketClientOperations> connector = (Mono<WebsocketClientOperations>) connect();
	return connector.flatMapMany(c -> Flux.from(receiver.apply(c, c))
	                                      .doFinally(s -> HttpClientFinalizer.discard(c)));
}
 
Example 15
Source File: Neo4jQueryExecution.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(PreparedQuery preparedQuery, boolean asCollectionQuery) {

	Mono<ReactiveNeo4jOperations.ExecutableQuery> executableQuery = neo4jOperations
		.toExecutableQuery(preparedQuery);
	if (asCollectionQuery) {
		return executableQuery.flatMapMany(q -> q.getResults());
	} else {
		return executableQuery.flatMap(q -> q.getSingleResult());
	}
}
 
Example 16
Source File: ReactiveHttpClient.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
default Publisher<Object> executeRequest(ReactiveHttpRequest request, Type returnPublisherType) {
  Mono<ReactiveHttpResponse> response = executeRequest(request);
  if (returnPublisherType == Mono.class) {
    return response.flatMap(resp -> (Mono<Object>) resp.body());
  } else {
    return response.flatMapMany(ReactiveHttpResponse::body);
  }
}
 
Example 17
Source File: XmlEventDecoder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings({"rawtypes", "unchecked"})  // on JDK 9 where XMLEventReader is Iterator<Object>
public Flux<XMLEvent> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	Flux<DataBuffer> flux = Flux.from(inputStream);
	if (this.useAalto) {
		AaltoDataBufferToXmlEvent aaltoMapper = new AaltoDataBufferToXmlEvent();
		return flux.flatMap(aaltoMapper)
				.doFinally(signalType -> aaltoMapper.endOfInput());
	}
	else {
		Mono<DataBuffer> singleBuffer = DataBufferUtils.join(flux);
		return singleBuffer.
				flatMapMany(dataBuffer -> {
					try {
						InputStream is = dataBuffer.asInputStream();
						Iterator eventReader = inputFactory.createXMLEventReader(is);
						return Flux.fromIterable((Iterable<XMLEvent>) () -> eventReader)
								.doFinally(t -> DataBufferUtils.release(dataBuffer));
					}
					catch (XMLStreamException ex) {
						return Mono.error(ex);
					}
				});
	}
}
 
Example 18
Source File: RedissonReactiveSetCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ByteBuffer> sPop(SPopCommand command) {
    Assert.notNull(command.getKey(), "Key must not be null!");
    
    byte[] keyBuf = toByteArray(command.getKey());
    Mono<Set<byte[]>> m = write(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.SPOP, keyBuf, command.getCount());
    return m.flatMapMany(v -> Flux.fromIterable(v).map(e -> ByteBuffer.wrap(e)));
}
 
Example 19
Source File: ReactivePreAuthorizeAspect.java    From light-security with Apache License 2.0 5 votes vote down vote up
/**
 * 参考了org.springframework.security.access.prepost.PrePostAdviceReactiveMethodInterceptor#invoke的写法
 *
 * @param point 切点
 * @return obj
 */
@Around("@annotation(com.itmuch.lightsecurity.annotation.PreAuthorize) ")
public Object preAuth(ProceedingJoinPoint point) {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    if (method.isAnnotationPresent(PreAuthorize.class)) {
        PreAuthorize preAuthorize = method.getAnnotation(PreAuthorize.class);

        String expression = preAuthorize.value();
        Mono<Boolean> mono = ReactiveSpringElCheckUtil.check(
                new StandardEvaluationContext(reactivePreAuthorizeExpressionRoot),
                expression)
                .filter(t -> t)
                .switchIfEmpty(Mono.defer(() -> Mono.error(new LightSecurityException("Access Denied."))));

        Class<?> returnType = method.getReturnType();

        if (Mono.class.isAssignableFrom(returnType)) {
            return mono
                    .flatMap(
                            auth -> this.proceed(point)
                    );
        }

        if (Flux.class.isAssignableFrom(returnType)) {
            return mono
                    .flatMapMany(
                            auth -> this.<Flux<?>>proceed(point)
                    );
        }

        return mono
                .flatMapMany(auth -> Flux.from(
                        this.proceed(point))
                );

    }
    return this.proceed(point);
}
 
Example 20
Source File: FluxPublisherHttpClient.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<?> executeRequest(ReactiveHttpRequest request) {
	Mono<ReactiveHttpResponse> response = reactiveHttpClient.executeRequest(request);
	return response.flatMapMany(ReactiveHttpResponse::body);
}