Search in sources :

Example 91 with DisposableServer

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

the class HttpRedirectTest method testLastLocationSetToResourceUrlOnRedirect.

@Test
void testLastLocationSetToResourceUrlOnRedirect() {
    final String redirectPath = "/redirect";
    final String destinationPath = "/destination";
    final String responseContent = "Success";
    Http11SslContextSpec serverSslContextSpec = Http11SslContextSpec.forServer(ssc.certificate(), ssc.privateKey());
    DisposableServer redirectServer = null;
    DisposableServer initialServer = null;
    try {
        redirectServer = createServer().route(r -> r.get(redirectPath, (req, res) -> res.sendRedirect(destinationPath)).get(destinationPath, (req, res) -> res.sendString(Mono.just(responseContent)))).secure(spec -> spec.sslContext(serverSslContextSpec)).bindNow();
        final int redirectServerPort = redirectServer.port();
        initialServer = createServer().handle((req, res) -> res.sendRedirect("https://localhost:" + redirectServerPort + destinationPath)).bindNow();
        Http11SslContextSpec clientSslContextSpec = Http11SslContextSpec.forClient().configure(builder -> builder.trustManager(InsecureTrustManagerFactory.INSTANCE));
        final String requestUri = "http://localhost:" + initialServer.port();
        StepVerifier.create(HttpClient.create().wiretap(true).followRedirect(true).secure(spec -> spec.sslContext(clientSslContextSpec)).get().uri(requestUri).response((res, conn) -> Mono.justOrEmpty(res.resourceUrl()))).expectNext("https://localhost:" + redirectServer.port() + destinationPath).expectComplete().verify(Duration.ofSeconds(30));
    } finally {
        if (redirectServer != null) {
            redirectServer.disposeNow();
        }
        if (initialServer != null) {
            initialServer.disposeNow();
        }
    }
}
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) DisposableServer(reactor.netty.DisposableServer) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 92 with DisposableServer

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

the class HttpRedirectTest method redirectTests.

private void redirectTests(String url) {
    AtomicInteger counter = new AtomicInteger(1);
    disposableServer = createServer().handle((req, res) -> {
        if (req.uri().contains("/login") && req.method().equals(HttpMethod.POST) && counter.getAndDecrement() > 0) {
            return res.sendRedirect(url);
        } else {
            return res.status(200).send();
        }
    }).bindNow();
    ConnectionProvider pool = ConnectionProvider.create("redirectTests", 1);
    HttpClient client = createClient(pool, disposableServer::address);
    Flux.range(0, 100).concatMap(i -> client.followRedirect(true).post().uri("/login").responseContent().then()).blockLast(Duration.ofSeconds(30));
}
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) ConnectionProvider(reactor.netty.resources.ConnectionProvider)

Example 93 with DisposableServer

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

the class DefaultPooledConnectionProviderTest method testIssue951_MaxPendingAcquire.

@Test
void testIssue951_MaxPendingAcquire() throws InterruptedException {
    DisposableServer server = TcpServer.create().port(0).handle((in, out) -> out.sendString(Mono.just("test").delayElement(Duration.ofMillis(100)))).wiretap(true).bindNow();
    DefaultPooledConnectionProvider provider = (DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue951_MaxPendingAcquire").maxConnections(1).pendingAcquireTimeout(Duration.ofMillis(30)).pendingAcquireMaxCount(1).build();
    CountDownLatch latch = new CountDownLatch(2);
    try {
        AtomicReference<InstrumentedPool<PooledConnection>> pool = new AtomicReference<>();
        List<? extends Signal<? extends Connection>> list = Flux.range(0, 3).flatMapDelayError(i -> TcpClient.create(provider).port(server.port()).doOnConnected(conn -> {
            ConcurrentMap<PooledConnectionProvider.PoolKey, InstrumentedPool<PooledConnection>> pools = provider.channelPools;
            pool.set(pools.get(pools.keySet().toArray()[0]));
        }).doOnDisconnected(conn -> latch.countDown()).handle((in, out) -> in.receive().then()).wiretap(true).connect().materialize(), 256, 32).collectList().doFinally(fin -> latch.countDown()).block(Duration.ofSeconds(30));
        assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch 30s").isTrue();
        assertThat(list).isNotNull().hasSize(3);
        int onNext = 0;
        int onErrorTimeout = 0;
        int onErrorPendingAcquire = 0;
        String msg1 = "Pool#acquire(Duration) has been pending for more than the configured timeout of 30ms";
        String msg2 = "Pending acquire queue has reached its maximum size of 1";
        for (int i = 0; i < 3; i++) {
            Signal<? extends Connection> signal = list.get(i);
            if (signal.isOnNext()) {
                onNext++;
            } else if (signal.getThrowable() instanceof TimeoutException && msg1.equals(signal.getThrowable().getMessage())) {
                onErrorTimeout++;
            } else if (signal.getThrowable() instanceof PoolAcquirePendingLimitException && msg2.equals(signal.getThrowable().getMessage())) {
                onErrorPendingAcquire++;
            }
        }
        assertThat(onNext).isEqualTo(1);
        assertThat(onErrorTimeout).isEqualTo(1);
        assertThat(onErrorPendingAcquire).isEqualTo(1);
        assertThat(pool.get().metrics().acquiredSize()).as("currently acquired").isEqualTo(0);
        assertThat(pool.get().metrics().idleSize()).as("currently idle").isEqualTo(0);
    } finally {
        server.disposeNow();
        provider.dispose();
    }
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) SocketAddress(java.net.SocketAddress) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) InstrumentedPool(reactor.pool.InstrumentedPool) TimeoutException(java.util.concurrent.TimeoutException) TcpClient(reactor.netty.tcp.TcpClient) ConnectionObserver(reactor.netty.ConnectionObserver) Future(java.util.concurrent.Future) PoolAcquirePendingLimitException(reactor.pool.PoolAcquirePendingLimitException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) NameResolverProvider(reactor.netty.transport.NameResolverProvider) PooledRef(reactor.pool.PooledRef) AddressResolver(io.netty.resolver.AddressResolver) Awaitility.await(org.awaitility.Awaitility.await) AddressUtils(reactor.netty.transport.AddressUtils) Signal(reactor.core.publisher.Signal) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SchedulerClock(reactor.scheduler.clock.SchedulerClock) LockSupport(java.util.concurrent.locks.LockSupport) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) DisposableServer(reactor.netty.DisposableServer) TcpClientTests(reactor.netty.tcp.TcpClientTests) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) SocketUtils(reactor.netty.SocketUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) ConcurrentMap(java.util.concurrent.ConcurrentMap) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TcpResources(reactor.netty.tcp.TcpResources) ConnectException(java.net.ConnectException) Connection(reactor.netty.Connection) ClientTransportConfig(reactor.netty.transport.ClientTransportConfig) EventLoopGroup(io.netty.channel.EventLoopGroup) VirtualTimeScheduler(reactor.test.scheduler.VirtualTimeScheduler) NetUtil(io.netty.util.NetUtil) Mono(reactor.core.publisher.Mono) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) Flux(reactor.core.publisher.Flux) ChannelMetricsRecorder(reactor.netty.channel.ChannelMetricsRecorder) TcpServer(reactor.netty.tcp.TcpServer) DefaultAddressResolverGroup(io.netty.resolver.DefaultAddressResolverGroup) Collections(java.util.Collections) ConcurrentMap(java.util.concurrent.ConcurrentMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) DisposableServer(reactor.netty.DisposableServer) InstrumentedPool(reactor.pool.InstrumentedPool) PoolAcquirePendingLimitException(reactor.pool.PoolAcquirePendingLimitException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.jupiter.api.Test)

Example 94 with DisposableServer

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

the class DefaultPooledConnectionProviderTest method doTestIssue1790.

private void doTestIssue1790(boolean fifoPool) {
    DefaultPooledConnectionProvider provider;
    if (fifoPool) {
        provider = (DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue1790").maxConnections(1).fifo().build();
    } else {
        provider = (DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue1790").maxConnections(1).lifo().build();
    }
    DisposableServer disposableServer = TcpServer.create().port(0).wiretap(true).bindNow();
    Connection connection = null;
    try {
        connection = TcpClient.create(provider).port(disposableServer.port()).wiretap(true).connectNow();
        assertThat(provider.channelPools).hasSize(1);
        @SuppressWarnings({ "unchecked", "rawtypes" }) InstrumentedPool<DefaultPooledConnectionProvider.PooledConnection> channelPool = provider.channelPools.values().toArray(new InstrumentedPool[0])[0];
        assertThat(channelPool.metrics()).withFailMessage("Reactor-netty relies on Reactor-pool instrumented pool.metrics()" + " to be the pool instance itself, got <%s> and <%s>", channelPool.metrics(), channelPool).isSameAs(channelPool);
    } finally {
        if (connection != null) {
            connection.disposeNow();
        }
        disposableServer.disposeNow();
        provider.disposeLater().block(Duration.ofSeconds(5));
    }
}
Also used : PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) DisposableServer(reactor.netty.DisposableServer) PooledConnection(reactor.netty.resources.DefaultPooledConnectionProvider.PooledConnection) Connection(reactor.netty.Connection) InstrumentedPool(reactor.pool.InstrumentedPool)

Example 95 with DisposableServer

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

the class TcpClientTests method testRetryOnDifferentAddress.

@Test
void testRetryOnDifferentAddress() throws Exception {
    DisposableServer server = TcpServer.create().port(0).wiretap(true).handle((req, res) -> res.sendString(Mono.just("test"))).bindNow();
    final CountDownLatch latch = new CountDownLatch(1);
    Supplier<SocketAddress> addressSupplier = new Supplier<SocketAddress>() {

        int i = 2;

        @Override
        public SocketAddress get() {
            return new InetSocketAddress("localhost", server.port() + i--);
        }
    };
    Connection conn = TcpClient.create().remoteAddress(addressSupplier).doOnConnected(connection -> latch.countDown()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100).handle((in, out) -> Mono.never()).wiretap(true).connect().retry().block(Duration.ofSeconds(30));
    assertThat(conn).isNotNull();
    assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    conn.disposeNow();
    server.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) InetSocketAddress(java.net.InetSocketAddress) Connection(reactor.netty.Connection) Supplier(java.util.function.Supplier) CountDownLatch(java.util.concurrent.CountDownLatch) SocketAddress(java.net.SocketAddress) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) InetSocketAddress(java.net.InetSocketAddress) 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