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

The following examples show how to use reactor.core.publisher.Flux#doOnNext() . 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<DataBuffer> encode(Publisher<? extends DataBuffer> inputStream,
		DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
		@Nullable Map<String, Object> hints) {

	Flux<DataBuffer> flux = Flux.from(inputStream);

	if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
		flux = flux.doOnNext(buffer -> {
			String logPrefix = Hints.getLogPrefix(hints);
			logger.debug(logPrefix + "Writing " + buffer.readableByteCount() + " bytes");
		});
	}

	return flux;
}
 
Example 2
static void reactor3() {
    for (int i = 1; i < 100000; i += 1) {
        Flux<Integer> source = Flux.just(1);
        for (int j = 1; j <= i; j++) {
            source = source.doOnNext(e -> { System.out.print(""); });
        }

        try {
            source.subscribe();
        } catch (StackOverflowError ex) {
            System.out.println(i);
            ex.printStackTrace();
            break;
        }
    }
}
 
Example 3
@Override
public Mono<Void> sendOne(ByteBuf frame) {
  FrameType frameType = FrameHeaderCodec.frameType(frame);
  int readableBytes = frame.readableBytes();
  if (!shouldFragment(frameType, readableBytes)) {
    return delegate.sendOne(frame);
  }
  Flux<ByteBuf> fragments = Flux.from(fragmentFrame(alloc(), mtu, frame, frameType));
  if (logger.isDebugEnabled()) {
    fragments =
        fragments.doOnNext(
            byteBuf -> {
              logger.debug(
                  "{} - stream id {} - frame type {} - \n {}",
                  type,
                  FrameHeaderCodec.streamId(byteBuf),
                  FrameHeaderCodec.frameType(byteBuf),
                  ByteBufUtil.prettyHexDump(byteBuf));
            });
  }
  return delegate.send(fragments);
}
 
Example 4
Source Project: spring-analysis-note   File: DataBufferEncoder.java    License: MIT License 5 votes vote down vote up
@Override
public Flux<DataBuffer> encode(Publisher<? extends DataBuffer> inputStream,
		DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
		@Nullable Map<String, Object> hints) {

	Flux<DataBuffer> flux = Flux.from(inputStream);
	if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
		flux = flux.doOnNext(buffer -> logValue(buffer, hints));
	}
	return flux;
}
 
Example 5
Source Project: r2dbc-mysql   File: ReactorNettyClient.java    License: Apache License 2.0 5 votes vote down vote up
ReactorNettyClient(Connection connection, MySqlSslConfiguration ssl, ConnectionContext context) {
    requireNonNull(connection, "connection must not be null");
    requireNonNull(context, "context must not be null");
    requireNonNull(ssl, "ssl must not be null");

    this.connection = connection;
    this.context = context;

    // Note: encoder/decoder should before reactor bridge.
    connection.addHandlerLast(EnvelopeSlicer.NAME, new EnvelopeSlicer())
        .addHandlerLast(MessageDuplexCodec.NAME, new MessageDuplexCodec(context, this.closing, this.requestQueue));

    if (ssl.getSslMode().startSsl()) {
        connection.addHandlerFirst(SslBridgeHandler.NAME, new SslBridgeHandler(context, ssl));
    }

    if (InternalLoggerFactory.getInstance(ReactorNettyClient.class).isTraceEnabled()) {
        // Or just use logger.isTraceEnabled()?
        logger.debug("Connection tracking logging is enabled");
        connection.addHandlerFirst(LoggingHandler.class.getSimpleName(), new LoggingHandler(ReactorNettyClient.class, LogLevel.TRACE));
    }

    Flux<ServerMessage> inbound = connection.inbound().receiveObject()
        .handle(INBOUND_HANDLE);

    if (logger.isDebugEnabled()) {
        inbound = inbound.doOnNext(DEBUG_LOGGING);
    } else if (logger.isInfoEnabled()) {
        inbound = inbound.doOnNext(INFO_LOGGING);
    }

    inbound.subscribe(this.responseProcessor::onNext, throwable -> {
        try {
            logger.error("Connection Error: {}", throwable.getMessage(), throwable);
            responseProcessor.onError(throwable);
        } finally {
            connection.dispose();
        }
    }, this.responseProcessor::onComplete);
}
 
Example 6
Source Project: r2dbc-mysql   File: ReactorNettyClient.java    License: Apache License 2.0 5 votes vote down vote up
ReactorNettyClient(Connection connection, MySqlSslConfiguration ssl, ConnectionContext context) {
    requireNonNull(connection, "connection must not be null");
    requireNonNull(context, "context must not be null");
    requireNonNull(ssl, "ssl must not be null");

    this.connection = connection;
    this.context = context;

    // Note: encoder/decoder should before reactor bridge.
    connection.addHandlerLast(EnvelopeSlicer.NAME, new EnvelopeSlicer())
        .addHandlerLast(MessageDuplexCodec.NAME, new MessageDuplexCodec(context, this.closing, this.requestQueue));

    if (ssl.getSslMode().startSsl()) {
        connection.addHandlerFirst(SslBridgeHandler.NAME, new SslBridgeHandler(context, ssl));
    }

    if (InternalLoggerFactory.getInstance(ReactorNettyClient.class).isTraceEnabled()) {
        // Or just use logger.isTraceEnabled()?
        logger.debug("Connection tracking logging is enabled");
        connection.addHandlerFirst(LoggingHandler.class.getSimpleName(), new LoggingHandler(ReactorNettyClient.class, LogLevel.TRACE));
    }

    Flux<ServerMessage> inbound = connection.inbound().receiveObject()
        .handle(INBOUND_HANDLE);

    if (logger.isDebugEnabled()) {
        inbound = inbound.doOnNext(DEBUG_LOGGING);
    } else if (logger.isInfoEnabled()) {
        inbound = inbound.doOnNext(INFO_LOGGING);
    }

    inbound.subscribe(this.responseProcessor::onNext, throwable -> {
        try {
            logger.error("Connection Error: {}", throwable.getMessage(), throwable);
            responseProcessor.onError(throwable);
        } finally {
            connection.dispose();
        }
    }, this.responseProcessor::onComplete);
}
 
Example 7
Source Project: styx   File: HttpRequestOperation.java    License: Apache License 2.0 5 votes vote down vote up
public Flux<LiveHttpResponse> execute(NettyConnection nettyConnection) {
    AtomicReference<RequestBodyChunkSubscriber> requestRequestBodyChunkSubscriber = new AtomicReference<>();
    requestTime = System.currentTimeMillis();
    executeCount.incrementAndGet();

    Flux<LiveHttpResponse> responseFlux = Flux.create(sink -> {
        if (nettyConnection.isConnected()) {
            RequestBodyChunkSubscriber bodyChunkSubscriber = new RequestBodyChunkSubscriber(request, nettyConnection);
            requestRequestBodyChunkSubscriber.set(bodyChunkSubscriber);
            addProxyBridgeHandlers(nettyConnection, sink);
            new WriteRequestToOrigin(sink, nettyConnection, request, bodyChunkSubscriber)
                    .write();
            if (requestLoggingEnabled) {
                httpRequestMessageLogger.logRequest(request, nettyConnection.getOrigin());
            }
        } else {
            sink.error(new TransportLostException(nettyConnection.channel(), nettyConnection.getOrigin()));
        }
    });

    if (requestLoggingEnabled) {
        responseFlux = responseFlux
                .doOnNext(response -> {
                    httpRequestMessageLogger.logResponse(request, response);
                });
    }
    return responseFlux.map(response ->
                    Requests.doFinally(response, cause -> {
                        if (nettyConnection.isConnected()) {
                            removeProxyBridgeHandlers(nettyConnection);
                            if (requestIsOngoing(requestRequestBodyChunkSubscriber.get())) {
                                LOGGER.warn("Origin responded too quickly to an ongoing request, or it was cancelled. Connection={}, Request={}.",
                                        new Object[]{nettyConnection.channel(), this.request});
                                nettyConnection.close();
                                requestRequestBodyChunkSubscriber.get().dispose();
                            }
                        }
                    }));
}
 
Example 8
public Flux<RpcCallResponse> postProcess(ReactorBatch batch, BatchCallContext context, Flux<RpcCallResponse> result) {
    // Fill batch items with result
    result = result.doOnNext(new ProcessBatchResult(context));

    // Connect batch items to execution
    batch.withExecution(Flux.from(result));

    // Close unprocessed items
    result = result.doFinally((s) -> batch.close());

    return result;
}
 
Example 9
private Mono<Object> decodeContent(MethodParameter parameter, Message<?> message,
		boolean isContentRequired, Flux<DataBuffer> content, MimeType mimeType) {

	ResolvableType targetType = ResolvableType.forMethodParameter(parameter);
	Class<?> resolvedType = targetType.resolve();
	ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
	ResolvableType elementType = (adapter != null ? targetType.getGeneric() : targetType);
	isContentRequired = isContentRequired || (adapter != null && !adapter.supportsEmpty());
	Consumer<Object> validator = getValidator(message, parameter);

	Map<String, Object> hints = Collections.emptyMap();

	for (Decoder<?> decoder : this.decoders) {
		if (decoder.canDecode(elementType, mimeType)) {
			if (adapter != null && adapter.isMultiValue()) {
				Flux<?> flux = content
						.map(buffer -> decoder.decode(buffer, elementType, mimeType, hints))
						.onErrorResume(ex -> Flux.error(handleReadError(parameter, message, ex)));
				if (isContentRequired) {
					flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(parameter, message)));
				}
				if (validator != null) {
					flux = flux.doOnNext(validator);
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				Mono<?> mono = content.next()
						.map(buffer -> decoder.decode(buffer, elementType, mimeType, hints))
						.onErrorResume(ex -> Mono.error(handleReadError(parameter, message, ex)));
				if (isContentRequired) {
					mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(parameter, message)));
				}
				if (validator != null) {
					mono = mono.doOnNext(validator);
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
			}
		}
	}

	return Mono.error(new MethodArgumentResolutionException(
			message, parameter, "Cannot decode to [" + targetType + "]" + message));
}
 
Example 10
/**
 * Read the body from a method argument with {@link HttpMessageReader}.
 * @param bodyParam represents the element type for the body
 * @param actualParam the actual method argument type; possibly different
 * from {@code bodyParam}, e.g. for an {@code HttpEntity} argument
 * @param isBodyRequired true if the body is required
 * @param bindingContext the binding context to use
 * @param exchange the current exchange
 * @return a Mono with the value to use for the method argument
 * @since 5.0.2
 */
protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParameter actualParam,
		boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {

	ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParam);
	ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
	Class<?> resolvedType = bodyType.resolve();
	ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
	ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
	isBodyRequired = isBodyRequired || (adapter != null && !adapter.supportsEmpty());

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	MediaType contentType = request.getHeaders().getContentType();
	MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
	Object[] hints = extractValidationHints(bodyParam);

	if (mediaType.isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED)) {
		return Mono.error(new IllegalStateException(
				"In a WebFlux application, form data is accessed via ServerWebExchange.getFormData()."));
	}

	if (logger.isDebugEnabled()) {
		logger.debug(exchange.getLogPrefix() + (contentType != null ?
				"Content-Type:" + contentType :
				"No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
	}

	for (HttpMessageReader<?> reader : getMessageReaders()) {
		if (reader.canRead(elementType, mediaType)) {
			Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			if (adapter != null && adapter.isMultiValue()) {
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
				}
				Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
				flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					flux = flux.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
				}
				Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
				mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					mono = mono.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
			}
		}
	}

	// No compatible reader but body may be empty..

	HttpMethod method = request.getMethod();
	if (contentType == null && method != null && SUPPORTED_METHODS.contains(method)) {
		Flux<DataBuffer> body = request.getBody().doOnNext(buffer -> {
			DataBufferUtils.release(buffer);
			// Body not empty, back to 415..
			throw new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType);
		});
		if (isBodyRequired) {
			body = body.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
		}
		return (adapter != null ? Mono.just(adapter.fromPublisher(body)) : Mono.from(body));
	}

	return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType));
}
 
Example 11
Source Project: micronaut-kafka   File: BookListener.java    License: Apache License 2.0 4 votes vote down vote up
@Topic("all-the-books")
public Flux<Book> receiveFlux(Flux<Book> books) {
    return books.doOnNext(book ->
            System.out.println("Got Book = " + book.getTitle())
    );
}
 
Example 12
/**
 * Read the body from a method argument with {@link HttpMessageReader}.
 * @param bodyParam represents the element type for the body
 * @param actualParam the actual method argument type; possibly different
 * from {@code bodyParam}, e.g. for an {@code HttpEntity} argument
 * @param isBodyRequired true if the body is required
 * @param bindingContext the binding context to use
 * @param exchange the current exchange
 * @return a Mono with the value to use for the method argument
 * @since 5.0.2
 */
protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParameter actualParam,
		boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {

	ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParam);
	ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
	Class<?> resolvedType = bodyType.resolve();
	ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
	ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
	isBodyRequired = isBodyRequired || (adapter != null && !adapter.supportsEmpty());

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	MediaType contentType = request.getHeaders().getContentType();
	MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
	Object[] hints = extractValidationHints(bodyParam);

	if (logger.isDebugEnabled()) {
		logger.debug(exchange.getLogPrefix() + (contentType != null ?
				"Content-Type:" + contentType :
				"No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
	}

	for (HttpMessageReader<?> reader : getMessageReaders()) {
		if (reader.canRead(elementType, mediaType)) {
			Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
			if (adapter != null && adapter.isMultiValue()) {
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
				}
				Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
				flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					flux = flux.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				if (logger.isDebugEnabled()) {
					logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
				}
				Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
				mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
				if (isBodyRequired) {
					mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
				}
				if (hints != null) {
					mono = mono.doOnNext(target ->
							validate(target, hints, bodyParam, bindingContext, exchange));
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
			}
		}
	}

	// No compatible reader but body may be empty..

	HttpMethod method = request.getMethod();
	if (contentType == null && method != null && SUPPORTED_METHODS.contains(method)) {
		Flux<DataBuffer> body = request.getBody().doOnNext(o -> {
			// Body not empty, back to 415..
			throw new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType);
		});
		if (isBodyRequired) {
			body = body.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
		}
		return (adapter != null ? Mono.just(adapter.fromPublisher(body)) : Mono.from(body));
	}

	return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType));
}