Search in sources :

Example 21 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer 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;
    }
}
Also used : ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) LiteralExpression(org.springframework.expression.common.LiteralExpression) WebClient(org.springframework.web.reactive.function.client.WebClient) Supplier(java.util.function.Supplier) ClientHttpResponse(org.springframework.http.client.reactive.ClientHttpResponse) MimeType(org.springframework.util.MimeType) ValueExpression(org.springframework.integration.expression.ValueExpression) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Message(org.springframework.messaging.Message) URI(java.net.URI) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) AbstractHttpRequestExecutingMessageHandler(org.springframework.integration.http.outbound.AbstractHttpRequestExecutingMessageHandler) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) DataBuffer(org.springframework.core.io.buffer.DataBuffer) StandardCharsets(java.nio.charset.StandardCharsets) HttpStatus(org.springframework.http.HttpStatus) Flux(reactor.core.publisher.Flux) HttpEntity(org.springframework.http.HttpEntity) BodyExtractors(org.springframework.web.reactive.function.BodyExtractors) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) MessageHandler(org.springframework.messaging.MessageHandler) BeanFactory(org.springframework.beans.factory.BeanFactory) Expression(org.springframework.expression.Expression) ResponseEntity(org.springframework.http.ResponseEntity) BodyInserters(org.springframework.web.reactive.function.BodyInserters) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) Assert(org.springframework.util.Assert) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpStatus(org.springframework.http.HttpStatus) Mono(reactor.core.publisher.Mono) Flux(reactor.core.publisher.Flux) WebClient(org.springframework.web.reactive.function.client.WebClient) MimeType(org.springframework.util.MimeType) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor)

Example 22 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-integration by spring-projects.

the class WebFluxRequestExecutingMessageHandlerTests method testFluxReply.

@Test
@SuppressWarnings("unchecked")
public void testFluxReply() {
    ClientHttpConnector httpConnector = new HttpHandlerConnector((request, response) -> {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
        DataBufferFactory bufferFactory = response.bufferFactory();
        Mono<DataBuffer> data = Mono.just(bufferFactory.wrap("foo\nbar\nbaz".getBytes()));
        return response.writeWith(data).then(Mono.defer(response::setComplete));
    });
    WebClient webClient = WebClient.builder().clientConnector(httpConnector).build();
    String destinationUri = "http://www.springsource.org/spring-integration";
    WebFluxRequestExecutingMessageHandler reactiveHandler = new WebFluxRequestExecutingMessageHandler(destinationUri, webClient);
    QueueChannel replyChannel = new QueueChannel();
    reactiveHandler.setOutputChannel(replyChannel);
    reactiveHandler.setExpectedResponseType(String.class);
    reactiveHandler.setReplyPayloadToFlux(true);
    reactiveHandler.handleMessage(MessageBuilder.withPayload("hello, world").build());
    Message<?> receive = replyChannel.receive(10_000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(Flux.class));
    Flux<String> flux = (Flux<String>) receive.getPayload();
    StepVerifier.create(flux).expectNext("foo", "bar", "baz").verifyComplete();
}
Also used : ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) QueueChannel(org.springframework.integration.channel.QueueChannel) Flux(reactor.core.publisher.Flux) Matchers.containsString(org.hamcrest.Matchers.containsString) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) WebClient(org.springframework.web.reactive.function.client.WebClient) HttpHandlerConnector(org.springframework.test.web.reactive.server.HttpHandlerConnector) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Test(org.junit.Test)

Example 23 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-integration by spring-projects.

the class WebFluxRequestExecutingMessageHandlerTests method testClientHttpResponseAsReply.

@Test
public void testClientHttpResponseAsReply() {
    ClientHttpConnector httpConnector = new HttpHandlerConnector((request, response) -> {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
        DataBufferFactory bufferFactory = response.bufferFactory();
        Flux<DataBuffer> data = Flux.just(bufferFactory.wrap("foo".getBytes()), bufferFactory.wrap("bar".getBytes()), bufferFactory.wrap("baz".getBytes()));
        return response.writeWith(data).then(Mono.defer(response::setComplete));
    });
    WebClient webClient = WebClient.builder().clientConnector(httpConnector).build();
    String destinationUri = "http://www.springsource.org/spring-integration";
    WebFluxRequestExecutingMessageHandler reactiveHandler = new WebFluxRequestExecutingMessageHandler(destinationUri, webClient);
    QueueChannel replyChannel = new QueueChannel();
    reactiveHandler.setOutputChannel(replyChannel);
    reactiveHandler.setBodyExtractor(new ClientHttpResponseBodyExtractor());
    reactiveHandler.handleMessage(MessageBuilder.withPayload("hello, world").build());
    Message<?> receive = replyChannel.receive(10_000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(ClientHttpResponse.class));
    ClientHttpResponse response = (ClientHttpResponse) receive.getPayload();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals(MediaType.TEXT_PLAIN, response.getHeaders().getContentType());
    StepVerifier.create(response.getBody().map(dataBuffer -> new String(dataBuffer.asByteBuffer().array()))).expectNext("foo", "bar", "baz").verifyComplete();
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) StepVerifier(reactor.test.StepVerifier) WebClient(org.springframework.web.reactive.function.client.WebClient) FluxMessageChannel(org.springframework.integration.channel.FluxMessageChannel) ErrorMessage(org.springframework.messaging.support.ErrorMessage) TestUtils(org.springframework.integration.test.util.TestUtils) ClientHttpResponse(org.springframework.http.client.reactive.ClientHttpResponse) Assert.assertThat(org.junit.Assert.assertThat) MessageBuilder(org.springframework.integration.support.MessageBuilder) ClientHttpResponseBodyExtractor(org.springframework.integration.webflux.support.ClientHttpResponseBodyExtractor) MessageHandlingException(org.springframework.messaging.MessageHandlingException) HttpHandlerConnector(org.springframework.test.web.reactive.server.HttpHandlerConnector) Message(org.springframework.messaging.Message) Subscriber(org.reactivestreams.Subscriber) Assert.assertNotNull(org.junit.Assert.assertNotNull) MediaType(org.springframework.http.MediaType) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) HttpHeaders(org.springframework.integration.http.HttpHeaders) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) HttpStatus(org.springframework.http.HttpStatus) Flux(reactor.core.publisher.Flux) HeaderMatcher.hasHeader(org.springframework.integration.test.matcher.HeaderMatcher.hasHeader) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) Matchers.containsString(org.hamcrest.Matchers.containsString) Assert.assertEquals(org.junit.Assert.assertEquals) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) QueueChannel(org.springframework.integration.channel.QueueChannel) ClientHttpResponseBodyExtractor(org.springframework.integration.webflux.support.ClientHttpResponseBodyExtractor) Matchers.containsString(org.hamcrest.Matchers.containsString) WebClient(org.springframework.web.reactive.function.client.WebClient) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) ClientHttpResponse(org.springframework.http.client.reactive.ClientHttpResponse) HttpHandlerConnector(org.springframework.test.web.reactive.server.HttpHandlerConnector) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Test(org.junit.Test)

Example 24 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-boot-admin by codecentric.

the class InstancesProxyController method endpointProxy.

@ResponseBody
@RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public Flux<InstanceWebProxy.InstanceResponse> endpointProxy(@PathVariable("applicationName") String applicationName, HttpServletRequest servletRequest) {
    ServletServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
    Flux<DataBuffer> cachedBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096).cache();
    InstanceWebProxy.ForwardRequest fwdRequest = createForwardRequest(request, cachedBody, this.adminContextPath + APPLICATION_MAPPED_PATH);
    return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), fwdRequest);
}
Also used : ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) InstanceWebProxy(de.codecentric.boot.admin.server.web.InstanceWebProxy) DataBuffer(org.springframework.core.io.buffer.DataBuffer) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 25 with DataBuffer

use of org.springframework.core.io.buffer.DataBuffer in project spring-boot-admin by codecentric.

the class InstancesProxyController method endpointProxy.

@ResponseBody
@RequestMapping(path = INSTANCE_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public void endpointProxy(@PathVariable("instanceId") String instanceId, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
    ServletServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
    Flux<DataBuffer> requestBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096);
    InstanceWebProxy.ForwardRequest fwdRequest = createForwardRequest(request, requestBody, this.adminContextPath + INSTANCE_MAPPED_PATH);
    this.instanceWebProxy.forward(this.registry.getInstance(InstanceId.of(instanceId)), fwdRequest, (clientResponse) -> {
        ServerHttpResponse response = new ServletServerHttpResponse(servletResponse);
        response.setStatusCode(clientResponse.statusCode());
        response.getHeaders().addAll(this.httpHeadersFilter.filterHeaders(clientResponse.headers().asHttpHeaders()));
        try {
            OutputStream responseBody = response.getBody();
            response.flush();
            return clientResponse.body(BodyExtractors.toDataBuffers()).window(1).concatMap((body) -> writeAndFlush(body, responseBody)).then();
        } catch (IOException ex) {
            return Mono.error(ex);
        }
    }).block();
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) AdminController(de.codecentric.boot.admin.server.web.AdminController) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ServerHttpResponse(org.springframework.http.server.ServerHttpResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpHeaderFilter(de.codecentric.boot.admin.server.web.HttpHeaderFilter) ServletServerHttpResponse(org.springframework.http.server.ServletServerHttpResponse) InstanceRegistry(de.codecentric.boot.admin.server.services.InstanceRegistry) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) URI(java.net.URI) AntPathMatcher(org.springframework.util.AntPathMatcher) InstanceWebClient(de.codecentric.boot.admin.server.web.client.InstanceWebClient) OutputStream(java.io.OutputStream) PathMatcher(org.springframework.util.PathMatcher) InstanceId(de.codecentric.boot.admin.server.domain.values.InstanceId) HttpServletResponse(javax.servlet.http.HttpServletResponse) Set(java.util.Set) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Flux(reactor.core.publisher.Flux) BodyExtractors(org.springframework.web.reactive.function.BodyExtractors) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) HandlerMapping(org.springframework.web.servlet.HandlerMapping) InstanceWebProxy(de.codecentric.boot.admin.server.web.InstanceWebProxy) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) BodyInserters(org.springframework.web.reactive.function.BodyInserters) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) InstanceWebProxy(de.codecentric.boot.admin.server.web.InstanceWebProxy) OutputStream(java.io.OutputStream) ServletServerHttpResponse(org.springframework.http.server.ServletServerHttpResponse) IOException(java.io.IOException) ServerHttpResponse(org.springframework.http.server.ServerHttpResponse) ServletServerHttpResponse(org.springframework.http.server.ServletServerHttpResponse) DataBuffer(org.springframework.core.io.buffer.DataBuffer) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

DataBuffer (org.springframework.core.io.buffer.DataBuffer)230 Test (org.junit.jupiter.api.Test)111 Mono (reactor.core.publisher.Mono)55 Flux (reactor.core.publisher.Flux)52 DefaultDataBuffer (org.springframework.core.io.buffer.DefaultDataBuffer)49 ResolvableType (org.springframework.core.ResolvableType)41 DefaultDataBufferFactory (org.springframework.core.io.buffer.DefaultDataBufferFactory)36 StepVerifier (reactor.test.StepVerifier)36 List (java.util.List)34 Test (org.junit.Test)30 DataBufferUtils (org.springframework.core.io.buffer.DataBufferUtils)29 IOException (java.io.IOException)28 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)27 MockServerHttpRequest (org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest)27 Map (java.util.Map)25 NettyDataBuffer (org.springframework.core.io.buffer.NettyDataBuffer)25 DataBufferFactory (org.springframework.core.io.buffer.DataBufferFactory)24 HttpHeaders (org.springframework.http.HttpHeaders)24 MediaType (org.springframework.http.MediaType)24 ByteBuffer (java.nio.ByteBuffer)23