Example usage for io.netty.handler.codec.http HttpUtil setTransferEncodingChunked

List of usage examples for io.netty.handler.codec.http HttpUtil setTransferEncodingChunked

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpUtil setTransferEncodingChunked.

Prototype

public static void setTransferEncodingChunked(HttpMessage m, boolean chunked) 

Source Link

Document

Set the HttpHeaderNames#TRANSFER_ENCODING to either include HttpHeaderValues#CHUNKED if chunked is true , or remove HttpHeaderValues#CHUNKED if chunked is false .

Usage

From source file:com.linkedin.r2.transport.http.client.RAPResponseDecoder.java

License:Apache License

@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/*from  w w  w  . ja v a 2 s . c  o m*/
                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;
            if (_shouldCloseConnection) {
                ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_DESTROY_SIGNAL);
            } else {
                ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_RELEASE_SIGNAL);
            }
        }
    } else {
        // something must be wrong, but let's proceed so that
        // handler after us has a chance to process it.
        ctx.fireChannelRead(msg);
    }
}

From source file:io.jsync.http.impl.DefaultHttpClientRequest.java

License:Open Source License

private void prepareHeaders() {
    HttpHeaders headers = request.headers();
    headers.remove(io.jsync.http.HttpHeaders.TRANSFER_ENCODING);
    if (!raw) {// www  . j  a va2s . c o  m
        if (!headers.contains(io.jsync.http.HttpHeaders.HOST)) {
            request.headers().set(io.jsync.http.HttpHeaders.HOST, conn.hostHeader);
        }
        if (chunked) {
            HttpUtil.setTransferEncodingChunked(request, true);
        }
    }
    if (client.getTryUseCompression()
            && request.headers().get(io.jsync.http.HttpHeaders.ACCEPT_ENCODING) == null) {
        // if compression should be used but nothing is specified by the user support deflate and gzip.
        request.headers().set(io.jsync.http.HttpHeaders.ACCEPT_ENCODING,
                io.jsync.http.HttpHeaders.DEFLATE_GZIP);

    }
}

From source file:org.glassfish.jersey.netty.connector.NettyConnector.java

License:Open Source License

@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 {//from   w  w  w  .ja  va 2s.c  o  m
        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;
}

From source file:org.glassfish.jersey.netty.httpserver.NettyResponseWriter.java

License:Open Source License

@Override
public synchronized OutputStream writeResponseStatusAndHeaders(long contentLength,
        ContainerResponse responseContext) throws ContainerException {

    if (responseWritten) {
        LOGGER.log(Level.FINE, "Response already written.");
        return null;
    }// w  ww .j  a v a 2  s .com

    responseWritten = true;

    String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
    int statusCode = responseContext.getStatus();

    HttpResponseStatus status = reasonPhrase == null ? HttpResponseStatus.valueOf(statusCode)
            : new HttpResponseStatus(statusCode, reasonPhrase);

    DefaultHttpResponse response;
    if (contentLength == 0) {
        response = new DefaultFullHttpResponse(req.protocolVersion(), status);
    } else {
        response = new DefaultHttpResponse(req.protocolVersion(), status);
    }

    for (final Map.Entry<String, List<String>> e : responseContext.getStringHeaders().entrySet()) {
        response.headers().add(e.getKey(), e.getValue());
    }

    if (contentLength == -1) {
        HttpUtil.setTransferEncodingChunked(response, true);
    } else {
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
    }

    if (HttpUtil.isKeepAlive(req)) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    ctx.writeAndFlush(response);

    if (req.method() != HttpMethod.HEAD && (contentLength > 0 || contentLength == -1)) {

        JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ctx.channel());

        if (HttpUtil.isTransferEncodingChunked(response)) {
            ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
        } else {
            ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
        }
        return jerseyChunkedInput;

    } else {
        ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        return null;
    }
}

From source file:org.restnext.server.ServerHandler.java

License:Apache License

private void write(ChannelHandlerContext ctx, Response response, boolean keepAlive) {
    HttpVersion version = fromVersion(response.getVersion());
    HttpResponseStatus status = fromStatus(response.getStatus());
    ByteBuf content = response.hasContent() ? Unpooled.wrappedBuffer(response.getContent())
            : Unpooled.EMPTY_BUFFER;//from w  w  w.  j av a  2 s  .com

    boolean chunked = response.isChunked();

    // create netty response
    HttpResponse resp;
    HttpChunkedInput chunkedResp = chunked
            ? new HttpChunkedInput(new ChunkedStream(new ByteBufInputStream(content), response.getChunkSize()))
            : null;

    if (chunked) {
        resp = new DefaultHttpResponse(version, status);
        HttpUtil.setTransferEncodingChunked(resp, true);
        createOutboutHeaders(resp, response, keepAlive);
        // Write the initial line and the header.
        ctx.write(resp);
    } else {
        resp = new DefaultFullHttpResponse(version, status, content);
        createOutboutHeaders(resp, response, keepAlive);
    }

    if (keepAlive) {
        if (chunked) {
            ctx.write(chunkedResp);
        } else {
            HttpUtil.setContentLength(resp, content.readableBytes());
            ctx.write(resp);
        }
    } else {
        ChannelFuture channelFuture;
        if (chunked) {
            channelFuture = ctx.writeAndFlush(chunkedResp);
        } else {
            channelFuture = ctx.writeAndFlush(resp);
        }
        // Close the connection after the write operation is done if necessary.
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:reactor.ipc.netty.http.client.HttpClientFormEncoder.java

License:Open Source License

/**
 * Finalize the request by preparing the Header in the request and returns the request
 * ready to be sent.<br> Once finalized, no data must be added.<br> If the request
 * does not need chunk (isChunked() == false), this request is the only object to send
 * to the remote server.//  w w w .  ja v a2s.co m
 *
 * @return the request object (chunked or not according to size of body)
 *
 * @throws ErrorDataEncoderException if the encoding is in error or if the finalize
 *                                   were already done
 */
HttpRequest finalizeRequest() throws ErrorDataEncoderException {
    // Finalize the multipartHttpDatas
    if (!headerFinalized) {
        if (isMultipart) {
            InternalAttribute internal = new InternalAttribute(charset);
            if (duringMixedMode) {
                internal.addValue("\r\n--" + multipartMixedBoundary + "--");
            }
            internal.addValue("\r\n--" + multipartDataBoundary + "--\r\n");
            multipartHttpDatas.add(internal);
            multipartMixedBoundary = null;
            currentFileUpload = null;
            duringMixedMode = false;
            globalBodySize += internal.size();
        }
        headerFinalized = true;
    } else {
        throw new ErrorDataEncoderException("Header already encoded");
    }

    HttpHeaders headers = request.headers();
    List<String> contentTypes = headers.getAll(HttpHeaderNames.CONTENT_TYPE);
    List<String> transferEncoding = headers.getAll(HttpHeaderNames.TRANSFER_ENCODING);
    if (contentTypes != null) {
        headers.remove(HttpHeaderNames.CONTENT_TYPE);
        for (String contentType : contentTypes) {
            // "multipart/form-data; boundary=--89421926422648"
            String lowercased = contentType.toLowerCase();
            if (lowercased.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString())
                    || lowercased.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString())) {
                // ignore
            } else {
                headers.add(HttpHeaderNames.CONTENT_TYPE, contentType);
            }
        }
    }
    if (isMultipart) {
        String value = HttpHeaderValues.MULTIPART_FORM_DATA + "; " + HttpHeaderValues.BOUNDARY + '='
                + multipartDataBoundary;
        headers.add(HttpHeaderNames.CONTENT_TYPE, value);
    } else {
        // Not multipart
        headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    }
    // Now consider size for chunk or not
    long realSize = globalBodySize;
    if (isMultipart) {
        iterator = multipartHttpDatas.listIterator();
    } else {
        realSize -= 1; // last '&' removed
        iterator = multipartHttpDatas.listIterator();
    }
    headers.set(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(realSize));
    if (realSize > chunkSize || isMultipart) {
        isChunked = true;
        if (transferEncoding != null) {
            headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
            for (CharSequence v : transferEncoding) {
                if (HttpHeaderValues.CHUNKED.contentEqualsIgnoreCase(v)) {
                    // ignore
                } else {
                    headers.add(HttpHeaderNames.TRANSFER_ENCODING, v);
                }
            }
        }
        HttpUtil.setTransferEncodingChunked(request, true);

        // wrap to hide the possible content
        return new WrappedHttpRequest(request);
    } else {
        // get the only one body and set it to the request
        HttpContent chunk = nextChunk();
        if (request instanceof FullHttpRequest) {
            FullHttpRequest fullRequest = (FullHttpRequest) request;
            ByteBuf chunkContent = chunk.content();
            if (fullRequest.content() != chunkContent) {
                fullRequest.content().clear().writeBytes(chunkContent);
                chunkContent.release();
            }
            return fullRequest;
        } else {
            return new WrappedFullHttpRequest(request, chunk);
        }
    }
}

From source file:reactor.ipc.netty.http.client.HttpClientOperations.java

License:Open Source License

@Override
public HttpClientRequest chunkedTransfer(boolean chunked) {
    if (!hasSentHeaders()) {
        HttpUtil.setTransferEncodingChunked(nettyRequest, chunked);
    } else {//from   www. ja v  a2  s .c  om
        throw new IllegalStateException("Status and headers already sent");
    }
    return this;
}

From source file:reactor.ipc.netty.http.client.HttpClientOperations.java

License:Open Source License

@Override
public final HttpClientRequest disableChunkedTransfer() {
    HttpUtil.setTransferEncodingChunked(nettyRequest, false);
    return this;
}

From source file:reactor.ipc.netty.http.HttpOperations.java

License:Open Source License

@Override
public final NettyOutbound sendFile(Path file, long position, long count) {
    Objects.requireNonNull(file);

    if (hasSentHeaders()) {
        return super.sendFile(file, position, count);
    }//from   www.j a v a 2  s. c  o m

    if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage())
            && !HttpUtil.isContentLengthSet(outboundHttpMessage()) && count < Integer.MAX_VALUE) {
        outboundHttpMessage().headers().setInt(HttpHeaderNames.CONTENT_LENGTH, (int) count);
    } else if (!HttpUtil.isContentLengthSet(outboundHttpMessage())) {
        outboundHttpMessage().headers().remove(HttpHeaderNames.CONTENT_LENGTH)
                .remove(HttpHeaderNames.TRANSFER_ENCODING);
        HttpUtil.setTransferEncodingChunked(outboundHttpMessage(), true);
    }

    return sendHeaders().then(super.sendFile(file, position, count));
}

From source file:reactor.ipc.netty.http.HttpOperations.java

License:Open Source License

@Override
public final NettyOutbound sendObject(final Publisher<?> source) {
    if (hasSentHeaders()) {
        return super.sendObject(source);
    }//from w  w  w . j  a  va  2s. c  om
    if (!HttpUtil.isContentLengthSet(outboundHttpMessage())
            && !outboundHttpMessage().headers().contains(HttpHeaderNames.TRANSFER_ENCODING)) {
        HttpUtil.setTransferEncodingChunked(outboundHttpMessage(), true);
    }
    return sendHeaders().then(super.sendObject(source));
}