Search in sources :

Example 1 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project jersey by jersey.

the class JerseyClientHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        final HttpResponse response = (HttpResponse) msg;
        final ClientResponse jerseyResponse = new ClientResponse(new Response.StatusType() {

            @Override
            public int getStatusCode() {
                return response.status().code();
            }

            @Override
            public Response.Status.Family getFamily() {
                return Response.Status.Family.familyOf(response.status().code());
            }

            @Override
            public String getReasonPhrase() {
                return response.status().reasonPhrase();
            }
        }, jerseyRequest);
        for (Map.Entry<String, String> entry : response.headers().entries()) {
            jerseyResponse.getHeaders().add(entry.getKey(), entry.getValue());
        }
        // request entity handling.
        if ((response.headers().contains(HttpHeaderNames.CONTENT_LENGTH) && HttpUtil.getContentLength(response) > 0) || HttpUtil.isTransferEncodingChunked(response)) {
            ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    isList.add(NettyInputStream.END_OF_INPUT_ERROR);
                }
            });
            jerseyResponse.setEntityStream(new NettyInputStream(isList));
        } else {
            jerseyResponse.setEntityStream(new InputStream() {

                @Override
                public int read() throws IOException {
                    return -1;
                }
            });
        }
        if (asyncConnectorCallback != null) {
            connector.executorService.execute(new Runnable() {

                @Override
                public void run() {
                    asyncConnectorCallback.response(jerseyResponse);
                    future.complete(jerseyResponse);
                }
            });
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            // copy bytes - when netty reads last chunk, it automatically closes the channel, which invalidates all
            // relates ByteBuffs.
            byte[] bytes = new byte[content.readableBytes()];
            content.getBytes(content.readerIndex(), bytes);
            isList.add(new ByteArrayInputStream(bytes));
        }
        if (msg instanceof LastHttpContent) {
            isList.add(NettyInputStream.END_OF_INPUT);
        }
    }
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) NettyInputStream(org.glassfish.jersey.netty.connector.internal.NettyInputStream) InputStream(java.io.InputStream) HttpResponse(io.netty.handler.codec.http.HttpResponse) IOException(java.io.IOException) NettyInputStream(org.glassfish.jersey.netty.connector.internal.NettyInputStream) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) IOException(java.io.IOException) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) CompletableFuture(java.util.concurrent.CompletableFuture) Future(io.netty.util.concurrent.Future) Map(java.util.Map) HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent)

Example 2 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project jersey by jersey.

the class JerseyServerHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;
        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        }
        // clearing the content - possible leftover from previous request processing.
        isList.clear();
        final ContainerRequest requestContext = createContainerRequest(ctx, req);
        requestContext.setWriter(new NettyResponseWriter(ctx, req, container));
        // must be like this, since there is a blocking read from Jersey
        container.getExecutorService().execute(new Runnable() {

            @Override
            public void run() {
                container.getApplicationHandler().handle(requestContext);
            }
        });
    }
    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            isList.add(new ByteBufInputStream(content));
        }
        if (msg instanceof LastHttpContent) {
            isList.add(NettyInputStream.END_OF_INPUT);
        }
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 3 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project rest.li by linkedin.

the class RAPResponseDecoder method channelRead0.

@Override
protected void channelRead0(final ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpResponse) {
        HttpResponse m = (HttpResponse) msg;
        _shouldCloseConnection = !HttpUtil.isKeepAlive(m);
        if (HttpUtil.is100ContinueExpected(m)) {
            ctx.writeAndFlush(CONTINUE).addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }
        if (!m.decoderResult().isSuccess()) {
            ctx.fireExceptionCaught(m.decoderResult().cause());
            return;
        }
        // remove chunked encoding.
        if (HttpUtil.isTransferEncodingChunked(m)) {
            HttpUtil.setTransferEncodingChunked(m, false);
        }
        Timeout<None> timeout = ctx.channel().attr(TIMEOUT_ATTR_KEY).getAndRemove();
        if (timeout == null) {
            LOG.debug("dropped a response after channel inactive or exception had happened.");
            return;
        }
        final TimeoutBufferedWriter writer = new TimeoutBufferedWriter(ctx, _maxContentLength, BUFFER_HIGH_WATER_MARK, BUFFER_LOW_WATER_MARK, timeout);
        EntityStream entityStream = EntityStreams.newEntityStream(writer);
        _chunkedMessageWriter = writer;
        StreamResponseBuilder builder = new StreamResponseBuilder();
        builder.setStatus(m.status().code());
        for (Map.Entry<String, String> e : m.headers()) {
            String key = e.getKey();
            String value = e.getValue();
            if (key.equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) {
                builder.addCookie(value);
            } else {
                builder.unsafeAddHeaderValue(key, value);
            }
        }
        ctx.fireChannelRead(builder.build(entityStream));
    } else if (msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        TimeoutBufferedWriter currentWriter = _chunkedMessageWriter;
        // Sanity check
        if (currentWriter == null) {
            throw new IllegalStateException("received " + HttpContent.class.getSimpleName() + " without " + HttpResponse.class.getSimpleName());
        }
        if (!chunk.decoderResult().isSuccess()) {
            this.exceptionCaught(ctx, chunk.decoderResult().cause());
        }
        currentWriter.processHttpChunk(chunk);
        if (chunk instanceof LastHttpContent) {
            _chunkedMessageWriter = null;
        }
    } else {
        // something must be wrong, but let's proceed so that
        // handler after us has a chance to process it.
        ctx.fireChannelRead(msg);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteString(com.linkedin.data.ByteString) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelFutureListener(io.netty.channel.ChannelFutureListener) TimeoutException(java.util.concurrent.TimeoutException) ClosedChannelException(java.nio.channels.ClosedChannelException) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) IOException(java.io.IOException) EntityStream(com.linkedin.r2.message.stream.entitystream.EntityStream) None(com.linkedin.common.util.None) Map(java.util.Map) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 4 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project rest.li by linkedin.

the class TestChannelPoolStreamHandler method testConnectionClose.

@Test(dataProvider = "connectionClose")
public void testConnectionClose(String headerName, List<String> headerValue) {
    EmbeddedChannel ch = getChannel();
    FakePool pool = new FakePool();
    ch.attr(ChannelPoolStreamHandler.CHANNEL_POOL_ATTR_KEY).set(pool);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
    HttpContent lastChunk = new DefaultLastHttpContent();
    response.headers().set(headerName, headerValue);
    ch.writeInbound(response);
    ch.writeInbound(lastChunk);
    Assert.assertTrue(pool.isDisposeCalled());
    Assert.assertFalse(pool.isPutCalled());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.testng.annotations.Test)

Example 5 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project rest.li by linkedin.

the class TestChannelPoolStreamHandler method testConnectionKeepAlive.

@Test(dataProvider = "connectionKeepAlive")
public void testConnectionKeepAlive(String headerName, List<String> headerValue) {
    EmbeddedChannel ch = getChannel();
    FakePool pool = new FakePool();
    ch.attr(ChannelPoolStreamHandler.CHANNEL_POOL_ATTR_KEY).set(pool);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
    HttpContent lastChunk = new DefaultLastHttpContent();
    response.headers().set(headerName, headerValue);
    ch.writeInbound(response);
    ch.writeInbound(lastChunk);
    Assert.assertFalse(pool.isDisposeCalled());
    Assert.assertTrue(pool.isPutCalled());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.testng.annotations.Test)

Aggregations

HttpContent (io.netty.handler.codec.http.HttpContent)158 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)122 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)62 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)59 Test (org.junit.Test)59 ByteBuf (io.netty.buffer.ByteBuf)40 HttpResponse (io.netty.handler.codec.http.HttpResponse)37 HttpRequest (io.netty.handler.codec.http.HttpRequest)35 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)34 ArrayList (java.util.ArrayList)30 HttpObject (io.netty.handler.codec.http.HttpObject)28 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)24 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)20 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)17 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)17 Channel (io.netty.channel.Channel)16 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)15 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)14 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)13 IOException (java.io.IOException)13