Search in sources :

Example 81 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project hadoop by apache.

the class SimpleHttpProxyHandler method channelRead0.

@Override
public void channelRead0(final ChannelHandlerContext ctx, final HttpRequest req) {
    uri = req.getUri();
    final Channel client = ctx.channel();
    Bootstrap proxiedServer = new Bootstrap().group(client.eventLoop()).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
        }
    });
    ChannelFuture f = proxiedServer.connect(host);
    proxiedChannel = f.channel();
    f.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                ctx.channel().pipeline().remove(HttpResponseEncoder.class);
                HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1, req.getMethod(), req.getUri());
                newReq.headers().add(req.headers());
                newReq.headers().set(CONNECTION, Values.CLOSE);
                future.channel().writeAndFlush(newReq);
            } else {
                DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR);
                resp.headers().set(CONNECTION, Values.CLOSE);
                LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
                ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
                client.close();
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) Bootstrap(io.netty.bootstrap.Bootstrap) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder)

Example 82 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project spring-framework by spring-projects.

the class Netty4ClientHttpRequest method createFullHttpRequest.

private FullHttpRequest createFullHttpRequest(HttpHeaders headers) {
    io.netty.handler.codec.http.HttpMethod nettyMethod = io.netty.handler.codec.http.HttpMethod.valueOf(this.method.name());
    String authority = this.uri.getRawAuthority();
    String path = this.uri.toString().substring(this.uri.toString().indexOf(authority) + authority.length());
    FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, nettyMethod, path, this.body.buffer());
    nettyRequest.headers().set(HttpHeaders.HOST, this.uri.getHost());
    nettyRequest.headers().set(HttpHeaders.CONNECTION, "close");
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        nettyRequest.headers().add(entry.getKey(), entry.getValue());
    }
    if (!nettyRequest.headers().contains(HttpHeaders.CONTENT_LENGTH) && this.body.buffer().readableBytes() > 0) {
        nettyRequest.headers().set(HttpHeaders.CONTENT_LENGTH, this.body.buffer().readableBytes());
    }
    return nettyRequest;
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) List(java.util.List) Map(java.util.Map)

Example 83 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project undertow by undertow-io.

the class HTTP2ViaUpgradeTestCase method testHttp2WithNettyClient.

@Test
public void testHttp2WithNettyClient() throws Exception {
    message = "Hello World";
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(Integer.MAX_VALUE);
    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        final int port = DefaultServer.getHostPort("default") + 1;
        final String host = DefaultServer.getHostAddress("default");
        b.remoteAddress(host, port);
        b.handler(initializer);
        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);
        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        URI hostName = URI.create("http://" + host + ':' + port);
        System.err.println("Sending request(s)...");
        // Create a simple GET request.
        final ChannelPromise promise = channel.newPromise();
        responseHandler.put(streamId, promise);
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, hostName.toString());
        request.headers().add(HttpHeaderNames.HOST, hostName);
        request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
        request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
        channel.writeAndFlush(request);
        streamId += 2;
        promise.await(10, TimeUnit.SECONDS);
        Assert.assertEquals(message, messages.poll());
        System.out.println("Finished HTTP/2 request(s)");
        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelPromise(io.netty.channel.ChannelPromise) HttpString(io.undertow.util.HttpString) URI(java.net.URI) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 84 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project riposte by Nike-Inc.

the class VerifyTimeoutsAndProxyConnectionPoolingWorksComponentTest method verify_incomplete_call_is_timed_out.

@Test
public void verify_incomplete_call_is_timed_out() throws InterruptedException, TimeoutException, ExecutionException, IOException {
    Bootstrap bootstrap = new Bootstrap();
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {
        CompletableFuture<Pair<String, String>> responseFromServer = new CompletableFuture<>();
        // Create a raw netty HTTP client so we can fiddle with headers and intentionally create a bad request
        //      that should trigger the bad call timeout.
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec());
                p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                p.addLast(new SimpleChannelInboundHandler<HttpObject>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                        if (msg instanceof FullHttpResponse) {
                            // Store the server response for asserting on later.
                            FullHttpResponse responseMsg = (FullHttpResponse) msg;
                            responseFromServer.complete(Pair.of(responseMsg.content().toString(CharsetUtil.UTF_8), responseMsg.headers().get(HttpHeaders.Names.CONNECTION)));
                        } else {
                            // Should never happen.
                            throw new RuntimeException("Received unexpected message type: " + msg.getClass());
                        }
                    }
                });
            }
        });
        // Connect to the server.
        Channel ch = bootstrap.connect("localhost", downstreamServerConfig.endpointsPort()).sync().channel();
        // Create a bad HTTP request. This one will be bad because it has a non-zero content-length header,
        //      but we're sending no payload. The server should (correctly) sit and wait for payload bytes to
        //      arrive until it hits the timeout, at which point it should return the correct error response.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, LongDelayTestEndpoint.MATCHING_PATH);
        request.headers().set(HttpHeaders.Names.HOST, "localhost");
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, "100");
        long beforeCallTimeNanos = System.nanoTime();
        // Send the bad request.
        ch.writeAndFlush(request);
        // Wait for the response to be received and the connection to be closed.
        try {
            ch.closeFuture().get(incompleteCallTimeoutMillis * 10, TimeUnit.MILLISECONDS);
            responseFromServer.get(incompleteCallTimeoutMillis * 10, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ex) {
            fail("The call took much longer than expected without receiving a response. " + "Cancelling this test - it's not working properly", ex);
        }
        // If we reach here then the call should be complete.
        long totalCallTimeMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beforeCallTimeNanos);
        // Verify that we got back the correct error response.
        //      It should be a MALFORMED_REQUEST with extra metadata explaining that the call was bad.
        Pair<String, String> responseInfo = responseFromServer.get();
        DefaultErrorContractDTO errorContract = objectMapper.readValue(responseInfo.getLeft(), DefaultErrorContractDTO.class);
        assertThat(errorContract).isNotNull();
        assertThat(errorContract.errors.size()).isEqualTo(1);
        DefaultErrorDTO error = errorContract.errors.get(0);
        ApiError expectedApiError = SampleCoreApiError.MALFORMED_REQUEST;
        Map<String, Object> expectedMetadata = MapBuilder.builder("cause", (Object) "Unfinished/invalid HTTP request").build();
        assertThat(error.code).isEqualTo(expectedApiError.getErrorCode());
        assertThat(error.message).isEqualTo(expectedApiError.getMessage());
        assertThat(error.metadata).isEqualTo(expectedMetadata);
        // The server should have closed the connection even though we asked for keep-alive.
        assertThat(responseInfo.getRight()).isEqualTo(HttpHeaders.Values.CLOSE);
        // Total call time should be pretty close to incompleteCallTimeoutMillis give or take a few
        //      milliseconds, but due to the inability to account for slow machines running the unit tests,
        //      a server that isn't warmed up, etc, we can't put a ceiling on the wiggle room we'd need, so
        //      we'll just verify it took at least the minimum necessary amount of time.
        assertThat(totalCallTimeMillis).isGreaterThanOrEqualTo(incompleteCallTimeoutMillis);
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) CompletableFuture(java.util.concurrent.CompletableFuture) HttpObject(io.netty.handler.codec.http.HttpObject) Bootstrap(io.netty.bootstrap.Bootstrap) DefaultErrorDTO(com.nike.backstopper.model.DefaultErrorDTO) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Pair(com.nike.internal.util.Pair) TimeoutException(java.util.concurrent.TimeoutException) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultErrorContractDTO(com.nike.backstopper.model.DefaultErrorContractDTO) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) HttpObject(io.netty.handler.codec.http.HttpObject) ApiError(com.nike.backstopper.apierror.ApiError) SampleCoreApiError(com.nike.backstopper.apierror.sample.SampleCoreApiError) Test(org.junit.Test)

Example 85 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project riposte by Nike-Inc.

the class VerifyRequestSizeValidationComponentTest method should_return_expected_response_when_chunked_request_not_exceeding_global_request_size.

@Test
public void should_return_expected_response_when_chunked_request_not_exceeding_global_request_size() throws Exception {
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, BasicEndpoint.MATCHING_PATH, Unpooled.wrappedBuffer(generatePayloadOfSizeInBytes(GLOBAL_MAX_REQUEST_SIZE).getBytes(UTF_8)));
    request.headers().set(HttpHeaders.Names.HOST, "127.0.0.1");
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, CHUNKED);
    // when
    Pair<Integer, String> serverResponse = executeRequest(request, serverConfig.endpointsPort(), incompleteCallTimeoutMillis);
    // then
    assertThat(serverResponse.getLeft()).isEqualTo(HttpResponseStatus.OK.code());
    assertThat(serverResponse.getRight()).isEqualTo(BasicEndpoint.RESPONSE_PAYLOAD);
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) Test(org.junit.Test)

Aggregations

DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)92 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)53 Test (org.junit.Test)53 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)31 AsciiString (io.netty.util.AsciiString)28 ByteBuf (io.netty.buffer.ByteBuf)27 HttpRequest (io.netty.handler.codec.http.HttpRequest)22 ChannelPromise (io.netty.channel.ChannelPromise)15 FullHttpMessage (io.netty.handler.codec.http.FullHttpMessage)11 Http2CodecUtil.getEmbeddedHttp2Exception (io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception)11 Http2Runnable (io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable)11 URI (java.net.URI)9 Channel (io.netty.channel.Channel)8 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)8 Bootstrap (io.netty.bootstrap.Bootstrap)7 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)7 File (java.io.File)7 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)6 Map (java.util.Map)6 NullDispatcher (org.elasticsearch.http.NullDispatcher)6