Search in sources :

Example 56 with DisposableServer

use of reactor.netty.DisposableServer in project reactor-netty by reactor.

the class HttpServerTests method testCancelReceivingForWebSocketClient.

@Test
void testCancelReceivingForWebSocketClient() throws Exception {
    AtomicReference<WebSocketCloseStatus> statusServer = new AtomicReference<>();
    AtomicReference<WebSocketCloseStatus> statusClient = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(2);
    disposableServer = createServer().handle((req, resp) -> resp.sendWebsocket((in, out) -> {
        in.receiveCloseStatus().doOnNext(o -> {
            statusServer.set(o);
            latch.countDown();
        }).subscribe();
        return out.sendString(Flux.interval(Duration.ofMillis(10)).map(l -> l + ""));
    })).bindNow();
    createClient(disposableServer.port()).websocket().uri("/").handle((in, out) -> {
        in.receiveCloseStatus().doOnNext(o -> {
            statusClient.set(o);
            latch.countDown();
        }).subscribe();
        in.receive().take(1).subscribe();
        return Mono.never();
    }).subscribe();
    assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();
    assertThat(statusClient.get()).isNotNull().isEqualTo(WebSocketCloseStatus.ABNORMAL_CLOSURE);
    assertThat(statusServer.get()).isNotNull().isEqualTo(WebSocketCloseStatus.EMPTY);
}
Also used : AttributeKey(io.netty.util.AttributeKey) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SNIHostName(javax.net.ssl.SNIHostName) AbortedException(reactor.netty.channel.AbortedException) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpMessage(io.netty.handler.codec.http.HttpMessage) ByteBufHolder(io.netty.buffer.ByteBufHolder) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TcpClient(reactor.netty.tcp.TcpClient) ConnectionObserver(reactor.netty.ConnectionObserver) Future(java.util.concurrent.Future) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) DEFAULT_FORM_DECODER_SPEC(reactor.netty.http.server.HttpServerFormDecoderProvider.DEFAULT_FORM_DECODER_SPEC) Path(java.nio.file.Path) LoopResources(reactor.netty.resources.LoopResources) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) HttpRequest(io.netty.handler.codec.http.HttpRequest) Context(reactor.util.context.Context) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) Assertions.fail(org.assertj.core.api.Assertions.fail) NettyOutbound(reactor.netty.NettyOutbound) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) GZIPOutputStream(java.util.zip.GZIPOutputStream) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HttpClient(reactor.netty.http.client.HttpClient) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) HttpProtocol(reactor.netty.http.HttpProtocol) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ValueSource(org.junit.jupiter.params.provider.ValueSource) PrematureCloseException(reactor.netty.http.client.PrematureCloseException) SslContext(io.netty.handler.ssl.SslContext) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) Field(java.lang.reflect.Field) ReferenceCounted(io.netty.util.ReferenceCounted) Channel(io.netty.channel.Channel) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) ServerCookieEncoder(io.netty.handler.codec.http.cookie.ServerCookieEncoder) HttpUtil(io.netty.handler.codec.http.HttpUtil) SocketAddress(java.net.SocketAddress) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) TimeoutException(java.util.concurrent.TimeoutException) BaseHttpTest(reactor.netty.BaseHttpTest) Random(java.util.Random) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) TransportConfig(reactor.netty.transport.TransportConfig) ServerCookieDecoder(io.netty.handler.codec.http.cookie.ServerCookieDecoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SignalType(reactor.core.publisher.SignalType) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ChannelBindException(reactor.netty.ChannelBindException) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) DisposableServer(reactor.netty.DisposableServer) HttpVersion(io.netty.handler.codec.http.HttpVersion) Tuple3(reactor.util.function.Tuple3) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) Tuple2(reactor.util.function.Tuple2) HttpClientRequest(reactor.netty.http.client.HttpClientRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpMethod(io.netty.handler.codec.http.HttpMethod) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) TcpServer(reactor.netty.tcp.TcpServer) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Comparator(java.util.Comparator) Timeout(org.junit.jupiter.api.Timeout) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 57 with DisposableServer

use of reactor.netty.DisposableServer in project reactor-netty by reactor.

the class HttpServerTests method testCancelConnectionCloseForWebSocketServer.

@Test
void testCancelConnectionCloseForWebSocketServer() throws Exception {
    AtomicReference<WebSocketCloseStatus> statusServer = new AtomicReference<>();
    AtomicReference<WebSocketCloseStatus> statusClient = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(2);
    disposableServer = createServer().handle((req, resp) -> resp.sendWebsocket((in, out) -> {
        in.receiveCloseStatus().doOnNext(o -> {
            statusServer.set(o);
            latch.countDown();
        }).subscribe();
        in.withConnection(Connection::dispose);
        return Mono.never();
    })).bindNow();
    createClient(disposableServer.port()).websocket().uri("/").handle((in, out) -> {
        in.receiveCloseStatus().doOnNext(o -> {
            statusClient.set(o);
            latch.countDown();
        }).subscribe();
        return Mono.never();
    }).subscribe();
    assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();
    assertThat(statusClient.get()).isNotNull().isEqualTo(WebSocketCloseStatus.EMPTY);
    assertThat(statusServer.get()).isNotNull().isEqualTo(WebSocketCloseStatus.ABNORMAL_CLOSURE);
}
Also used : AttributeKey(io.netty.util.AttributeKey) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SNIHostName(javax.net.ssl.SNIHostName) AbortedException(reactor.netty.channel.AbortedException) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpMessage(io.netty.handler.codec.http.HttpMessage) ByteBufHolder(io.netty.buffer.ByteBufHolder) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TcpClient(reactor.netty.tcp.TcpClient) ConnectionObserver(reactor.netty.ConnectionObserver) Future(java.util.concurrent.Future) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) DEFAULT_FORM_DECODER_SPEC(reactor.netty.http.server.HttpServerFormDecoderProvider.DEFAULT_FORM_DECODER_SPEC) Path(java.nio.file.Path) LoopResources(reactor.netty.resources.LoopResources) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) HttpRequest(io.netty.handler.codec.http.HttpRequest) Context(reactor.util.context.Context) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) Assertions.fail(org.assertj.core.api.Assertions.fail) NettyOutbound(reactor.netty.NettyOutbound) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) GZIPOutputStream(java.util.zip.GZIPOutputStream) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HttpClient(reactor.netty.http.client.HttpClient) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) HttpProtocol(reactor.netty.http.HttpProtocol) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ValueSource(org.junit.jupiter.params.provider.ValueSource) PrematureCloseException(reactor.netty.http.client.PrematureCloseException) SslContext(io.netty.handler.ssl.SslContext) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) Field(java.lang.reflect.Field) ReferenceCounted(io.netty.util.ReferenceCounted) Channel(io.netty.channel.Channel) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) ServerCookieEncoder(io.netty.handler.codec.http.cookie.ServerCookieEncoder) HttpUtil(io.netty.handler.codec.http.HttpUtil) SocketAddress(java.net.SocketAddress) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) TimeoutException(java.util.concurrent.TimeoutException) BaseHttpTest(reactor.netty.BaseHttpTest) Random(java.util.Random) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) TransportConfig(reactor.netty.transport.TransportConfig) ServerCookieDecoder(io.netty.handler.codec.http.cookie.ServerCookieDecoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SignalType(reactor.core.publisher.SignalType) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ChannelBindException(reactor.netty.ChannelBindException) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) DisposableServer(reactor.netty.DisposableServer) HttpVersion(io.netty.handler.codec.http.HttpVersion) Tuple3(reactor.util.function.Tuple3) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) Tuple2(reactor.util.function.Tuple2) HttpClientRequest(reactor.netty.http.client.HttpClientRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpMethod(io.netty.handler.codec.http.HttpMethod) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) TcpServer(reactor.netty.tcp.TcpServer) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Comparator(java.util.Comparator) Timeout(org.junit.jupiter.api.Timeout) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 58 with DisposableServer

use of reactor.netty.DisposableServer in project reactor-netty by reactor.

the class HttpServerTests method startRouterAndAwait.

@Test
void startRouterAndAwait() throws InterruptedException {
    ExecutorService ex = Executors.newSingleThreadExecutor();
    AtomicReference<DisposableServer> ref = new AtomicReference<>();
    Future<?> f = ex.submit(() -> createServer().route(routes -> routes.get("/hello", (req, resp) -> resp.sendString(Mono.just("hello!")))).bindUntilJavaShutdown(Duration.ofSeconds(2), ref::set));
    // if the server cannot be started, a ExecutionException will be thrown instead
    assertThatExceptionOfType(TimeoutException.class).isThrownBy(() -> f.get(1, TimeUnit.SECONDS));
    // the router is not done and is still blocking the thread
    assertThat(f.isDone()).isFalse();
    assertThat(ref.get()).withFailMessage("Server is not initialized after 1s").isNotNull();
    // shutdown the router to unblock the thread
    ref.get().disposeNow();
    Thread.sleep(100);
    assertThat(f.isDone()).isTrue();
}
Also used : AttributeKey(io.netty.util.AttributeKey) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SNIHostName(javax.net.ssl.SNIHostName) AbortedException(reactor.netty.channel.AbortedException) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpMessage(io.netty.handler.codec.http.HttpMessage) ByteBufHolder(io.netty.buffer.ByteBufHolder) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TcpClient(reactor.netty.tcp.TcpClient) ConnectionObserver(reactor.netty.ConnectionObserver) Future(java.util.concurrent.Future) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) DEFAULT_FORM_DECODER_SPEC(reactor.netty.http.server.HttpServerFormDecoderProvider.DEFAULT_FORM_DECODER_SPEC) Path(java.nio.file.Path) LoopResources(reactor.netty.resources.LoopResources) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) HttpRequest(io.netty.handler.codec.http.HttpRequest) Context(reactor.util.context.Context) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) Assertions.fail(org.assertj.core.api.Assertions.fail) NettyOutbound(reactor.netty.NettyOutbound) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) GZIPOutputStream(java.util.zip.GZIPOutputStream) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HttpClient(reactor.netty.http.client.HttpClient) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) HttpProtocol(reactor.netty.http.HttpProtocol) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ValueSource(org.junit.jupiter.params.provider.ValueSource) PrematureCloseException(reactor.netty.http.client.PrematureCloseException) SslContext(io.netty.handler.ssl.SslContext) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) Field(java.lang.reflect.Field) ReferenceCounted(io.netty.util.ReferenceCounted) Channel(io.netty.channel.Channel) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) ServerCookieEncoder(io.netty.handler.codec.http.cookie.ServerCookieEncoder) HttpUtil(io.netty.handler.codec.http.HttpUtil) SocketAddress(java.net.SocketAddress) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) TimeoutException(java.util.concurrent.TimeoutException) BaseHttpTest(reactor.netty.BaseHttpTest) Random(java.util.Random) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) TransportConfig(reactor.netty.transport.TransportConfig) ServerCookieDecoder(io.netty.handler.codec.http.cookie.ServerCookieDecoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SignalType(reactor.core.publisher.SignalType) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ChannelBindException(reactor.netty.ChannelBindException) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) DisposableServer(reactor.netty.DisposableServer) HttpVersion(io.netty.handler.codec.http.HttpVersion) Tuple3(reactor.util.function.Tuple3) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) Tuple2(reactor.util.function.Tuple2) HttpClientRequest(reactor.netty.http.client.HttpClientRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpMethod(io.netty.handler.codec.http.HttpMethod) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) TcpServer(reactor.netty.tcp.TcpServer) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Comparator(java.util.Comparator) Timeout(org.junit.jupiter.api.Timeout) DisposableServer(reactor.netty.DisposableServer) ExecutorService(java.util.concurrent.ExecutorService) AtomicReference(java.util.concurrent.atomic.AtomicReference) TimeoutException(java.util.concurrent.TimeoutException) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 59 with DisposableServer

use of reactor.netty.DisposableServer in project reactor-netty by reactor.

the class HttpServerTests method testContentLengthHeadRequest.

@Test
void testContentLengthHeadRequest() {
    AtomicReference<HttpHeaders> sentHeaders = new AtomicReference<>();
    disposableServer = createServer().host("localhost").route(r -> r.route(req -> req.uri().equals("/1"), (req, res) -> res.sendString(Flux.just("OK").hide())).route(req -> req.uri().startsWith("/2"), (req, res) -> res.chunkedTransfer(false).sendString(Flux.just("OK").hide())).route(req -> req.uri().startsWith("/3"), (req, res) -> {
        res.responseHeaders().set(HttpHeaderNames.CONTENT_LENGTH, 2);
        return res.sendString(Mono.just("OK")).then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()));
    }).route(req -> req.uri().startsWith("/4"), (req, res) -> res.sendHeaders()).route(req -> req.uri().startsWith("/5"), (req, res) -> res.chunkedTransfer(false).sendHeaders()).route(req -> req.uri().startsWith("/6"), (req, res) -> {
        res.responseHeaders().set(HttpHeaderNames.CONTENT_LENGTH, 2);
        return res.sendHeaders().then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()));
    }).route(req -> req.uri().startsWith("/7"), (req, res) -> res.send().then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()))).route(req -> req.uri().startsWith("/8"), (req, res) -> res.chunkedTransfer(false).send().then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()))).route(req -> req.uri().startsWith("/9"), (req, res) -> {
        res.responseHeaders().set(HttpHeaderNames.CONTENT_LENGTH, 2);
        return res.send().then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()));
    }).route(req -> req.uri().startsWith("/10"), (req, res) -> {
        res.responseHeaders().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        return res.sendString(Mono.just("OK")).then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()));
    }).route(req -> req.uri().startsWith("/11"), (req, res) -> {
        res.responseHeaders().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        return res.sendString(Flux.just("OK").hide()).then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()));
    }).route(req -> req.uri().startsWith("/12"), (req, res) -> {
        res.responseHeaders().set(HttpHeaderNames.CONTENT_LENGTH, 2);
        return res.sendObject(Unpooled.wrappedBuffer("OK".getBytes(Charset.defaultCharset()))).then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()));
    }).route(req -> req.uri().startsWith("/13"), (req, res) -> {
        res.responseHeaders().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        return res.sendObject(Unpooled.wrappedBuffer("OK".getBytes(Charset.defaultCharset()))).then().doOnSuccess(aVoid -> sentHeaders.set(res.responseHeaders()));
    })).bindNow();
    InetSocketAddress address = (InetSocketAddress) disposableServer.address();
    doTestContentLengthHeadRequest("/1", address, HttpMethod.GET, sentHeaders, true, false);
    doTestContentLengthHeadRequest("/1", address, HttpMethod.HEAD, sentHeaders, true, false);
    doTestContentLengthHeadRequest("/2", address, HttpMethod.GET, sentHeaders, false, true);
    doTestContentLengthHeadRequest("/2", address, HttpMethod.HEAD, sentHeaders, false, true);
    doTestContentLengthHeadRequest("/3", address, HttpMethod.GET, sentHeaders, false, false);
    doTestContentLengthHeadRequest("/3", address, HttpMethod.HEAD, sentHeaders, false, false);
    doTestContentLengthHeadRequest("/4", address, HttpMethod.HEAD, sentHeaders, true, false);
    doTestContentLengthHeadRequest("/5", address, HttpMethod.HEAD, sentHeaders, false, true);
    doTestContentLengthHeadRequest("/6", address, HttpMethod.HEAD, sentHeaders, false, false);
    doTestContentLengthHeadRequest("/7", address, HttpMethod.HEAD, sentHeaders, true, false);
    doTestContentLengthHeadRequest("/8", address, HttpMethod.HEAD, sentHeaders, false, true);
    doTestContentLengthHeadRequest("/9", address, HttpMethod.HEAD, sentHeaders, false, false);
    doTestContentLengthHeadRequest("/10", address, HttpMethod.HEAD, sentHeaders, false, false);
    doTestContentLengthHeadRequest("/11", address, HttpMethod.HEAD, sentHeaders, false, false);
    doTestContentLengthHeadRequest("/12", address, HttpMethod.HEAD, sentHeaders, false, false);
    doTestContentLengthHeadRequest("/13", address, HttpMethod.HEAD, sentHeaders, false, false);
}
Also used : AttributeKey(io.netty.util.AttributeKey) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SNIHostName(javax.net.ssl.SNIHostName) AbortedException(reactor.netty.channel.AbortedException) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpMessage(io.netty.handler.codec.http.HttpMessage) ByteBufHolder(io.netty.buffer.ByteBufHolder) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TcpClient(reactor.netty.tcp.TcpClient) ConnectionObserver(reactor.netty.ConnectionObserver) Future(java.util.concurrent.Future) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) DEFAULT_FORM_DECODER_SPEC(reactor.netty.http.server.HttpServerFormDecoderProvider.DEFAULT_FORM_DECODER_SPEC) Path(java.nio.file.Path) LoopResources(reactor.netty.resources.LoopResources) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) HttpRequest(io.netty.handler.codec.http.HttpRequest) Context(reactor.util.context.Context) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) Assertions.fail(org.assertj.core.api.Assertions.fail) NettyOutbound(reactor.netty.NettyOutbound) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) GZIPOutputStream(java.util.zip.GZIPOutputStream) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HttpClient(reactor.netty.http.client.HttpClient) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) HttpProtocol(reactor.netty.http.HttpProtocol) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ValueSource(org.junit.jupiter.params.provider.ValueSource) PrematureCloseException(reactor.netty.http.client.PrematureCloseException) SslContext(io.netty.handler.ssl.SslContext) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) Field(java.lang.reflect.Field) ReferenceCounted(io.netty.util.ReferenceCounted) Channel(io.netty.channel.Channel) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) ServerCookieEncoder(io.netty.handler.codec.http.cookie.ServerCookieEncoder) HttpUtil(io.netty.handler.codec.http.HttpUtil) SocketAddress(java.net.SocketAddress) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) TimeoutException(java.util.concurrent.TimeoutException) BaseHttpTest(reactor.netty.BaseHttpTest) Random(java.util.Random) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) TransportConfig(reactor.netty.transport.TransportConfig) ServerCookieDecoder(io.netty.handler.codec.http.cookie.ServerCookieDecoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SignalType(reactor.core.publisher.SignalType) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ChannelBindException(reactor.netty.ChannelBindException) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) DisposableServer(reactor.netty.DisposableServer) HttpVersion(io.netty.handler.codec.http.HttpVersion) Tuple3(reactor.util.function.Tuple3) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) Tuple2(reactor.util.function.Tuple2) HttpClientRequest(reactor.netty.http.client.HttpClientRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpMethod(io.netty.handler.codec.http.HttpMethod) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) TcpServer(reactor.netty.tcp.TcpServer) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Comparator(java.util.Comparator) Timeout(org.junit.jupiter.api.Timeout) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) InetSocketAddress(java.net.InetSocketAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 60 with DisposableServer

use of reactor.netty.DisposableServer in project reactor-netty by reactor.

the class HttpRedirectTest method redirect_issuesOnRequestForEachAttempt.

/**
 * This ensures functionality such as metrics and tracing can accurately count requests.
 */
@Test
void redirect_issuesOnRequestForEachAttempt() {
    disposableServer = createServer().host("localhost").route(r -> r.get("/1", (req, res) -> res.sendRedirect("/3")).get("/3", (req, res) -> res.status(200).sendString(Mono.just("OK")))).bindNow();
    AtomicInteger onRequestCount = new AtomicInteger();
    AtomicInteger onResponseCount = new AtomicInteger();
    AtomicInteger onRedirectCount = new AtomicInteger();
    AtomicInteger doOnResponseError = new AtomicInteger();
    Tuple2<String, HttpResponseStatus> response = createClient(disposableServer::address).followRedirect(true).doOnRequest((r, c) -> onRequestCount.incrementAndGet()).doOnResponse((r, c) -> onResponseCount.incrementAndGet()).doOnRedirect((r, c) -> onRedirectCount.incrementAndGet()).doOnResponseError((r, t) -> doOnResponseError.incrementAndGet()).get().uri("/1").responseSingle((res, bytes) -> bytes.asString().zipWith(Mono.just(res.status()))).block(Duration.ofSeconds(30));
    assertThat(response).isNotNull();
    assertThat(response.getT1()).isEqualTo("OK");
    assertThat(response.getT2()).isEqualTo(HttpResponseStatus.OK);
    assertThat(onRequestCount.get()).isEqualTo(2);
    assertThat(onResponseCount.get()).isEqualTo(1);
    assertThat(onRedirectCount.get()).isEqualTo(1);
    assertThat(doOnResponseError.get()).isEqualTo(0);
}
Also used : StepVerifier(reactor.test.StepVerifier) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) SocketUtils(reactor.netty.SocketUtils) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpProtocol(reactor.netty.http.HttpProtocol) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BaseHttpTest(reactor.netty.BaseHttpTest) Tuple2(reactor.util.function.Tuple2) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) Connection(reactor.netty.Connection) LoopResources(reactor.netty.resources.LoopResources) HttpContent(io.netty.handler.codec.http.HttpContent) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) BlockingQueue(java.util.concurrent.BlockingQueue) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Flux(reactor.core.publisher.Flux) List(java.util.List) HttpServer(reactor.netty.http.server.HttpServer) SslHandler(io.netty.handler.ssl.SslHandler) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) DisposableServer(reactor.netty.DisposableServer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Aggregations

DisposableServer (reactor.netty.DisposableServer)137 Mono (reactor.core.publisher.Mono)84 Test (org.junit.jupiter.api.Test)79 Duration (java.time.Duration)71 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)71 AtomicReference (java.util.concurrent.atomic.AtomicReference)68 Flux (reactor.core.publisher.Flux)68 Connection (reactor.netty.Connection)67 TimeUnit (java.util.concurrent.TimeUnit)65 LoopResources (reactor.netty.resources.LoopResources)60 List (java.util.List)58 CountDownLatch (java.util.concurrent.CountDownLatch)57 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)56 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)55 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)54 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)54 InsecureTrustManagerFactory (io.netty.handler.ssl.util.InsecureTrustManagerFactory)53 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)53 Assumptions.assumeThat (org.assertj.core.api.Assumptions.assumeThat)53 StepVerifier (reactor.test.StepVerifier)53