Java Code Examples for reactor.core.publisher.Flux#error()

The following examples show how to use reactor.core.publisher.Flux#error() . These examples are extracted from open source projects. 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
@Override
public Flux<Part> read(ResolvableType elementType, ReactiveHttpInputMessage message, Map<String, Object> hints) {
	byte[] boundary = boundary(message);
	if (boundary == null) {
		return Flux.error(new CodecException("No multipart boundary found in Content-Type: \"" +
				message.getHeaders().getContentType() + "\""));
	}
	if (logger.isTraceEnabled()) {
		logger.trace("Boundary: " + toString(boundary));
	}

	byte[] boundaryNeedle = concat(BOUNDARY_PREFIX, boundary);
	Flux<DataBuffer> body = skipUntilFirstBoundary(message.getBody(), boundary);

	return DataBufferUtils.split(body, boundaryNeedle)
			.takeWhile(DefaultMultipartMessageReader::notLastBoundary)
			.map(DefaultMultipartMessageReader::toPart)
			.doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release)
			.doOnDiscard(DefaultPart.class, part -> DataBufferUtils.release(part.body));
}
 
Example 2
/**
 * Implements a bidirectional stream → stream call as {@link Flux} → {@link Flux}, where both the client
 * and the server independently stream to each other.
 */
@SuppressWarnings("unchecked")
public static <TRequest, TResponse> Flux<TResponse> manyToMany(
        Flux<TRequest> fluxSource,
        Function<StreamObserver<TResponse>, StreamObserver<TRequest>> delegate,
        CallOptions options) {
    try {

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

        ReactorSubscriberAndClientProducer<TRequest> subscriberAndGRPCProducer =
            fluxSource.subscribeWith(new ReactorSubscriberAndClientProducer<>());
        ReactorClientStreamObserverAndPublisher<TResponse> observerAndPublisher =
            new ReactorClientStreamObserverAndPublisher<>(
                s -> subscriberAndGRPCProducer.subscribe((CallStreamObserver<TRequest>) s),
                subscriberAndGRPCProducer::cancel, prefetch, lowTide
            );
        delegate.apply(observerAndPublisher);

        return Flux.from(observerAndPublisher);
    } catch (Throwable throwable) {
        return Flux.error(throwable);
    }
}
 
Example 3
private Flux<ApiCallRcWith<List<MaxVlmSizeCandidatePojo>>> queryMaxVlmSizeInScope(
    AutoSelectFilterApi selectFilter,
    Map<StorPool.Key, Long> thinFreeCapacities
)
{
    Flux<ApiCallRcWith<List<MaxVlmSizeCandidatePojo>>> flux;
    if (selectFilter.getReplicaCount() == null)
    {
        flux = Flux.error(
            new ApiRcException(ApiCallRcImpl.simpleEntry(
                ApiConsts.FAIL_INVLD_PLACE_COUNT,
                "Replica count is required for this operation")
            )
        );
    }
    else
    {
        flux = qmvsHelper.queryMaxVlmSize(selectFilter, null, 0, thinFreeCapacities);
    }

    return flux;
}
 
Example 4
Source Project: java-technology-stack   File: BodyExtractors.java    License: MIT License 6 votes vote down vote up
private static <T> Flux<T> unsupportedErrorHandler(
		ReactiveHttpInputMessage message, UnsupportedMediaTypeException ex) {

	Flux<T> result;
	if (message.getHeaders().getContentType() == null) {
		// Maybe it's okay there is no content type, if there is no content..
		result = message.getBody().map(buffer -> {
			DataBufferUtils.release(buffer);
			throw ex;
		});
	}
	else {
		result = message instanceof ClientHttpResponse ?
				consumeAndCancel(message).thenMany(Flux.error(ex)) : Flux.error(ex);
	}
	return result;
}
 
Example 5
@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 6
Source Project: reactor-core   File: FluxSpecTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
	public void fluxCanFilterTerminalStates() {
//		"A deferred Flux can filter terminal states"
//		given: "a composable with an initial value"
		Flux<String> stream = Flux.just("test");

//		when:"the complete signal is observed and flux is retrieved"
		Mono<Void> tap = stream.then();

//		then: "it is available"
		assertThat(tap.block()).isNull();

//		when: "the error signal is observed and flux is retrieved"
		stream = Flux.error(new Exception());
		final Mono<Void> errorTap = stream.then();

//		then: "it is available"
		assertThatExceptionOfType(Exception.class)
				.isThrownBy(errorTap::block);
	}
 
Example 7
@Override
@NotNull
public Flux<Payload> requestStream(Payload payload) {
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
    GSVRoutingMetadata routingMetaData = getGsvRoutingMetadata(compositeMetadata);
    if (routingMetaData == null) {
        ReferenceCountUtil.safeRelease(payload);
        return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
    }
    MessageMimeTypeMetadata dataEncodingMetadata = getDataEncodingMetadata(compositeMetadata);
    if (dataEncodingMetadata == null) {
        ReferenceCountUtil.safeRelease(payload);
        return Flux.error(new InvalidException(RsocketErrorCode.message("RST-700404")));
    }
    Flux<Payload> result = localRequestStream(routingMetaData, dataEncodingMetadata, compositeMetadata.getAcceptMimeTypesMetadata(), payload);
    return injectTraceContext(result, compositeMetadata);
}
 
Example 8
public Flux<Payload> requestChannel(Payload signal, Publisher<Payload> payloads) {
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(signal.metadata());
    GSVRoutingMetadata routingMetaData = getGsvRoutingMetadata(compositeMetadata);
    if (routingMetaData == null) {
        ReferenceCountUtil.safeRelease(signal);
        return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404")));
    }
    MessageMimeTypeMetadata dataEncodingMetadata = getDataEncodingMetadata(compositeMetadata);
    if (dataEncodingMetadata == null) {
        ReferenceCountUtil.safeRelease(signal);
        return Flux.error(new InvalidException(RsocketErrorCode.message("RST-700404")));
    }
    if (payloads instanceof Flux) {
        return localRequestChannel(routingMetaData, dataEncodingMetadata, compositeMetadata.getAcceptMimeTypesMetadata(), signal, ((Flux<Payload>) payloads).skip(1));
    } else {
        return localRequestChannel(routingMetaData, dataEncodingMetadata, compositeMetadata.getAcceptMimeTypesMetadata(), signal, Flux.from(payloads).skip(1));
    }
}
 
Example 9
@Test
public void createFlux() {
    Flux<String> stream1 = Flux.just("Hello", "world");
    Flux<Integer> stream2 = Flux.fromArray(new Integer[]{1, 2, 3});
    Flux<Integer> stream3 = Flux.range(1, 500);

    Flux<String> emptyStream = Flux.empty();
    Flux<String> streamWithError = Flux.error(new RuntimeException("Hi!"));
}
 
Example 10
@Override
public Flux<String> doSomethingFlux(boolean throwException) throws IOException {

    if (throwException) {
        return Flux.error(new IllegalArgumentException("FailedFlux"));
    }

    return Flux.fromArray(Arrays.array("test", "test2"));
}
 
Example 11
public Flux<ReplicatorEvent<TaskRelocationSnapshot, TaskRelocationEvent>> onEvent(TaskRelocationEvent event) {
    try {
        if (lastSnapshotRef.get() != null) {
            return processSnapshotUpdate(event);
        }
        if (event.equals(TaskRelocationEvent.newSnapshotEndEvent())) {
            return buildInitialCache();
        }
        snapshotEvents.add(event);
    } catch (Exception e) {
        logger.warn("Unexpected error when handling the relocation event: {}", event, e);
        return Flux.error(e); // Return error to force the cache reconnect.
    }
    return Flux.empty();
}
 
Example 12
@Test
public void encodeError() {
	Flux<Pojo> input = Flux.error(RuntimeException::new);

	testEncode(input, Pojo.class, step -> step
			.expectError(RuntimeException.class)
			.verify());
}
 
Example 13
Source Project: styx   File: StyxBackendServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
private Flux<LiveHttpResponse> retry(
        LiveHttpRequest request,
        RetryPolicyContext retryContext,
        List<RemoteHost> previousOrigins,
        int attempt,
        Throwable cause,
        HttpInterceptor.Context context) {
    LoadBalancer.Preferences lbContext = new LoadBalancer.Preferences() {
        @Override
        public Optional<String> preferredOrigins() {
            return Optional.empty();
        }

        @Override
        public List<Origin> avoidOrigins() {
            return previousOrigins.stream()
                    .map(RemoteHost::origin)
                    .collect(Collectors.toList());
        }
    };

    if (this.retryPolicy.evaluate(retryContext, loadBalancer, lbContext).shouldRetry()) {
        return Flux.from(sendRequest(request, previousOrigins, attempt, context));
    } else {
        return Flux.error(cause);
    }
}
 
Example 14
@Override
@Bulkhead(name = "backendB")
public Flux<String> fluxFailure() {
    return Flux.error(new IOException("BAM!"));
}
 
Example 15
Source Project: resilience4j   File: TestDummyService.java    License: Apache License 2.0 4 votes vote down vote up
default Flux<String> fluxError() {
    return Flux.error(new RuntimeException("Test"));
}
 
Example 16
@Override
public Flux<HelloResponse> sayHelloRespStream(Mono<HelloRequest> reactorRequest) {
    return Flux.error(new StatusRuntimeException(Status.INTERNAL));
}
 
Example 17
public Flux<DataBuffer> getBody() {
	return (this.body != null ? this.body :
			Flux.error(new IllegalStateException("Body has not been written yet")));
}
 
Example 18
@Override
public Flux<Payload> requestChannel(Payload payload, Flux<Payload> publisher) {
  return Flux.error(new UnsupportedOperationException("Request-Channel not implemented."));
}
 
Example 19
Source Project: rsocket-java   File: RSocket.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Request-Channel interaction model of {@code RSocket}.
 *
 * @param payloads Stream of request payloads.
 * @return Stream of response payloads.
 */
default Flux<Payload> requestChannel(Publisher<Payload> payloads) {
  return Flux.error(new UnsupportedOperationException("Request-Channel not implemented."));
}
 
Example 20
Source Project: rsocket-java   File: RSocket.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Request-Stream interaction model of {@code RSocket}.
 *
 * @param payload Request payload.
 * @return {@code Publisher} containing the stream of {@code Payload}s representing the response.
 */
default Flux<Payload> requestStream(Payload payload) {
  payload.release();
  return Flux.error(new UnsupportedOperationException("Request-Stream not implemented."));
}