use of reactor.core.publisher.Mono in project spring-cloud-sleuth by spring-cloud.
the class TraceUserInfoRestTemplateCustomizer method wrapHttpClientRequestSending.
Mono<HttpClientResponse> wrapHttpClientRequestSending(ProceedingJoinPoint pjp, HttpMethod method, String url, Function<? super HttpClientRequest, ? extends Publisher<Void>> handler) throws Throwable {
// add headers and set CS
final Span currentSpan = this.tracer.currentSpan();
final AtomicReference<Span> span = new AtomicReference<>();
Function<HttpClientRequest, Publisher<Void>> combinedFunction = req -> {
try (Tracer.SpanInScope spanInScope = this.tracer.withSpanInScope(currentSpan)) {
io.netty.handler.codec.http.HttpHeaders originalHeaders = req.requestHeaders().copy();
io.netty.handler.codec.http.HttpHeaders tracedHeaders = req.requestHeaders();
span.set(this.handler.handleSend(this.injector, tracedHeaders, req));
io.netty.handler.codec.http.HttpHeaders addedHeaders = tracedHeaders.copy();
originalHeaders.forEach(header -> addedHeaders.remove(header.getKey()));
try (Tracer.SpanInScope clientInScope = this.tracer.withSpanInScope(span.get())) {
if (log.isDebugEnabled()) {
log.debug("Created a new client span for Netty client");
}
return handle(handler, new TracedHttpClientRequest(req, addedHeaders));
}
}
};
// run
Mono<HttpClientResponse> responseMono = (Mono<HttpClientResponse>) pjp.proceed(new Object[] { method, url, combinedFunction });
// get response
return responseMono.doOnSuccessOrError((httpClientResponse, throwable) -> {
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.get())) {
// status codes and CR
this.handler.handleReceive(httpClientResponse, throwable, span.get());
if (log.isDebugEnabled()) {
log.debug("Setting client sent spans");
}
}
});
}
use of reactor.core.publisher.Mono in project spring-cloud-sleuth by spring-cloud.
the class TraceWebFilter method filter.
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
if (tracer().currentSpan() != null) {
// clear any previous trace
tracer().withSpanInScope(null);
}
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String uri = request.getPath().pathWithinApplication().value();
if (log.isDebugEnabled()) {
log.debug("Received a request to uri [" + uri + "]");
}
Span spanFromAttribute = getSpanFromAttribute(exchange);
final String CONTEXT_ERROR = "sleuth.webfilter.context.error";
return chain.filter(exchange).compose(f -> f.then(Mono.subscriberContext()).onErrorResume(t -> Mono.subscriberContext().map(c -> c.put(CONTEXT_ERROR, t))).flatMap(c -> {
// reactivate span from context
Span span = spanFromContext(c);
Mono<Void> continuation;
Throwable t = null;
if (c.hasKey(CONTEXT_ERROR)) {
t = c.get(CONTEXT_ERROR);
continuation = Mono.error(t);
} else {
continuation = Mono.empty();
}
Object attribute = exchange.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
if (attribute instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) attribute;
addClassMethodTag(handlerMethod, span);
addClassNameTag(handlerMethod, span);
}
addResponseTagsForSpanWithoutParent(exchange, response, span);
handler().handleSend(response, t, span);
if (log.isDebugEnabled()) {
log.debug("Handled send of " + span);
}
return continuation;
}).subscriberContext(c -> {
Span span;
if (c.hasKey(Span.class)) {
Span parent = c.get(Span.class);
span = tracer().nextSpan(TraceContextOrSamplingFlags.create(parent.context())).start();
if (log.isDebugEnabled()) {
log.debug("Found span in reactor context" + span);
}
} else {
if (spanFromAttribute != null) {
span = spanFromAttribute;
if (log.isDebugEnabled()) {
log.debug("Found span in attribute " + span);
}
} else {
span = handler().handleReceive(extractor(), request.getHeaders(), request);
if (log.isDebugEnabled()) {
log.debug("Handled receive of span " + span);
}
}
exchange.getAttributes().put(TRACE_REQUEST_ATTR, span);
}
return c.put(Span.class, span);
}));
}
use of reactor.core.publisher.Mono in project spring-integration by spring-projects.
the class MessagingGatewaySupport method doSendAndReceiveMessageReactive.
@SuppressWarnings("unchecked")
private Mono<Message<?>> doSendAndReceiveMessageReactive(MessageChannel requestChannel, Object object, boolean error) {
return Mono.defer(() -> {
Message<?> message;
try {
message = object instanceof Message<?> ? (Message<?>) object : this.requestMapper.toMessage(object);
message = this.historyWritingPostProcessor.postProcessMessage(message);
} catch (Exception e) {
throw new MessageMappingException("Cannot map to message: " + object, e);
}
Object originalReplyChannelHeader = message.getHeaders().getReplyChannel();
Object originalErrorChannelHeader = message.getHeaders().getErrorChannel();
FutureReplyChannel replyChannel = new FutureReplyChannel();
Message<?> requestMessage = MutableMessageBuilder.fromMessage(message).setReplyChannel(replyChannel).setHeader(this.messagingTemplate.getSendTimeoutHeader(), null).setHeader(this.messagingTemplate.getReceiveTimeoutHeader(), null).setErrorChannel(replyChannel).build();
if (requestChannel instanceof ReactiveStreamsSubscribableChannel) {
((ReactiveStreamsSubscribableChannel) requestChannel).subscribeTo(Mono.just(requestMessage));
} else {
long sendTimeout = sendTimeout(requestMessage);
boolean sent = sendTimeout >= 0 ? requestChannel.send(requestMessage, sendTimeout) : requestChannel.send(requestMessage);
if (!sent) {
throw new MessageDeliveryException(requestMessage, "Failed to send message to channel '" + requestChannel + "' within timeout: " + sendTimeout);
}
}
return Mono.fromFuture(replyChannel.messageFuture).doOnSubscribe(s -> {
if (!error && this.countsEnabled) {
this.messageCount.incrementAndGet();
}
}).<Message<?>>map(replyMessage -> MessageBuilder.fromMessage(replyMessage).setHeader(MessageHeaders.REPLY_CHANNEL, originalReplyChannelHeader).setHeader(MessageHeaders.ERROR_CHANNEL, originalErrorChannelHeader).build()).onErrorResume(t -> error ? Mono.error(t) : handleSendError(requestMessage, t));
});
}
use of reactor.core.publisher.Mono in project spring-integration by spring-projects.
the class WebFluxRequestExecutingMessageHandler method exchange.
@Override
protected Object exchange(Supplier<URI> uriSupplier, HttpMethod httpMethod, HttpEntity<?> httpRequest, Object expectedResponseType, Message<?> requestMessage) {
WebClient.RequestBodySpec requestSpec = this.webClient.method(httpMethod).uri(b -> uriSupplier.get()).headers(headers -> headers.putAll(httpRequest.getHeaders()));
if (httpRequest.hasBody()) {
requestSpec.body(BodyInserters.fromObject(httpRequest.getBody()));
}
Mono<ClientResponse> responseMono = requestSpec.exchange().flatMap(response -> {
HttpStatus httpStatus = response.statusCode();
if (httpStatus.isError()) {
return response.body(BodyExtractors.toDataBuffers()).reduce(DataBuffer::write).map(dataBuffer -> {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
DataBufferUtils.release(dataBuffer);
return bytes;
}).defaultIfEmpty(new byte[0]).map(bodyBytes -> {
throw new WebClientResponseException("ClientResponse has erroneous status code: " + httpStatus.value() + " " + httpStatus.getReasonPhrase(), httpStatus.value(), httpStatus.getReasonPhrase(), response.headers().asHttpHeaders(), bodyBytes, response.headers().contentType().map(MimeType::getCharset).orElse(StandardCharsets.ISO_8859_1));
});
} else {
return Mono.just(response);
}
});
if (isExpectReply()) {
return responseMono.flatMap(response -> {
ResponseEntity.BodyBuilder httpEntityBuilder = ResponseEntity.status(response.statusCode()).headers(response.headers().asHttpHeaders());
Mono<?> bodyMono;
if (expectedResponseType != null) {
if (this.replyPayloadToFlux) {
BodyExtractor<? extends Flux<?>, ReactiveHttpInputMessage> extractor;
if (expectedResponseType instanceof ParameterizedTypeReference<?>) {
extractor = BodyExtractors.toFlux((ParameterizedTypeReference<?>) expectedResponseType);
} else {
extractor = BodyExtractors.toFlux((Class<?>) expectedResponseType);
}
Flux<?> flux = response.body(extractor);
bodyMono = Mono.just(flux);
} else {
BodyExtractor<? extends Mono<?>, ReactiveHttpInputMessage> extractor;
if (expectedResponseType instanceof ParameterizedTypeReference<?>) {
extractor = BodyExtractors.toMono((ParameterizedTypeReference<?>) expectedResponseType);
} else {
extractor = BodyExtractors.toMono((Class<?>) expectedResponseType);
}
bodyMono = response.body(extractor);
}
} else if (this.bodyExtractor != null) {
Object body = response.body(this.bodyExtractor);
if (body instanceof Mono) {
bodyMono = (Mono<?>) body;
} else {
bodyMono = Mono.just(body);
}
} else {
bodyMono = Mono.empty();
}
return bodyMono.map(httpEntityBuilder::body).defaultIfEmpty(httpEntityBuilder.build());
}).map(this::getReply);
} else {
responseMono.subscribe(v -> {
}, ex -> sendErrorMessage(requestMessage, ex));
return null;
}
}
use of reactor.core.publisher.Mono in project cf-java-client by cloudfoundry.
the class ReactorServerInformation method getAuthenticationCode.
@Override
public Mono<GetAutoLoginAuthenticationCodeResponse> getAuthenticationCode(GetAutoLoginAuthenticationCodeRequest request) {
return post(request, GetAutoLoginAuthenticationCodeResponse.class, builder -> builder.pathSegment("autologin"), outbound -> outbound.map(r -> {
String encoded = Base64.getEncoder().encodeToString(new AsciiString(request.getClientId()).concat(":").concat(request.getClientSecret()).toByteArray());
r.requestHeaders().set(AUTHORIZATION, BASIC_PREAMBLE + encoded);
return r;
})).checkpoint();
}
Aggregations