Search in sources :

Example 11 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod 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 12 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project jocean-http by isdom.

the class DefaultSignalClientTestCase method testSignalClientWithoutSignalBeanForPostWithJSONContentAndUsingUri.

@Test
public void testSignalClientWithoutSignalBeanForPostWithJSONContentAndUsingUri() throws Exception {
    final byte[] respToSendback = new byte[] { 12, 13, 14, 15 };
    final AtomicReference<HttpMethod> reqMethodReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqpathReceivedRef = new AtomicReference<>();
    final AtomicReference<TestRequestByPost> reqbeanReceivedRef = new AtomicReference<>();
    final Action2<FullHttpRequest, HttpTrade> requestAndTradeAwareWhenCompleted = new Action2<FullHttpRequest, HttpTrade>() {

        @Override
        public void call(final FullHttpRequest req, final HttpTrade trade) {
            try {
                reqMethodReceivedRef.set(req.method());
                reqpathReceivedRef.set(req.uri());
                reqbeanReceivedRef.set((TestRequestByPost) JSON.parseObject(Nettys.dumpByteBufAsBytes(req.content()), TestRequestByPost.class));
            } catch (IOException e) {
                LOG.warn("exception when Nettys.dumpByteBufAsBytes, detail: {}", ExceptionUtils.exception2detail(e));
            }
            trade.outbound(buildBytesResponse(respToSendback, trade.onTerminate()));
        }
    };
    final String testAddr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(testAddr, requestAndTradeAwareWhenCompleted, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
    try {
        final TestChannelCreator creator = new TestChannelCreator();
        final TestChannelPool pool = new TestChannelPool(1);
        final DefaultHttpClient httpclient = new DefaultHttpClient(creator, pool, Feature.ENABLE_LOGGING);
        final DefaultSignalClient signalClient = new DefaultSignalClient(buildUri2Addr(testAddr), httpclient);
        final byte[] bytesReceived = ((SignalClient) signalClient).interaction().request(new Object()).feature(new SignalClient.UsingUri(new URI("http://test")), new SignalClient.UsingPath("/test/raw"), new SignalClient.UsingMethod(POST.class), new SignalClient.JSONContent("{\"code\": \"added\"}")).<byte[]>build().timeout(1, TimeUnit.SECONDS).toBlocking().single();
        assertEquals(HttpMethod.POST, reqMethodReceivedRef.get());
        assertEquals("/test/raw", reqpathReceivedRef.get());
        assertEquals(new TestRequestByPost(null, "added"), reqbeanReceivedRef.get());
        assertTrue(Arrays.equals(respToSendback, bytesReceived));
        pool.awaitRecycleChannels();
    } finally {
        server.unsubscribe();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) POST(javax.ws.rs.POST) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) Subscription(rx.Subscription) Action2(rx.functions.Action2) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) SignalClient(org.jocean.http.rosa.SignalClient) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) HttpObject(io.netty.handler.codec.http.HttpObject) HttpMethod(io.netty.handler.codec.http.HttpMethod) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Example 13 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project jocean-http by isdom.

the class DefaultSignalClientTestCase method testSignalClientWithoutSignalBeanForPostWithJSONContent.

@Test
public void testSignalClientWithoutSignalBeanForPostWithJSONContent() throws Exception {
    final byte[] respToSendback = new byte[] { 12, 13, 14, 15 };
    final AtomicReference<HttpMethod> reqMethodReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqpathReceivedRef = new AtomicReference<>();
    final AtomicReference<TestRequestByPost> reqbeanReceivedRef = new AtomicReference<>();
    final Action2<FullHttpRequest, HttpTrade> requestAndTradeAwareWhenCompleted = new Action2<FullHttpRequest, HttpTrade>() {

        @Override
        public void call(final FullHttpRequest req, final HttpTrade trade) {
            try {
                reqMethodReceivedRef.set(req.method());
                reqpathReceivedRef.set(req.uri());
                reqbeanReceivedRef.set((TestRequestByPost) JSON.parseObject(Nettys.dumpByteBufAsBytes(req.content()), TestRequestByPost.class));
            } catch (IOException e) {
                LOG.warn("exception when Nettys.dumpByteBufAsBytes, detail: {}", ExceptionUtils.exception2detail(e));
            }
            trade.outbound(buildBytesResponse(respToSendback, trade.onTerminate()));
        }
    };
    final String testAddr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(testAddr, requestAndTradeAwareWhenCompleted, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
    try {
        final TestChannelCreator creator = new TestChannelCreator();
        final TestChannelPool pool = new TestChannelPool(1);
        final DefaultHttpClient httpclient = new DefaultHttpClient(creator, pool, Feature.ENABLE_LOGGING);
        final DefaultSignalClient signalClient = new DefaultSignalClient(new URI("http://test"), buildUri2Addr(testAddr), httpclient);
        final byte[] bytesReceived = ((SignalClient) signalClient).interaction().request(new Object()).feature(new SignalClient.UsingPath("/test/raw"), new SignalClient.UsingMethod(POST.class), new SignalClient.JSONContent("{\"code\": \"added\"}")).<byte[]>build().timeout(1, TimeUnit.SECONDS).toBlocking().single();
        assertEquals(HttpMethod.POST, reqMethodReceivedRef.get());
        assertEquals("/test/raw", reqpathReceivedRef.get());
        assertEquals(new TestRequestByPost(null, "added"), reqbeanReceivedRef.get());
        assertTrue(Arrays.equals(respToSendback, bytesReceived));
        pool.awaitRecycleChannels();
    } finally {
        server.unsubscribe();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) POST(javax.ws.rs.POST) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) Subscription(rx.Subscription) Action2(rx.functions.Action2) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) SignalClient(org.jocean.http.rosa.SignalClient) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) HttpObject(io.netty.handler.codec.http.HttpObject) HttpMethod(io.netty.handler.codec.http.HttpMethod) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Example 14 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project jocean-http by isdom.

the class DefaultSignalClientTestCase method testSignalClientOnlySignalForGetWithoutRegisterRespType.

@Test
public void testSignalClientOnlySignalForGetWithoutRegisterRespType() throws Exception {
    final byte[] respToSendback = new byte[] { 12, 13, 14, 15 };
    final AtomicReference<HttpMethod> reqMethodReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqpathReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqbeanReceivedRef = new AtomicReference<>();
    final Action2<FullHttpRequest, HttpTrade> requestAndTradeAwareWhenCompleted = new Action2<FullHttpRequest, HttpTrade>() {

        @Override
        public void call(final FullHttpRequest req, final HttpTrade trade) {
            reqMethodReceivedRef.set(req.method());
            final QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
            reqpathReceivedRef.set(decoder.path());
            reqbeanReceivedRef.set(decoder.parameters().get("id").get(0));
            trade.outbound(buildBytesResponse(respToSendback, trade.onTerminate()));
        }
    };
    final String testAddr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(testAddr, requestAndTradeAwareWhenCompleted, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
    try {
        final TestChannelCreator creator = new TestChannelCreator();
        final TestChannelPool pool = new TestChannelPool(1);
        final DefaultHttpClient httpclient = new DefaultHttpClient(creator, pool, Feature.ENABLE_LOGGING);
        final DefaultSignalClient signalClient = new DefaultSignalClient(new URI("http://test"), buildUri2Addr(testAddr), httpclient);
        final CommonRequest reqToSend = new CommonRequest("1");
        final byte[] bytesReceived = ((SignalClient) signalClient).interaction().request(reqToSend).feature(new SignalClient.UsingPath("/test/simpleRequest"), new SignalClient.UsingMethod(GET.class)).<byte[]>build().timeout(1, TimeUnit.SECONDS).toBlocking().single();
        assertEquals(HttpMethod.GET, reqMethodReceivedRef.get());
        assertEquals("/test/simpleRequest", reqpathReceivedRef.get());
        assertEquals(reqToSend.getId(), reqbeanReceivedRef.get());
        assertTrue(Arrays.equals(respToSendback, bytesReceived));
        pool.awaitRecycleChannels();
    } finally {
        server.unsubscribe();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Action2(rx.functions.Action2) AtomicReference(java.util.concurrent.atomic.AtomicReference) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) SignalClient(org.jocean.http.rosa.SignalClient) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) GET(javax.ws.rs.GET) Subscription(rx.Subscription) HttpMethod(io.netty.handler.codec.http.HttpMethod) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Example 15 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project jocean-http by isdom.

the class DefaultSignalClientTestCase method testSignalClientOnlySignalForGet.

@Test
public void testSignalClientOnlySignalForGet() throws Exception {
    final TestResponse respToSendback = new TestResponse("0", "OK");
    final AtomicReference<HttpMethod> reqMethodReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqpathReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqbeanReceivedRef = new AtomicReference<>();
    final Action2<FullHttpRequest, HttpTrade> requestAndTradeAwareWhenCompleted = new Action2<FullHttpRequest, HttpTrade>() {

        @Override
        public void call(final FullHttpRequest req, final HttpTrade trade) {
            reqMethodReceivedRef.set(req.method());
            final QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
            reqpathReceivedRef.set(decoder.path());
            reqbeanReceivedRef.set(decoder.parameters().get("id").get(0));
            trade.outbound(buildResponse(respToSendback, trade.onTerminate()));
        }
    };
    final String testAddr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(testAddr, requestAndTradeAwareWhenCompleted, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
    try {
        final TestChannelCreator creator = new TestChannelCreator();
        final TestChannelPool pool = new TestChannelPool(1);
        final DefaultHttpClient httpclient = new DefaultHttpClient(creator, pool);
        final DefaultSignalClient signalClient = new DefaultSignalClient(new URI("http://test"), httpclient);
        signalClient.registerRequestType(TestRequest.class, TestResponse.class, null, buildUri2Addr(testAddr), Feature.ENABLE_LOGGING);
        final TestRequest reqToSend = new TestRequest("1");
        final TestResponse respReceived = ((SignalClient) signalClient).interaction().request(reqToSend).<TestResponse>build().timeout(1, TimeUnit.SECONDS).toBlocking().single();
        assertEquals(HttpMethod.GET, reqMethodReceivedRef.get());
        assertEquals("/test/simpleRequest", reqpathReceivedRef.get());
        assertEquals(reqToSend.getId(), reqbeanReceivedRef.get());
        assertEquals(respToSendback, respReceived);
        pool.awaitRecycleChannels();
    } finally {
        server.unsubscribe();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Action2(rx.functions.Action2) AtomicReference(java.util.concurrent.atomic.AtomicReference) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) Subscription(rx.Subscription) HttpMethod(io.netty.handler.codec.http.HttpMethod) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Aggregations

HttpMethod (io.netty.handler.codec.http.HttpMethod)95 Test (org.junit.Test)51 HttpRequest (io.netty.handler.codec.http.HttpRequest)28 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)25 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)21 URI (java.net.URI)15 IOException (java.io.IOException)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)11 HttpVersion (io.netty.handler.codec.http.HttpVersion)11 DefaultHttpClient (org.jocean.http.client.impl.DefaultHttpClient)11 TestChannelCreator (org.jocean.http.client.impl.TestChannelCreator)11 TestChannelPool (org.jocean.http.client.impl.TestChannelPool)11 DefaultSignalClient (org.jocean.http.rosa.impl.DefaultSignalClient)11 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)11 Subscription (rx.Subscription)11 Action2 (rx.functions.Action2)11 ByteBuf (io.netty.buffer.ByteBuf)10 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)10 Map (java.util.Map)9