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

The following examples show how to use reactor.core.publisher.Mono#doOnNext() . 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: DingTalkNotifier.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
private Mono<HashMap> checkResult(Mono<HashMap> msg) {
    return msg.doOnNext(map -> {
        String code = String.valueOf(map.get("errcode"));
        if ("0".equals(code)) {
            log.info("发送钉钉通知成功");
        } else {
            log.warn("发送钉钉通知失败:{}", map);
            throw new BusinessException("发送钉钉通知失败:" + map.get("errmsg"), code);
        }
    });
}
 
Example 2
Source File: WeixinCorpNotifier.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
private Mono<HashMap> checkResult(Mono<HashMap> msg) {
    return msg.doOnNext(map -> {
        String code = String.valueOf(map.get("errcode"));
        if ("0".equals(code)) {
            log.info("发送微信企业通知成功");
        } else {
            log.warn("发送微信企业通知失败:{}", map);
            throw new BusinessException("发送微信企业通知失败:" + map.get("errmsg"), code);
        }
    });
}
 
Example 3
Source File: UserRepositoryImpl.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> saveUser(Mono<User> monoUser) {
	Mono<User> userMono = monoUser.doOnNext(user -> {
		// do post
		users.put(user.getId(), user);

		// log on console
		System.out.println("########### POST:" + user);
	});

	return userMono.then();
}
 
Example 4
Source File: UserRepositoryImpl.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<User> putUser(Long id, Mono<User> monoUser) {
	Mono<User> userMono = monoUser.doOnNext(user -> {
		// reset user.Id
		user.setId(id);

		// do put
		users.put(id, user);

		// log on console
		System.out.println("########### PUT:" + user);
	});

	return userMono;
}
 
Example 5
Source File: ReactorDemo.java    From reactive-streams-in-java with Apache License 2.0 5 votes vote down vote up
public static void runComputation() throws Exception {
    StringBuffer sb = new StringBuffer();
    Mono<String> source = Mono.fromCallable(() -> { // 1
        Thread.sleep(1000); // imitate expensive computation
        return "Done";
    });
    source.doOnNext((x) -> System.out.println("Completed runComputation"));

    Flux<String> background = source.subscribeOn(Schedulers.elastic())
            .flux(); // 2

    Flux<String> foreground = background.publishOn(Schedulers.immediate());

    foreground.subscribe(System.out::println, Throwable::printStackTrace);// 4
}
 
Example 6
Source File: AuthenticationStepsOperator.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private Mono<Object> createMono(Iterable<Node<?>> steps) {

		Mono<Object> state = Mono.just(Undefinded.INSTANCE);

		for (Node<?> o : steps) {

			if (logger.isDebugEnabled()) {
				logger.debug(String.format("Executing %s with current state %s", o, state));
			}

			if (o instanceof HttpRequestNode) {
				state = state.flatMap(stateObject -> doHttpRequest((HttpRequestNode<Object>) o, stateObject));
			}

			if (o instanceof MapStep) {
				state = state.map(stateObject -> doMapStep((MapStep<Object, Object>) o, stateObject));
			}

			if (o instanceof ZipStep) {
				state = state.zipWith(doZipStep((ZipStep<Object, Object>) o))
						.map(it -> Pair.of(it.getT1(), it.getT2()));
			}

			if (o instanceof OnNextStep) {
				state = state.doOnNext(stateObject -> doOnNext((OnNextStep<Object>) o, stateObject));
			}

			if (o instanceof SupplierStep<?>) {
				state = state.map(stateObject -> doSupplierStep((SupplierStep<Object>) o));
			}

			if (logger.isDebugEnabled()) {
				logger.debug(String.format("Executed %s with current state %s", o, state));
			}
		}
		return state;
	}
 
Example 7
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
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 8
Source File: AbstractMessageReaderArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * 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 9
Source File: AbstractMessageReaderArgumentResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * 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));
}
 
Example 10
Source File: LoggerReactiveHttpClient.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<byte[]> bodyData() {
  Mono<byte[]> publisher = getResponse().bodyData();

  return publisher.doOnNext(responseBodyLogger(start));
}
 
Example 11
Source File: LoggerReactiveHttpClient.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<byte[]> bodyData() {
  Mono<byte[]> publisher = getResponse().bodyData();

  return publisher.doOnNext(responseBodyLogger(start));
}