Search in sources :

Example 1 with HttpClientResponse

use of reactor.ipc.netty.http.client.HttpClientResponse in project spring-cloud-sleuth by spring-cloud.

the class TraceUserInfoRestTemplateCustomizer method wrapHttpClientRequestSending.

Mono<HttpClientResponse> wrapHttpClientRequestSending(ProceedingJoinPoint pjp, HttpMethod method, String url, Function<? super HttpClientRequest, ? extends Publisher<Void>> handler) throws Throwable {
    // add headers and set CS
    final Span currentSpan = this.tracer.currentSpan();
    final AtomicReference<Span> span = new AtomicReference<>();
    Function<HttpClientRequest, Publisher<Void>> combinedFunction = req -> {
        try (Tracer.SpanInScope spanInScope = this.tracer.withSpanInScope(currentSpan)) {
            io.netty.handler.codec.http.HttpHeaders originalHeaders = req.requestHeaders().copy();
            io.netty.handler.codec.http.HttpHeaders tracedHeaders = req.requestHeaders();
            span.set(this.handler.handleSend(this.injector, tracedHeaders, req));
            io.netty.handler.codec.http.HttpHeaders addedHeaders = tracedHeaders.copy();
            originalHeaders.forEach(header -> addedHeaders.remove(header.getKey()));
            try (Tracer.SpanInScope clientInScope = this.tracer.withSpanInScope(span.get())) {
                if (log.isDebugEnabled()) {
                    log.debug("Created a new client span for Netty client");
                }
                return handle(handler, new TracedHttpClientRequest(req, addedHeaders));
            }
        }
    };
    // run
    Mono<HttpClientResponse> responseMono = (Mono<HttpClientResponse>) pjp.proceed(new Object[] { method, url, combinedFunction });
    // get response
    return responseMono.doOnSuccessOrError((httpClientResponse, throwable) -> {
        try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.get())) {
            // status codes and CR
            this.handler.handleReceive(httpClientResponse, throwable, span.get());
            if (log.isDebugEnabled()) {
                log.debug("Setting client sent spans");
            }
        }
    });
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) HttpRequest(org.springframework.http.HttpRequest) Span(brave.Span) Autowired(org.springframework.beans.factory.annotation.Autowired) WebClient(org.springframework.web.reactive.function.client.WebClient) NettyOutbound(reactor.ipc.netty.NettyOutbound) UserInfoRestTemplateCustomizer(org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoRestTemplateCustomizer) HttpClientConfiguration(org.springframework.cloud.commons.httpclient.HttpClientConfiguration) Aspect(org.aspectj.lang.annotation.Aspect) Map(java.util.Map) Path(java.nio.file.Path) RestTemplate(org.springframework.web.client.RestTemplate) HttpTracing(brave.http.HttpTracing) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Tracer(brave.Tracer) Set(java.util.Set) Pointcut(org.aspectj.lang.annotation.Pointcut) Cookie(io.netty.handler.codec.http.cookie.Cookie) TraceContext(brave.propagation.TraceContext) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) Around(org.aspectj.lang.annotation.Around) BeanPostProcessor(org.springframework.beans.factory.config.BeanPostProcessor) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) ClientHttpRequestInterceptor(org.springframework.http.client.ClientHttpRequestInterceptor) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) TraceWebServletAutoConfiguration(org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration) HttpClientHandler(brave.http.HttpClientHandler) LogFactory(org.apache.commons.logging.LogFactory) ListableBeanFactory(org.springframework.beans.factory.ListableBeanFactory) HttpVersion(io.netty.handler.codec.http.HttpVersion) ConditionalOnClass(org.springframework.boot.autoconfigure.condition.ConditionalOnClass) RestTemplateCustomizer(org.springframework.boot.web.client.RestTemplateCustomizer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) OAuth2RestTemplate(org.springframework.security.oauth2.client.OAuth2RestTemplate) ArrayList(java.util.ArrayList) AutoConfigureAfter(org.springframework.boot.autoconfigure.AutoConfigureAfter) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) NettyPipeline(reactor.ipc.netty.NettyPipeline) HttpClient(reactor.ipc.netty.http.client.HttpClient) Propagation(brave.propagation.Propagation) WebsocketOutbound(reactor.ipc.netty.http.websocket.WebsocketOutbound) Subscriber(org.reactivestreams.Subscriber) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) ClientHttpRequestExecution(org.springframework.http.client.ClientHttpRequestExecution) ConditionalOnBean(org.springframework.boot.autoconfigure.condition.ConditionalOnBean) Order(org.springframework.core.annotation.Order) FileChunkedStrategy(reactor.ipc.netty.channel.data.FileChunkedStrategy) Publisher(org.reactivestreams.Publisher) TracingClientHttpRequestInterceptor(brave.spring.web.TracingClientHttpRequestInterceptor) HttpMethod(io.netty.handler.codec.http.HttpMethod) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) Mono(reactor.core.publisher.Mono) Consumer(java.util.function.Consumer) Flux(reactor.core.publisher.Flux) TracingHttpAsyncClientBuilder(brave.httpasyncclient.TracingHttpAsyncClientBuilder) BeanFactory(org.springframework.beans.factory.BeanFactory) NettyContext(reactor.ipc.netty.NettyContext) HttpClientRequest(reactor.ipc.netty.http.client.HttpClientRequest) TracingHttpClientBuilder(brave.httpclient.TracingHttpClientBuilder) Log(org.apache.commons.logging.Log) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) Bean(org.springframework.context.annotation.Bean) AutoConfigureBefore(org.springframework.boot.autoconfigure.AutoConfigureBefore) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) Tracer(brave.Tracer) Mono(reactor.core.publisher.Mono) AtomicReference(java.util.concurrent.atomic.AtomicReference) Publisher(org.reactivestreams.Publisher) Span(brave.Span) HttpClientRequest(reactor.ipc.netty.http.client.HttpClientRequest) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse)

Example 2 with HttpClientResponse

use of reactor.ipc.netty.http.client.HttpClientResponse in project reactor-netty by reactor.

the class HttpServerTests method keepAlive.

@Test
public void keepAlive() throws URISyntaxException {
    Path resource = Paths.get(getClass().getResource("/public").toURI());
    NettyContext c = HttpServer.create(0).newRouter(routes -> routes.directory("/test", resource)).block(Duration.ofSeconds(30));
    HttpResources.set(PoolResources.fixed("http", 1));
    HttpClientResponse response0 = HttpClient.create(c.address().getPort()).get("/test/index.html").block(Duration.ofSeconds(30));
    HttpClientResponse response1 = HttpClient.create(c.address().getPort()).get("/test/test.css").block(Duration.ofSeconds(30));
    HttpClientResponse response2 = HttpClient.create(c.address().getPort()).get("/test/test1.css").block(Duration.ofSeconds(30));
    HttpClientResponse response3 = HttpClient.create(c.address().getPort()).get("/test/test2.css").block(Duration.ofSeconds(30));
    HttpClientResponse response4 = HttpClient.create(c.address().getPort()).get("/test/test3.css").block(Duration.ofSeconds(30));
    HttpClientResponse response5 = HttpClient.create(c.address().getPort()).get("/test/test4.css").block(Duration.ofSeconds(30));
    HttpClientResponse response6 = HttpClient.create(opts -> opts.port(c.address().getPort()).disablePool()).get("/test/test5.css").block(Duration.ofSeconds(30));
    Assert.assertEquals(response0.channel(), response1.channel());
    Assert.assertEquals(response0.channel(), response2.channel());
    Assert.assertEquals(response0.channel(), response3.channel());
    Assert.assertEquals(response0.channel(), response4.channel());
    Assert.assertEquals(response0.channel(), response5.channel());
    Assert.assertNotEquals(response0.channel(), response6.channel());
    HttpResources.reset();
    response0.dispose();
    response1.dispose();
    response2.dispose();
    response3.dispose();
    response4.dispose();
    response5.dispose();
    response6.dispose();
    c.dispose();
}
Also used : Path(java.nio.file.Path) HttpResources(reactor.ipc.netty.http.HttpResources) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) NettyOutbound(reactor.ipc.netty.NettyOutbound) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) BlockingNettyContext(reactor.ipc.netty.tcp.BlockingNettyContext) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Path(java.nio.file.Path) Context(reactor.util.context.Context) StandardOpenOption(java.nio.file.StandardOpenOption) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FileSystem(java.nio.file.FileSystem) InetSocketAddress(java.net.InetSocketAddress) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) SSLException(javax.net.ssl.SSLException) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) ByteBufFlux(reactor.ipc.netty.ByteBufFlux) HttpVersion(io.netty.handler.codec.http.HttpVersion) FluxSink(reactor.core.publisher.FluxSink) Tuple3(reactor.util.function.Tuple3) Tuple2(reactor.util.function.Tuple2) AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) ByteBuf(io.netty.buffer.ByteBuf) Assert(org.testng.Assert) HttpClient(reactor.ipc.netty.http.client.HttpClient) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ExecutorService(java.util.concurrent.ExecutorService) TcpClient(reactor.ipc.netty.tcp.TcpClient) SslContext(io.netty.handler.ssl.SslContext) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) FutureMono(reactor.ipc.netty.FutureMono) CompletionHandler(java.nio.channels.CompletionHandler) HttpMethod(io.netty.handler.codec.http.HttpMethod) IOException(java.io.IOException) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) PoolResources(reactor.ipc.netty.resources.PoolResources) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) AtomicLong(java.util.concurrent.atomic.AtomicLong) Flux(reactor.core.publisher.Flux) Paths(java.nio.file.Paths) NettyContext(reactor.ipc.netty.NettyContext) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) FileSystems(java.nio.file.FileSystems) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) BlockingNettyContext(reactor.ipc.netty.tcp.BlockingNettyContext) NettyContext(reactor.ipc.netty.NettyContext) Test(org.junit.Test)

Example 3 with HttpClientResponse

use of reactor.ipc.netty.http.client.HttpClientResponse in project reactor-netty by reactor.

the class HttpServerTests method sendFileSecure.

@Test
public void sendFileSecure() throws CertificateException, SSLException, URISyntaxException {
    Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").toURI());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer)).newHandler((req, resp) -> resp.sendFile(largeFile)).block();
    HttpClientResponse response = HttpClient.create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)).get("/foo").block(Duration.ofSeconds(120));
    context.dispose();
    context.onClose().block();
    String body = response.receive().aggregate().asString(StandardCharsets.UTF_8).block();
    assertThat(body).startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.").contains("1024 mark here -><- 1024 mark here").endsWith("End of File");
}
Also used : Path(java.nio.file.Path) HttpResources(reactor.ipc.netty.http.HttpResources) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) NettyOutbound(reactor.ipc.netty.NettyOutbound) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) BlockingNettyContext(reactor.ipc.netty.tcp.BlockingNettyContext) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Path(java.nio.file.Path) Context(reactor.util.context.Context) StandardOpenOption(java.nio.file.StandardOpenOption) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FileSystem(java.nio.file.FileSystem) InetSocketAddress(java.net.InetSocketAddress) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) SSLException(javax.net.ssl.SSLException) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) ByteBufFlux(reactor.ipc.netty.ByteBufFlux) HttpVersion(io.netty.handler.codec.http.HttpVersion) FluxSink(reactor.core.publisher.FluxSink) Tuple3(reactor.util.function.Tuple3) Tuple2(reactor.util.function.Tuple2) AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) ByteBuf(io.netty.buffer.ByteBuf) Assert(org.testng.Assert) HttpClient(reactor.ipc.netty.http.client.HttpClient) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ExecutorService(java.util.concurrent.ExecutorService) TcpClient(reactor.ipc.netty.tcp.TcpClient) SslContext(io.netty.handler.ssl.SslContext) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) FutureMono(reactor.ipc.netty.FutureMono) CompletionHandler(java.nio.channels.CompletionHandler) HttpMethod(io.netty.handler.codec.http.HttpMethod) IOException(java.io.IOException) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) PoolResources(reactor.ipc.netty.resources.PoolResources) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) AtomicLong(java.util.concurrent.atomic.AtomicLong) Flux(reactor.core.publisher.Flux) Paths(java.nio.file.Paths) NettyContext(reactor.ipc.netty.NettyContext) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) FileSystems(java.nio.file.FileSystems) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) SslContext(io.netty.handler.ssl.SslContext) BlockingNettyContext(reactor.ipc.netty.tcp.BlockingNettyContext) NettyContext(reactor.ipc.netty.NettyContext) Test(org.junit.Test)

Example 4 with HttpClientResponse

use of reactor.ipc.netty.http.client.HttpClientResponse in project reactor-netty by reactor.

the class NettyOptionsTest method afterChannelInit.

@Test
public void afterChannelInit() throws InterruptedException {
    List<Channel> initializedChannels = new ArrayList<>();
    NettyContext nettyContext = HttpServer.create(opt -> opt.afterChannelInit(initializedChannels::add)).start((req, resp) -> resp.sendNotFound()).getContext();
    assertThat(initializedChannels).hasSize(0);
    HttpClientResponse resp = HttpClient.create(opt -> opt.connectAddress(() -> nettyContext.address())).get("/", req -> req.failOnClientError(false).send()).block();
    assertThat(initializedChannels).hasSize(1).doesNotContain(nettyContext.channel());
    resp.dispose();
    nettyContext.dispose();
}
Also used : ChannelGroup(io.netty.channel.group.ChannelGroup) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) ArrayList(java.util.ArrayList) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NettyContext(reactor.ipc.netty.NettyContext) HttpClient(reactor.ipc.netty.http.client.HttpClient) HttpServer(reactor.ipc.netty.http.server.HttpServer) Channel(io.netty.channel.Channel) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) ArrayList(java.util.ArrayList) NettyContext(reactor.ipc.netty.NettyContext) Test(org.junit.Test)

Example 5 with HttpClientResponse

use of reactor.ipc.netty.http.client.HttpClientResponse in project reactor-netty by reactor.

the class NettyOptionsTest method channelIsAddedToChannelGroup.

@Test
public void channelIsAddedToChannelGroup() {
    // create a ChannelGroup that never removes disconnected channels
    ChannelGroup group = new DefaultChannelGroup(null) {

        @Override
        public boolean remove(Object o) {
            System.err.println("removed " + o);
            return false;
        }
    };
    NettyContext nettyContext = HttpServer.create(opt -> opt.channelGroup(group)).start((req, resp) -> resp.sendNotFound()).getContext();
    HttpClientResponse resp = HttpClient.create(opt -> opt.connectAddress(() -> nettyContext.address())).get("/", req -> req.failOnClientError(false).send()).block();
    assertThat((Iterable<Channel>) group).doesNotContain(nettyContext.channel()).hasSize(1);
    resp.dispose();
    nettyContext.dispose();
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelGroup(io.netty.channel.group.ChannelGroup) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) ArrayList(java.util.ArrayList) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NettyContext(reactor.ipc.netty.NettyContext) HttpClient(reactor.ipc.netty.http.client.HttpClient) HttpServer(reactor.ipc.netty.http.server.HttpServer) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) Channel(io.netty.channel.Channel) ChannelGroup(io.netty.channel.group.ChannelGroup) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) NettyContext(reactor.ipc.netty.NettyContext) Test(org.junit.Test)

Aggregations

HttpClientResponse (reactor.ipc.netty.http.client.HttpClientResponse)30 Mono (reactor.core.publisher.Mono)29 Test (org.junit.Test)27 NettyContext (reactor.ipc.netty.NettyContext)27 HttpClient (reactor.ipc.netty.http.client.HttpClient)27 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)25 Duration (java.time.Duration)21 AtomicReference (java.util.concurrent.atomic.AtomicReference)21 Flux (reactor.core.publisher.Flux)21 StepVerifier (reactor.test.StepVerifier)21 InetSocketAddress (java.net.InetSocketAddress)20 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)19 HttpServer (reactor.ipc.netty.http.server.HttpServer)19 Ignore (org.junit.Ignore)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)12 Assert (org.junit.Assert)12 ByteArrayInputStream (java.io.ByteArrayInputStream)11 IOException (java.io.IOException)11 GZIPInputStream (java.util.zip.GZIPInputStream)11 Consumer (java.util.function.Consumer)10