Search in sources :

Example 11 with NettyDataBufferFactory

use of org.springframework.core.io.buffer.NettyDataBufferFactory in project spring-framework by spring-projects.

the class AbstractDataBufferAllocatingTests method verifyAllocations.

private void verifyAllocations() {
    if (this.bufferFactory instanceof NettyDataBufferFactory) {
        ByteBufAllocator allocator = ((NettyDataBufferFactory) this.bufferFactory).getByteBufAllocator();
        if (allocator instanceof PooledByteBufAllocator) {
            Instant start = Instant.now();
            while (true) {
                PooledByteBufAllocatorMetric metric = ((PooledByteBufAllocator) allocator).metric();
                long total = getAllocations(metric.directArenas()) + getAllocations(metric.heapArenas());
                if (total == 0) {
                    return;
                }
                if (Instant.now().isBefore(start.plus(Duration.ofSeconds(5)))) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException ex) {
                    // ignore
                    }
                    continue;
                }
                assertThat(total).as("ByteBuf Leak: " + total + " unreleased allocations").isEqualTo(0);
            }
        }
    }
}
Also used : UnpooledByteBufAllocator(io.netty.buffer.UnpooledByteBufAllocator) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) Instant(java.time.Instant) PooledByteBufAllocatorMetric(io.netty.buffer.PooledByteBufAllocatorMetric) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator)

Example 12 with NettyDataBufferFactory

use of org.springframework.core.io.buffer.NettyDataBufferFactory in project spring-framework by spring-projects.

the class ReactorNettyRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol) {
    ReactorServerHttpResponse response = (ReactorServerHttpResponse) exchange.getResponse();
    HandshakeInfo info = getHandshakeInfo(exchange, subProtocol);
    NettyDataBufferFactory bufferFactory = (NettyDataBufferFactory) response.bufferFactory();
    return response.getReactorResponse().sendWebsocket(subProtocol.orElse(null), (in, out) -> handler.handle(new ReactorNettyWebSocketSession(in, out, info, bufferFactory)));
}
Also used : ReactorNettyWebSocketSession(org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession) ReactorServerHttpResponse(org.springframework.http.server.reactive.ReactorServerHttpResponse) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo)

Example 13 with NettyDataBufferFactory

use of org.springframework.core.io.buffer.NettyDataBufferFactory in project spring-framework by spring-projects.

the class BodyExtractorsTests method unsupportedMediaTypeShouldConsumeAndCancel.

// SPR-17054
@Test
public void unsupportedMediaTypeShouldConsumeAndCancel() {
    NettyDataBufferFactory factory = new NettyDataBufferFactory(new PooledByteBufAllocator(true));
    NettyDataBuffer buffer = factory.wrap(ByteBuffer.wrap("spring".getBytes(StandardCharsets.UTF_8)));
    TestPublisher<DataBuffer> body = TestPublisher.create();
    MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
    response.getHeaders().setContentType(MediaType.APPLICATION_PDF);
    response.setBody(body.flux());
    BodyExtractor<Mono<User>, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(User.class);
    StepVerifier.create(extractor.extract(response, this.context)).then(() -> {
        body.assertWasSubscribed();
        body.emit(buffer);
    }).expectErrorSatisfies(throwable -> {
        boolean condition = throwable instanceof UnsupportedMediaTypeException;
        assertThat(condition).isTrue();
        assertThatExceptionOfType(IllegalReferenceCountException.class).isThrownBy(buffer::release);
        body.assertCancelled();
    }).verify();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) TestPublisher(reactor.test.publisher.TestPublisher) FilePart(org.springframework.http.codec.multipart.FilePart) FormFieldPart(org.springframework.http.codec.multipart.FormFieldPart) JsonView(com.fasterxml.jackson.annotation.JsonView) StepVerifier(reactor.test.StepVerifier) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) FormHttpMessageReader(org.springframework.http.codec.FormHttpMessageReader) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) HashMap(java.util.HashMap) JSON_VIEW_HINT(org.springframework.http.codec.json.Jackson2CodecSupport.JSON_VIEW_HINT) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Part(org.springframework.http.codec.multipart.Part) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Jaxb2XmlDecoder(org.springframework.http.codec.xml.Jaxb2XmlDecoder) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) DefaultPartHttpMessageReader(org.springframework.http.codec.multipart.DefaultPartHttpMessageReader) MockClientHttpResponse(org.springframework.web.testfixture.http.client.reactive.MockClientHttpResponse) StringDecoder(org.springframework.core.codec.StringDecoder) MediaType(org.springframework.http.MediaType) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) ByteBufferDecoder(org.springframework.core.codec.ByteBufferDecoder) DataBuffer(org.springframework.core.io.buffer.DataBuffer) StandardCharsets(java.nio.charset.StandardCharsets) DecoderHttpMessageReader(org.springframework.http.codec.DecoderHttpMessageReader) Test(org.junit.jupiter.api.Test) Flux(reactor.core.publisher.Flux) HttpStatus(org.springframework.http.HttpStatus) MockServerHttpRequest(org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest) List(java.util.List) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) MultipartHttpMessageReader(org.springframework.http.codec.multipart.MultipartHttpMessageReader) Optional(java.util.Optional) Collections(java.util.Collections) Mono(reactor.core.publisher.Mono) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer) MockClientHttpResponse(org.springframework.web.testfixture.http.client.reactive.MockClientHttpResponse) Test(org.junit.jupiter.api.Test)

Example 14 with NettyDataBufferFactory

use of org.springframework.core.io.buffer.NettyDataBufferFactory in project spring-framework by spring-projects.

the class ReactorNettyWebSocketClient method execute.

@Override
public Mono<Void> execute(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
    String protocols = StringUtils.collectionToCommaDelimitedString(handler.getSubProtocols());
    return getHttpClient().headers(nettyHeaders -> setNettyHeaders(requestHeaders, nettyHeaders)).websocket(buildSpec(protocols)).uri(url.toString()).handle((inbound, outbound) -> {
        HttpHeaders responseHeaders = toHttpHeaders(inbound);
        String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
        HandshakeInfo info = new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
        NettyDataBufferFactory factory = new NettyDataBufferFactory(outbound.alloc());
        WebSocketSession session = new ReactorNettyWebSocketSession(inbound, outbound, info, factory, getMaxFramePayloadLength());
        if (logger.isDebugEnabled()) {
            logger.debug("Started session '" + session.getId() + "' for " + url);
        }
        return handler.handle(session).checkpoint(url + " [ReactorNettyWebSocketClient]");
    }).doOnRequest(n -> {
        if (logger.isDebugEnabled()) {
            logger.debug("Connecting to " + url);
        }
    }).next();
}
Also used : NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) WebSocketSession(org.springframework.web.reactive.socket.WebSocketSession) WebsocketClientSpec(reactor.netty.http.client.WebsocketClientSpec) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) HttpHeaders(org.springframework.http.HttpHeaders) Mono(reactor.core.publisher.Mono) ReactorNettyWebSocketSession(org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession) Supplier(java.util.function.Supplier) WebsocketInbound(reactor.netty.http.websocket.WebsocketInbound) Log(org.apache.commons.logging.Log) Nullable(org.springframework.lang.Nullable) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) URI(java.net.URI) LogFactory(org.apache.commons.logging.LogFactory) HttpClient(reactor.netty.http.client.HttpClient) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) HttpHeaders(org.springframework.http.HttpHeaders) ReactorNettyWebSocketSession(org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) WebSocketSession(org.springframework.web.reactive.socket.WebSocketSession) ReactorNettyWebSocketSession(org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession)

Example 15 with NettyDataBufferFactory

use of org.springframework.core.io.buffer.NettyDataBufferFactory in project spring-framework by spring-projects.

the class MetadataEncoder method asDataBuffer.

private DataBuffer asDataBuffer(ByteBuf byteBuf) {
    if (bufferFactory() instanceof NettyDataBufferFactory) {
        return ((NettyDataBufferFactory) bufferFactory()).wrap(byteBuf);
    } else {
        DataBuffer buffer = bufferFactory().wrap(byteBuf.nioBuffer());
        byteBuf.release();
        return buffer;
    }
}
Also used : NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Aggregations

NettyDataBufferFactory (org.springframework.core.io.buffer.NettyDataBufferFactory)15 Mono (reactor.core.publisher.Mono)6 ByteBuf (io.netty.buffer.ByteBuf)5 HandshakeInfo (org.springframework.web.reactive.socket.HandshakeInfo)5 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)4 URI (java.net.URI)3 Log (org.apache.commons.logging.Log)3 Test (org.junit.jupiter.api.Test)3 Assert (org.springframework.util.Assert)3 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)2 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 DataBuffer (org.springframework.core.io.buffer.DataBuffer)2 WebSocketHandler (org.springframework.web.reactive.socket.WebSocketHandler)2 ReactorNettyWebSocketSession (org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession)2 RxNettyWebSocketSession (org.springframework.web.reactive.socket.adapter.RxNettyWebSocketSession)2 HttpServerResponse (reactor.netty.http.server.HttpServerResponse)2 Observable (rx.Observable)2