Search in sources :

Example 1 with NettyOutbound

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

the class TcpServerTests method assertSendFile.

private void assertSendFile(Function<NettyOutbound, NettyOutbound> fn) throws Exception {
    DisposableServer context = TcpServer.create().handle((in, out) -> in.receive().asString().flatMap(word -> "GOGOGO".equals(word) ? fn.apply(out).then() : out.sendString(Mono.just("NOPE")))).wiretap(true).bindNow();
    assertThat(context).isNotNull();
    AtomicReference<String> m1 = new AtomicReference<>();
    AtomicReference<String> m2 = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(2);
    Connection client1 = TcpClient.create().port(context.port()).handle((in, out) -> {
        in.receive().asString().log("-----------------CLIENT1").subscribe(s -> {
            m1.set(s);
            latch.countDown();
        });
        return out.sendString(Mono.just("gogogo")).neverComplete();
    }).wiretap(true).connectNow();
    Connection client2 = TcpClient.create().port(context.port()).option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 1024, 65536)).handle((in, out) -> {
        in.receive().asString(StandardCharsets.UTF_8).take(2).reduceWith(String::new, String::concat).log("-----------------CLIENT2").subscribe(s -> {
            m2.set(s);
            latch.countDown();
        });
        return out.sendString(Mono.just("GOGOGO")).neverComplete();
    }).wiretap(true).connectNow();
    assertThat(client2).isNotNull();
    assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    client1.disposeNow();
    client2.disposeNow();
    context.disposeNow();
    assertThat(m1.get()).isNotNull().isEqualTo("NOPE");
    assertThat(m2.get()).isNotNull().startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.").contains("1024 mark here ->").contains("<- 1024 mark here").endsWith("End of File");
}
Also used : SNIHostName(javax.net.ssl.SNIHostName) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) BiFunction(java.util.function.BiFunction) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) ConnectionObserver(reactor.netty.ConnectionObserver) Loggers(reactor.util.Loggers) SocketChannel(java.nio.channels.SocketChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) NettyPipeline(reactor.netty.NettyPipeline) Duration(java.time.Duration) Logger(reactor.util.Logger) Path(java.nio.file.Path) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) LoopResources(reactor.netty.resources.LoopResources) ChannelGroup(io.netty.channel.group.ChannelGroup) FileSystem(java.nio.file.FileSystem) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ChannelBindException(reactor.netty.ChannelBindException) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) NettyOutbound(reactor.netty.NettyOutbound) Exceptions(reactor.core.Exceptions) DisposableServer(reactor.netty.DisposableServer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) SocketUtils(reactor.netty.SocketUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) Connection(reactor.netty.Connection) SslContext(io.netty.handler.ssl.SslContext) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Publisher(org.reactivestreams.Publisher) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) SslProvider(io.netty.handler.ssl.SslProvider) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) NettyInbound(reactor.netty.NettyInbound) Timeout(org.junit.jupiter.api.Timeout) FileSystems(java.nio.file.FileSystems) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 2 with NettyOutbound

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

the class TcpServerTests method exposesNettyPipelineConfiguration.

@Test
void exposesNettyPipelineConfiguration() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(2);
    final TcpClient client = TcpClient.create().port(port);
    BiFunction<? super NettyInbound, ? super NettyOutbound, ? extends Publisher<Void>> serverHandler = (in, out) -> {
        in.receive().asString().subscribe(data -> {
            log.info("data " + data + " on " + in);
            latch.countDown();
        });
        return Flux.never();
    };
    TcpServer server = TcpServer.create().doOnConnection(c -> c.addHandlerLast("codec", new LineBasedFrameDecoder(8 * 1024))).port(port);
    DisposableServer connected = server.handle(serverHandler).wiretap(true).bindNow();
    assertThat(connected).isNotNull();
    Connection clientContext = client.handle((in, out) -> out.sendString(Flux.just("Hello World!\n", "Hello 11!\n"))).wiretap(true).connectNow();
    assertThat(clientContext).isNotNull();
    assertThat(latch.await(10, TimeUnit.SECONDS)).as("Latch was counted down").isTrue();
    connected.disposeNow();
    clientContext.disposeNow();
}
Also used : SNIHostName(javax.net.ssl.SNIHostName) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) BiFunction(java.util.function.BiFunction) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) ConnectionObserver(reactor.netty.ConnectionObserver) Loggers(reactor.util.Loggers) SocketChannel(java.nio.channels.SocketChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) NettyPipeline(reactor.netty.NettyPipeline) Duration(java.time.Duration) Logger(reactor.util.Logger) Path(java.nio.file.Path) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) LoopResources(reactor.netty.resources.LoopResources) ChannelGroup(io.netty.channel.group.ChannelGroup) FileSystem(java.nio.file.FileSystem) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ChannelBindException(reactor.netty.ChannelBindException) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) NettyOutbound(reactor.netty.NettyOutbound) Exceptions(reactor.core.Exceptions) DisposableServer(reactor.netty.DisposableServer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) SocketUtils(reactor.netty.SocketUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) Connection(reactor.netty.Connection) SslContext(io.netty.handler.ssl.SslContext) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Publisher(org.reactivestreams.Publisher) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) SslProvider(io.netty.handler.ssl.SslProvider) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) NettyInbound(reactor.netty.NettyInbound) Timeout(org.junit.jupiter.api.Timeout) FileSystems(java.nio.file.FileSystems) DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 3 with NettyOutbound

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

the class TcpClientTests method testIssue585_2.

@Test
void testIssue585_2() throws Exception {
    DisposableServer server = TcpServer.create().port(0).handle((req, res) -> res.send(req.receive().retain())).wiretap(true).bindNow();
    byte[] bytes = "test".getBytes(Charset.defaultCharset());
    ByteBuf b1 = Unpooled.wrappedBuffer(bytes);
    ByteBuf b2 = Unpooled.wrappedBuffer(bytes);
    ByteBuf b3 = Unpooled.wrappedBuffer(bytes);
    WeakReference<ByteBuf> refCheck1 = new WeakReference<>(b1);
    WeakReference<ByteBuf> refCheck2 = new WeakReference<>(b2);
    WeakReference<ByteBuf> refCheck3 = new WeakReference<>(b3);
    Connection conn = TcpClient.create().remoteAddress(server::address).wiretap(true).connectNow();
    NettyOutbound out = conn.outbound();
    out.sendObject(b1).then().block(Duration.ofSeconds(30));
    assertThat(b1.refCnt()).isEqualTo(0);
    b1 = null;
    checkReference(refCheck1);
    out.sendObject(b2).then().block(Duration.ofSeconds(30));
    assertThat(b2.refCnt()).isEqualTo(0);
    b2 = null;
    checkReference(refCheck2);
    out.sendObject(b3).then().block(Duration.ofSeconds(30));
    assertThat(b3.refCnt()).isEqualTo(0);
    b3 = null;
    checkReference(refCheck3);
    server.disposeNow();
    conn.disposeNow();
}
Also used : DisposableServer(reactor.netty.DisposableServer) NettyOutbound(reactor.netty.NettyOutbound) WeakReference(java.lang.ref.WeakReference) Connection(reactor.netty.Connection) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.Test)

Example 4 with NettyOutbound

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

the class TcpClientTests method testIssue585_1.

@Test
void testIssue585_1() throws Exception {
    DisposableServer server = TcpServer.create().port(0).handle((req, res) -> res.send(req.receive().retain())).wiretap(true).bindNow();
    CountDownLatch latch = new CountDownLatch(1);
    byte[] bytes = "test".getBytes(Charset.defaultCharset());
    ByteBuf b1 = Unpooled.wrappedBuffer(bytes);
    ByteBuf b2 = Unpooled.wrappedBuffer(bytes);
    ByteBuf b3 = Unpooled.wrappedBuffer(bytes);
    WeakReference<ByteBuf> refCheck1 = new WeakReference<>(b1);
    WeakReference<ByteBuf> refCheck2 = new WeakReference<>(b2);
    WeakReference<ByteBuf> refCheck3 = new WeakReference<>(b3);
    Connection conn = TcpClient.create().remoteAddress(server::address).wiretap(true).connectNow();
    NettyOutbound out = conn.outbound();
    Flux.concatDelayError(out.sendObject(Mono.error(new RuntimeException("test"))).sendObject(b1).then(), out.sendObject(Mono.error(new RuntimeException("test"))).sendObject(b2).then(), out.sendObject(Mono.error(new RuntimeException("test"))).sendObject(b3).then()).doOnError(t -> latch.countDown()).subscribe(conn.disposeSubscriber());
    assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    assertThat(b1.refCnt()).isEqualTo(0);
    b1 = null;
    checkReference(refCheck1);
    assertThat(b2.refCnt()).isEqualTo(0);
    b2 = null;
    checkReference(refCheck2);
    assertThat(b3.refCnt()).isEqualTo(0);
    b3 = null;
    checkReference(refCheck3);
    server.disposeNow();
    conn.disposeNow();
}
Also used : AttributeKey(io.netty.util.AttributeKey) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) SocketAddress(java.net.SocketAddress) AbortedException(reactor.netty.channel.AbortedException) Retry(reactor.util.retry.Retry) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) Future(java.util.concurrent.Future) Loggers(reactor.util.Loggers) SocketChannel(java.nio.channels.SocketChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) Duration(java.time.Duration) Logger(reactor.util.Logger) NameResolverProvider(reactor.netty.transport.NameResolverProvider) LoopResources(reactor.netty.resources.LoopResources) ChannelOperations(reactor.netty.channel.ChannelOperations) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) NettyOutbound(reactor.netty.NettyOutbound) DisposableServer(reactor.netty.DisposableServer) ChannelOption(io.netty.channel.ChannelOption) SocketUtils(reactor.netty.SocketUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Schedulers(reactor.core.scheduler.Schedulers) WeakReference(java.lang.ref.WeakReference) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) Properties(java.util.Properties) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) Publisher(org.reactivestreams.Publisher) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) ServerSocketChannel(java.nio.channels.ServerSocketChannel) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) Bootstrap(io.netty.bootstrap.Bootstrap) Flux(reactor.core.publisher.Flux) AfterEach(org.junit.jupiter.api.AfterEach) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) DefaultAddressResolverGroup(io.netty.resolver.DefaultAddressResolverGroup) ConnectionProvider(reactor.netty.resources.ConnectionProvider) DisposableServer(reactor.netty.DisposableServer) NettyOutbound(reactor.netty.NettyOutbound) WeakReference(java.lang.ref.WeakReference) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.Test)

Example 5 with NettyOutbound

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

the class DefaultHttpServerRoutesTest method directoryRouteTest.

@Test
void directoryRouteTest() throws URISyntaxException {
    HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
    Mockito.when(request.paramsResolver(Mockito.any())).thenReturn(request);
    Mockito.when(request.uri()).thenReturn("/test");
    Mockito.when(request.method()).thenReturn(HttpMethod.GET);
    Subscription subscription = Mockito.mock(Subscription.class);
    NettyOutbound outbound = Mockito.mock(NettyOutbound.class);
    Mockito.doAnswer(invocation -> {
        Subscriber<Void> subscriber = invocation.getArgument(0);
        subscriber.onSubscribe(subscription);
        subscriber.onNext(null);
        subscriber.onComplete();
        return null;
    }).when(outbound).subscribe(Mockito.any());
    HttpServerResponse response = Mockito.mock(HttpServerResponse.class);
    Mockito.when(response.sendFile(Mockito.any())).thenReturn(outbound);
    Path resource = Paths.get(getClass().getResource("/public").toURI());
    DefaultHttpServerRoutes routes = new DefaultHttpServerRoutes();
    HttpServerRoutes route = routes.directory("/test", resource);
    Publisher<Void> publisher = route.apply(request, response);
    assertThat(publisher).isNotNull();
    StepVerifier.create(publisher).expectNextMatches(p -> true).expectComplete().verify(Duration.ofMillis(200));
}
Also used : Path(java.nio.file.Path) NettyOutbound(reactor.netty.NettyOutbound) Subscription(org.reactivestreams.Subscription) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)5 NettyOutbound (reactor.netty.NettyOutbound)5 ByteBuf (io.netty.buffer.ByteBuf)4 Connection (reactor.netty.Connection)4 DisposableServer (reactor.netty.DisposableServer)4 Unpooled (io.netty.buffer.Unpooled)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)3 ChannelOption (io.netty.channel.ChannelOption)3 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)3 LineBasedFrameDecoder (io.netty.handler.codec.LineBasedFrameDecoder)3 NetUtil (io.netty.util.NetUtil)3 IOException (java.io.IOException)3 InetSocketAddress (java.net.InetSocketAddress)3 ByteBuffer (java.nio.ByteBuffer)3 SocketChannel (java.nio.channels.SocketChannel)3 Charset (java.nio.charset.Charset)3 Duration (java.time.Duration)3 List (java.util.List)3 CountDownLatch (java.util.concurrent.CountDownLatch)3