Search in sources :

Example 1 with DefaultHttpRequest

use of io.netty.handler.codec.http.DefaultHttpRequest in project elasticsearch by elastic.

the class Netty4HttpPipeliningHandlerTests method testThatPipeliningWorksWithChunkedRequests.

public void testThatPipeliningWorksWithChunkedRequests() throws InterruptedException {
    final int numberOfRequests = randomIntBetween(2, 128);
    final EmbeddedChannel embeddedChannel = new EmbeddedChannel(new AggregateUrisAndHeadersHandler(), new HttpPipeliningHandler(numberOfRequests), new WorkEmulatorHandler());
    for (int i = 0; i < numberOfRequests; i++) {
        final DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/" + i);
        embeddedChannel.writeInbound(request);
        embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    }
    final List<CountDownLatch> latches = new ArrayList<>();
    for (int i = numberOfRequests - 1; i >= 0; i--) {
        latches.add(finishRequest(Integer.toString(i)));
    }
    for (final CountDownLatch latch : latches) {
        latch.await();
    }
    embeddedChannel.flush();
    for (int i = 0; i < numberOfRequests; i++) {
        assertReadHttpMessageHasContent(embeddedChannel, Integer.toString(i));
    }
    assertTrue(embeddedChannel.isOpen());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) ArrayList(java.util.ArrayList) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 2 with DefaultHttpRequest

use of io.netty.handler.codec.http.DefaultHttpRequest in project jersey by jersey.

the class NettyConnector method apply.

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }
                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);
                    final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
                    p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
                }
                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
            }
        });
        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }
        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();
        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };
        ch.closeFuture().addListener(closeListener);
        HttpRequest nettyRequest;
        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }
        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }
        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }
        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });
            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);
                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });
            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }
    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }
    return settableFuture;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Configuration(javax.ws.rs.core.Configuration) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) CompletableFuture(java.util.concurrent.CompletableFuture) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) JdkSslContext(io.netty.handler.ssl.JdkSslContext) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Map(java.util.Map)

Example 3 with DefaultHttpRequest

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

the class DefaultHttpClientTestCase method testInitiatorInteractionSendPartRequestThenFailedAsHttp.

@Test(timeout = 5000)
public void testInitiatorInteractionSendPartRequestThenFailedAsHttp() throws Exception {
    // 配置 池化分配器 为 取消缓存,使用 Heap
    configDefaultAllocator();
    final PooledByteBufAllocator allocator = defaultAllocator();
    final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(1);
    final String addr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(addr, trades, Feature.ENABLE_LOGGING);
    final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING);
    assertEquals(0, allActiveAllocationsCount(allocator));
    try {
        final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
        req.headers().set(HttpHeaderNames.CONTENT_LENGTH, 100);
        final ConnectableObservable<HttpObject> errorOfEnd = Observable.<HttpObject>error(new RuntimeException("test error")).publish();
        final Channel ch1 = (Channel) startInteraction(client.initiator().remoteAddress(new LocalAddress(addr)), Observable.concat(Observable.<HttpObject>just(req), errorOfEnd), new Interaction() {

            @Override
            public void interact(final HttpInitiator initiator, final Observable<DisposableWrapper<FullHttpResponse>> getresp) throws Exception {
                final TestSubscriber<DisposableWrapper<FullHttpResponse>> subscriber = new TestSubscriber<>();
                getresp.subscribe(subscriber);
                // server side recv req
                final HttpTrade trade = trades.take();
                assertTrue(trade.isActive());
                // fire error
                errorOfEnd.connect();
                subscriber.awaitTerminalEvent();
                subscriber.assertError(RuntimeException.class);
                subscriber.assertNoValues();
                TerminateAware.Util.awaitTerminated(trade);
                assertTrue(!trade.isActive());
            }
        }, new Action1<WriteCtrl>() {

            @Override
            public void call(final WriteCtrl writeCtrl) {
                writeCtrl.setFlushPerWrite(true);
            }
        }).transport();
        assertEquals(0, allActiveAllocationsCount(allocator));
        final Channel ch2 = (Channel) startInteraction(client.initiator().remoteAddress(new LocalAddress(addr)), Observable.just(fullHttpRequest()), standardInteraction(allocator, trades)).transport();
        assertEquals(0, allActiveAllocationsCount(allocator));
        assertNotSame(ch1, ch2);
    } finally {
        client.close();
        server.unsubscribe();
    }
}
Also used : DisposableWrapper(org.jocean.idiom.DisposableWrapper) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpObject(io.netty.handler.codec.http.HttpObject) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Subscription(rx.Subscription) WriteCtrl(org.jocean.http.WriteCtrl) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) LocalAddress(io.netty.channel.local.LocalAddress) Channel(io.netty.channel.Channel) SSLException(javax.net.ssl.SSLException) TransportException(org.jocean.http.TransportException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TestSubscriber(rx.observers.TestSubscriber) Test(org.junit.Test)

Example 4 with DefaultHttpRequest

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

the class DefaultHttpTradeTestCase method testTradeForMultiSubscribeRequestOnlyOneToSource.

@Test
public final void testTradeForMultiSubscribeRequestOnlyOneToSource() {
    final DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    final HttpContent[] req_contents = Nettys4Test.buildContentArray(REQ_CONTENT.getBytes(Charsets.UTF_8), 1);
    final EmbeddedChannel channel = new EmbeddedChannel();
    final HttpTrade trade = new DefaultHttpTrade(channel);
    // trade.inboundHolder().setMaxBlockSize(-1);
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber1 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber1);
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber2 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber2);
    final TestSubscriber<DisposableWrapper<HttpObject>> reqSubscriber3 = new TestSubscriber<>();
    trade.inbound().subscribe(reqSubscriber3);
    writeToInboundAndFlush(channel, request);
    writeToInboundAndFlush(channel, req_contents[0]);
    reqSubscriber1.assertValueCount(2);
    reqSubscriber1.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
    reqSubscriber2.assertValueCount(2);
    reqSubscriber2.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
    reqSubscriber3.assertValueCount(2);
    reqSubscriber3.assertValues(RxNettys.<HttpObject>wrap4release(request), RxNettys.<HttpObject>wrap4release(req_contents[0]));
}
Also used : HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) DisposableWrapper(org.jocean.idiom.DisposableWrapper) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) TestSubscriber(rx.observers.TestSubscriber) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Nettys4Test(org.jocean.http.util.Nettys4Test) Test(org.junit.Test)

Example 5 with DefaultHttpRequest

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

the class DefaultHttpTradeTestCase method testTradeForReadyOutboundResponseAfterResponseOnNext.

@Test
public final void testTradeForReadyOutboundResponseAfterResponseOnNext() {
    final HttpTrade trade = new DefaultHttpTrade(new EmbeddedChannel());
    assertTrue(trade.isActive());
    final SubscriberHolder<HttpObject> subsholder1 = new SubscriberHolder<>();
    final Subscription subscription1 = trade.outbound(Observable.unsafeCreate(subsholder1));
    assertNotNull(subscription1);
    final DefaultHttpRequest req1 = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    Nettys4Test.emitHttpObjects(subsholder1.getAt(0), req1);
}
Also used : HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) HttpObject(io.netty.handler.codec.http.HttpObject) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Subscription(rx.Subscription) SubscriberHolder(org.jocean.idiom.rx.SubscriberHolder) Nettys4Test(org.jocean.http.util.Nettys4Test) Test(org.junit.Test)

Aggregations

DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)111 HttpRequest (io.netty.handler.codec.http.HttpRequest)79 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)52 Test (org.junit.Test)51 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)43 HttpMethod (io.netty.handler.codec.http.HttpMethod)23 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)18 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)18 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)16 HttpContent (io.netty.handler.codec.http.HttpContent)13 HttpObject (io.netty.handler.codec.http.HttpObject)13 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)12 ByteBuf (io.netty.buffer.ByteBuf)11 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)11 Test (org.junit.jupiter.api.Test)10 Channel (io.netty.channel.Channel)9 Nettys4Test (org.jocean.http.util.Nettys4Test)9 ArrayList (java.util.ArrayList)8 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)7 DisposableWrapper (org.jocean.idiom.DisposableWrapper)6