Search in sources :

Example 1 with HttpProtocol

use of reactor.netty.http.HttpProtocol in project reactor-netty by reactor.

the class HttpClientConfig method protocols.

void protocols(HttpProtocol... protocols) {
    this.protocols = protocols;
    int _protocols = 0;
    for (HttpProtocol p : protocols) {
        if (p == HttpProtocol.HTTP11) {
            _protocols |= h11;
        } else if (p == HttpProtocol.H2) {
            _protocols |= h2;
        } else if (p == HttpProtocol.H2C) {
            _protocols |= h2c;
        }
    }
    this._protocols = _protocols;
}
Also used : HttpProtocol(reactor.netty.http.HttpProtocol)

Example 2 with HttpProtocol

use of reactor.netty.http.HttpProtocol in project reactor-netty by reactor.

the class HttpServerTests method doTestIssue1978.

private void doTestIssue1978(HttpProtocol[] serverProtocols, HttpProtocol[] clientProtocols, @Nullable Http2SslContextSpec serverCtx, @Nullable Http2SslContextSpec clientCtx, long serverDelay, long clientDelay) throws Exception {
    int count = 5;
    CountDownLatch latch = new CountDownLatch(count);
    Mono<String> mono = Mono.just("testIssue1978");
    Mono<String> serverResponse = serverDelay == 0 ? mono : mono.delayElement(Duration.ofMillis(serverDelay));
    HttpServer mainServer = HttpServer.create().protocol(serverProtocols).httpRequestDecoder(spec -> spec.h2cMaxContentLength(8 * 1024));
    HttpServer server = serverCtx != null ? mainServer.secure(sslContextSpec -> sslContextSpec.sslContext(serverCtx)) : mainServer;
    disposableServer = server.handle((req, res) -> {
        req.withConnection(conn -> conn.channel().closeFuture().addListener(f -> latch.countDown()));
        return res.sendString(serverResponse);
    }).bindNow();
    byte[] content = new byte[1024];
    Random rndm = new Random();
    rndm.nextBytes(content);
    String strContent = new String(content, Charset.defaultCharset());
    Flux<String> flux = Flux.just(strContent, strContent, strContent, strContent);
    Flux<String> clientRequest = clientDelay == 0 ? flux : flux.delayElements(Duration.ofMillis(clientDelay));
    HttpClient mainClient = HttpClient.create().port(disposableServer.port()).protocol(clientProtocols);
    HttpClient client = clientCtx != null ? mainClient.secure(sslContextSpec -> sslContextSpec.sslContext(clientCtx)) : mainClient;
    Flux.range(0, count).flatMap(i -> client.post().uri("/").send(ByteBufFlux.fromString(clientRequest)).responseContent().aggregate().asString()).blockLast(Duration.ofSeconds(10));
    assertThat(latch.await(10, TimeUnit.SECONDS)).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) Random(java.util.Random) HttpClient(reactor.netty.http.client.HttpClient) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 3 with HttpProtocol

use of reactor.netty.http.HttpProtocol in project reactor-netty by reactor.

the class DefaultPooledConnectionProviderTest method doTestIssue1982.

private void doTestIssue1982(HttpProtocol[] serverProtocols, HttpProtocol[] clientProtocols, @Nullable Http2SslContextSpec serverCtx, @Nullable Http2SslContextSpec clientCtx) throws Exception {
    HttpServer server = serverCtx != null ? HttpServer.create().secure(sslContextSpec -> sslContextSpec.sslContext(serverCtx)) : HttpServer.create();
    disposableServer = server.protocol(serverProtocols).http2Settings(h2 -> h2.maxConcurrentStreams(20)).handle((req, res) -> res.sendString(Mono.just("testIssue1982").delayElement(Duration.ofMillis(100)))).bindNow();
    DefaultPooledConnectionProvider provider = (DefaultPooledConnectionProvider) ConnectionProvider.create("", 5);
    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger counter = new AtomicInteger();
    HttpClient mainClient = clientCtx != null ? HttpClient.create(provider).port(disposableServer.port()).secure(sslContextSpec -> sslContextSpec.sslContext(clientCtx)) : HttpClient.create(provider).port(disposableServer.port());
    HttpClient client = mainClient.protocol(clientProtocols).observe((conn, state) -> {
        if (state == ConnectionObserver.State.CONNECTED) {
            counter.incrementAndGet();
        }
        if (state == ConnectionObserver.State.RELEASED && counter.decrementAndGet() == 0) {
            latch.countDown();
        }
    });
    try {
        Flux.range(0, 80).flatMap(i -> client.get().uri("/").responseContent().aggregate().asString()).blockLast(Duration.ofSeconds(10));
        assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
        @SuppressWarnings({ "unchecked", "rawtypes" }) InstrumentedPool<DefaultPooledConnectionProvider.PooledConnection> channelPool = provider.channelPools.values().toArray(new InstrumentedPool[0])[0];
        InstrumentedPool.PoolMetrics metrics = channelPool.metrics();
        assertThat(metrics.acquiredSize()).isEqualTo(0);
        assertThat(metrics.allocatedSize()).isEqualTo(metrics.idleSize());
    } finally {
        provider.disposeLater().block(Duration.ofSeconds(5));
    }
}
Also used : StepVerifier(reactor.test.StepVerifier) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) SocketAddress(java.net.SocketAddress) PoolShutdownException(reactor.netty.internal.shaded.reactor.pool.PoolShutdownException) HttpProtocol(reactor.netty.http.HttpProtocol) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) BaseHttpTest(reactor.netty.BaseHttpTest) Disabled(org.junit.jupiter.api.Disabled) StringUtils(org.apache.commons.lang3.StringUtils) Nullable(reactor.util.annotation.Nullable) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConcurrentMap(java.util.concurrent.ConcurrentMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) ConnectionObserver(reactor.netty.ConnectionObserver) ChannelPromise(io.netty.channel.ChannelPromise) BeforeAll(org.junit.jupiter.api.BeforeAll) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) ByteBufMono(reactor.netty.ByteBufMono) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) MethodSource(org.junit.jupiter.params.provider.MethodSource) ValueSource(org.junit.jupiter.params.provider.ValueSource) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) SslContext(io.netty.handler.ssl.SslContext) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InstrumentedPool(reactor.netty.internal.shaded.reactor.pool.InstrumentedPool) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) Signal(reactor.core.publisher.Signal) CertificateException(java.security.cert.CertificateException) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) Flux(reactor.core.publisher.Flux) CountDownLatch(java.util.concurrent.CountDownLatch) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) HttpServer(reactor.netty.http.server.HttpServer) SSLException(javax.net.ssl.SSLException) List(java.util.List) SslProvider(io.netty.handler.ssl.SslProvider) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) HttpClient(reactor.netty.http.client.HttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpClient(reactor.netty.http.client.HttpClient) HttpServer(reactor.netty.http.server.HttpServer) InstrumentedPool(reactor.netty.internal.shaded.reactor.pool.InstrumentedPool) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 4 with HttpProtocol

use of reactor.netty.http.HttpProtocol in project reactor-netty by reactor.

the class HttpServerConfig method protocols.

void protocols(HttpProtocol... protocols) {
    this.protocols = protocols;
    int _protocols = 0;
    for (HttpProtocol p : protocols) {
        if (p == HttpProtocol.HTTP11) {
            _protocols |= h11;
        } else if (p == HttpProtocol.H2) {
            _protocols |= h2;
        } else if (p == HttpProtocol.H2C) {
            _protocols |= h2c;
        }
    }
    this._protocols = _protocols;
}
Also used : HttpProtocol(reactor.netty.http.HttpProtocol)

Example 5 with HttpProtocol

use of reactor.netty.http.HttpProtocol in project reactor-netty by reactor.

the class HttpServerPostFormTests method doTestPostForm.

private void doTestPostForm(HttpServer server, HttpClient client, Consumer<HttpServerFormDecoderProvider.Builder> provider, boolean configOnServer, boolean multipart, boolean streaming, @Nullable String expectedResponse) throws Exception {
    AtomicReference<List<HttpData>> originalHttpData1 = new AtomicReference<>(new ArrayList<>());
    AtomicReference<List<HttpData>> originalHttpData2 = new AtomicReference<>(new ArrayList<>());
    AtomicReference<Map<String, CompositeByteBuf>> copiedHttpData = new AtomicReference<>(new HashMap<>());
    server = (configOnServer ? server.httpFormDecoder(provider) : server).handle((req, res) -> res.sendString((configOnServer ? req.receiveForm() : req.receiveForm(provider)).flatMap(data -> {
        if ("0".equals(req.path())) {
            originalHttpData1.get().add(data);
            if (streaming) {
                CompositeByteBuf copy = copiedHttpData.get().computeIfAbsent(data.getName(), k -> Unpooled.compositeBuffer());
                try {
                    // In case of streaming this is not a blocking call
                    copy.writeBytes(data.get());
                } catch (IOException e) {
                    return Mono.error(e);
                }
            }
        } else {
            originalHttpData2.get().add(data);
        }
        return Mono.just('[' + data.getName() + ' ' + data.getClass().getSimpleName() + ' ' + data.isCompleted() + "] ");
    }).onErrorResume(t -> Mono.just(t.getCause().getMessage())).log()));
    disposableServer = server.bindNow();
    List<Tuple2<Integer, String>> responses;
    Path file = Paths.get(getClass().getResource("/largeFile1.txt").toURI());
    responses = Flux.range(0, 2).flatMap(i -> client.port(disposableServer.port()).post().uri("/" + i).sendForm((req, form) -> form.multipart(multipart).file("test1", "largeFile1.txt", file.toFile(), null).attr("attr1", "attr2").file("test2", "largeFile1.txt", file.toFile(), null)).responseSingle((r, buf) -> buf.asString().map(s -> Tuples.of(r.status().code(), s)))).collectList().block(Duration.ofSeconds(30));
    assertThat(responses).as("response").isNotNull();
    for (Tuple2<Integer, String> response : responses) {
        assertThat(response.getT1()).as("status code").isEqualTo(200);
        if (expectedResponse != null) {
            assertThat(response.getT2()).as("response body reflecting request").contains(expectedResponse);
        }
    }
    assertThat(originalHttpData1.get()).allMatch(data -> data.refCnt() == 0);
    assertThat(originalHttpData2.get()).allMatch(data -> data.refCnt() == 0);
    if (streaming) {
        if (expectedResponse == null) {
            assertThat(copiedHttpData.get()).hasSize(3);
            byte[] fileBytes = Files.readAllBytes(file);
            testContent(copiedHttpData.get().get("test1"), fileBytes);
            testContent(copiedHttpData.get().get("test2"), fileBytes);
            copiedHttpData.get().forEach((s, buffer) -> buffer.release());
        } else {
            List<HttpProtocol> serverProtocols = Arrays.asList(server.configuration().protocols());
            if (serverProtocols.size() == 1 && serverProtocols.get(0).equals(HttpProtocol.HTTP11)) {
                assertThat(copiedHttpData.get()).hasSize(1);
                copiedHttpData.get().forEach((s, buffer) -> buffer.release());
            } else {
                assertThat(copiedHttpData.get()).hasSize(0);
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) HttpProtocol(reactor.netty.http.HttpProtocol) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) Tuples(reactor.util.function.Tuples) BaseHttpTest(reactor.netty.BaseHttpTest) Tuple2(reactor.util.function.Tuple2) HashMap(java.util.HashMap) Nullable(reactor.util.annotation.Nullable) AtomicReference(java.util.concurrent.atomic.AtomicReference) Unpooled(io.netty.buffer.Unpooled) Retention(java.lang.annotation.Retention) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) HttpData(io.netty.handler.codec.http.multipart.HttpData) Duration(java.time.Duration) Map(java.util.Map) Path(java.nio.file.Path) MethodSource(org.junit.jupiter.params.provider.MethodSource) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) Target(java.lang.annotation.Target) ElementType(java.lang.annotation.ElementType) Consumer(java.util.function.Consumer) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) List(java.util.List) Paths(java.nio.file.Paths) HttpClient(reactor.netty.http.client.HttpClient) RetentionPolicy(java.lang.annotation.RetentionPolicy) Path(java.nio.file.Path) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) HttpProtocol(reactor.netty.http.HttpProtocol) Tuple2(reactor.util.function.Tuple2) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

HttpProtocol (reactor.netty.http.HttpProtocol)5 InsecureTrustManagerFactory (io.netty.handler.ssl.util.InsecureTrustManagerFactory)3 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)3 IOException (java.io.IOException)3 Duration (java.time.Duration)3 List (java.util.List)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)3 MethodSource (org.junit.jupiter.params.provider.MethodSource)3 Flux (reactor.core.publisher.Flux)3 Mono (reactor.core.publisher.Mono)3 BaseHttpTest (reactor.netty.BaseHttpTest)3 Http2SslContextSpec (reactor.netty.http.Http2SslContextSpec)3 HttpClient (reactor.netty.http.client.HttpClient)3 Nullable (reactor.util.annotation.Nullable)3 Unpooled (io.netty.buffer.Unpooled)2 Channel (io.netty.channel.Channel)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)2