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

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

Introduction

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

Prototype

@Deprecated
public static void setTransferEncodingChunked(HttpMessage m) 

Source Link

Usage

From source file:com.addthis.hydra.query.web.AbstractBufferingHttpBundleEncoder.java

License:Apache License

AbstractBufferingHttpBundleEncoder(int initialBufferSize, int batchBufferSize) {
    this.batchBufferSize = batchBufferSize;
    HttpHeaders.setTransferEncodingChunked(responseStart);
    sendBuffer = new StringBuilder(initialBufferSize);
}

From source file:com.barchart.http.server.PooledServerResponse.java

License:BSD License

@Override
public void setChunkedEncoding(final boolean chunked) {

    if (chunked != isChunkedEncoding()) {

        if (chunked) {

            HttpHeaders.setTransferEncodingChunked(this);
            out = new HttpChunkOutputStream(context);
            writer = new OutputStreamWriter(out, charSet);

        } else {/*from   www .j a  v a2 s. com*/

            HttpHeaders.removeTransferEncodingChunked(this);
            out = new ByteBufOutputStream(content());
            writer = new OutputStreamWriter(out, charSet);

        }

    }

}

From source file:com.barchart.netty.server.http.pipeline.PooledHttpServerResponse.java

License:BSD License

private ChannelFuture startResponse() throws IOException {

    checkFinished();//from   w ww .ja  v a 2s .  c om

    if (started)
        throw new IllegalStateException("Response already started");

    started = true;

    // Set headers
    headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.encode(cookies));
    // Default content type
    if (!headers().contains(HttpHeaders.Names.CONTENT_TYPE)) {
        setContentType("text/html; charset=utf-8");
    }

    if (HttpHeaders.isKeepAlive(request)) {
        headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    if (chunkSize > 0) {
        // Chunked, send initial response that is not a FullHttpResponse
        final DefaultHttpResponse resp = new DefaultHttpResponse(getProtocolVersion(), getStatus());
        resp.headers().add(headers());
        HttpHeaders.setTransferEncodingChunked(resp);
        return context.writeAndFlush(resp);
    } else {
        setContentLength(content().readableBytes());
        return context.writeAndFlush(this);
    }

}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Writes response metadata to the channel if not already written previously and channel is active.
 * @param responseMetadata the {@link HttpResponse} that needs to be written.
 * @param listener the {@link GenericFutureListener} that needs to be attached to the write.
 * @return {@code true} if response metadata was written to the channel in this call. {@code false} otherwise.
 *///from w  w  w  .  jav a 2  s.c om
private boolean maybeWriteResponseMetadata(HttpResponse responseMetadata,
        GenericFutureListener<ChannelFuture> listener) {
    long writeProcessingStartTime = System.currentTimeMillis();
    boolean writtenThisTime = false;
    if (responseMetadataWriteInitiated.compareAndSet(false, true) && ctx.channel().isActive()) {
        // we do some manipulation here for chunking. According to the HTTP spec, we can have either a Content-Length
        // or Transfer-Encoding:chunked, never both. So we check for Content-Length - if it is not there, we add
        // Transfer-Encoding:chunked. Note that sending HttpContent chunks data anyway - we are just explicitly specifying
        // this in the header.
        if (!HttpHeaders.isContentLengthSet(responseMetadata)) {
            // This makes sure that we don't stomp on any existing transfer-encoding.
            HttpHeaders.setTransferEncodingChunked(responseMetadata);
        } else if (HttpHeaders.getContentLength(responseMetadata) == 0
                && !(responseMetadata instanceof FullHttpResponse)) {
            // if the Content-Length is 0, we can send a FullHttpResponse since there is no content expected.
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    responseMetadata.getStatus());
            fullHttpResponse.headers().set(responseMetadata.headers());
            responseMetadata = fullHttpResponse;
        }
        logger.trace("Sending response with status {} on channel {}", responseMetadata.getStatus(),
                ctx.channel());
        finalResponseMetadata = responseMetadata;
        ChannelPromise writePromise = ctx.newPromise().addListener(listener);
        ctx.writeAndFlush(responseMetadata, writePromise);
        writtenThisTime = true;
        long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime;
        nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime);
    }
    return writtenThisTime;
}

From source file:com.github.ambry.rest.EchoMethodHandler.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    if (obj instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) obj;
        logger.trace("Handling incoming request " + request);
        requestUri = request.getUri();//from   w  ww .ja v  a  2 s. c om
        byte[] methodBytes = request.getMethod().toString().getBytes();
        if (request.headers().get(IS_CHUNKED) == null || !request.headers().get(IS_CHUNKED).equals("true")) {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(methodBytes));
            updateHeaders(response, request, methodBytes.length);
        } else {
            httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            HttpHeaders.setTransferEncodingChunked(httpResponse);
            httpContentList = new ArrayList<HttpContent>();
            ByteBuf content = Unpooled.wrappedBuffer(methodBytes);
            HttpContent httpContent = new DefaultHttpContent(content);
            httpContentList.add(httpContent);
            httpContentList.add(httpContent);
            updateHeaders(httpResponse, request, methodBytes.length);
        }
    } else if (obj instanceof LastHttpContent) {
        if (requestUri.equals(DISCONNECT_URI)) {
            ctx.disconnect();
        } else if (requestUri.equals(CLOSE_URI)) {
            ctx.close();
        } else {
            if (response != null) {
                ctx.writeAndFlush(response);
            } else if (httpResponse != null) {
                ctx.writeAndFlush(httpResponse);
                for (HttpContent httpContent : httpContentList) {
                    ctx.writeAndFlush(httpContent);
                }
                ctx.writeAndFlush(new DefaultLastHttpContent());
            }
        }
    }
}

From source file:com.github.ambry.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Writes response metadata to the channel if not already written previously and channel is active.
 * @param responseMetadata the {@link HttpResponse} that needs to be written.
 * @param listener the {@link GenericFutureListener} that needs to be attached to the write.
 * @return {@code true} if response metadata was written to the channel in this call. {@code false} otherwise.
 *//*ww w.  j  a  v  a2 s. c  om*/
private boolean maybeWriteResponseMetadata(HttpResponse responseMetadata,
        GenericFutureListener<ChannelFuture> listener) {
    long writeProcessingStartTime = System.currentTimeMillis();
    boolean writtenThisTime = false;
    if (responseMetadataWritten.compareAndSet(false, true)) {
        // we do some manipulation here for chunking. According to the HTTP spec, we can have either a Content-Length
        // or Transfer-Encoding:chunked, never both. So we check for Content-Length - if it is not there, we add
        // Transfer-Encoding:chunked. Note that sending HttpContent chunks data anyway - we are just explicitly specifying
        // this in the header.
        if (!HttpHeaders.isContentLengthSet(responseMetadata)) {
            // This makes sure that we don't stomp on any existing transfer-encoding.
            HttpHeaders.setTransferEncodingChunked(responseMetadata);
        }
        logger.trace("Sending response with status {} on channel {}", responseMetadata.getStatus(),
                ctx.channel());
        ChannelPromise writePromise = ctx.newPromise().addListener(listener);
        ctx.writeAndFlush(responseMetadata, writePromise);
        writtenThisTime = true;
        long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime;
        nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime);
    }
    return writtenThisTime;
}

From source file:com.twitter.http2.HttpStreamDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    if (msg instanceof HttpHeadersFrame) {

        HttpHeadersFrame httpHeadersFrame = (HttpHeadersFrame) msg;
        int streamId = httpHeadersFrame.getStreamId();
        StreamedHttpMessage message = messageMap.get(streamId);

        if (message == null) {
            if (httpHeadersFrame.headers().contains(":status")) {

                // If a client receives a reply with a truncated header block,
                // reply with a RST_STREAM frame with error code INTERNAL_ERROR.
                if (httpHeadersFrame.isTruncated()) {
                    HttpRstStreamFrame httpRstStreamFrame = new DefaultHttpRstStreamFrame(streamId,
                            HttpErrorCode.INTERNAL_ERROR);
                    out.add(httpRstStreamFrame);
                    return;
                }/*from  w ww.  ja  v  a2s .c  o  m*/

                try {
                    StreamedHttpResponse response = createHttpResponse(httpHeadersFrame);

                    if (httpHeadersFrame.isLast()) {
                        HttpHeaders.setContentLength(response, 0);
                        response.getContent().close();
                    } else {
                        // Response body will follow in a series of Data Frames
                        if (!HttpHeaders.isContentLengthSet(response)) {
                            HttpHeaders.setTransferEncodingChunked(response);
                        }
                        messageMap.put(streamId, response);
                    }
                    out.add(response);
                } catch (Exception e) {
                    // If a client receives a SYN_REPLY without valid getStatus and version headers
                    // the client must reply with a RST_STREAM frame indicating a PROTOCOL_ERROR
                    HttpRstStreamFrame httpRstStreamFrame = new DefaultHttpRstStreamFrame(streamId,
                            HttpErrorCode.PROTOCOL_ERROR);
                    ctx.writeAndFlush(httpRstStreamFrame);
                    out.add(httpRstStreamFrame);
                }

            } else {

                // If a client sends a request with a truncated header block, the server must
                // reply with a HTTP 431 REQUEST HEADER FIELDS TOO LARGE reply.
                if (httpHeadersFrame.isTruncated()) {
                    httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
                    httpHeadersFrame.setLast(true);
                    httpHeadersFrame.headers().set(":status",
                            HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code());
                    ctx.writeAndFlush(httpHeadersFrame);
                    return;
                }

                try {
                    message = createHttpRequest(httpHeadersFrame);

                    if (httpHeadersFrame.isLast()) {
                        message.setDecoderResult(DecoderResult.SUCCESS);
                        message.getContent().close();
                    } else {
                        // Request body will follow in a series of Data Frames
                        messageMap.put(streamId, message);
                    }

                    out.add(message);

                } catch (Exception e) {
                    // If a client sends a SYN_STREAM without all of the method, url (host and path),
                    // scheme, and version headers the server must reply with a HTTP 400 BAD REQUEST reply.
                    // Also sends HTTP 400 BAD REQUEST reply if header name/value pairs are invalid
                    httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
                    httpHeadersFrame.setLast(true);
                    httpHeadersFrame.headers().set(":status", HttpResponseStatus.BAD_REQUEST.code());
                    ctx.writeAndFlush(httpHeadersFrame);
                }
            }
        } else {
            LastHttpContent trailer = trailerMap.remove(streamId);
            if (trailer == null) {
                trailer = new DefaultLastHttpContent();
            }

            // Ignore trailers in a truncated HEADERS frame.
            if (!httpHeadersFrame.isTruncated()) {
                for (Map.Entry<String, String> e : httpHeadersFrame.headers()) {
                    trailer.trailingHeaders().add(e.getKey(), e.getValue());
                }
            }

            if (httpHeadersFrame.isLast()) {
                messageMap.remove(streamId);
                message.addContent(trailer);
            } else {
                trailerMap.put(streamId, trailer);
            }
        }

    } else if (msg instanceof HttpDataFrame) {

        HttpDataFrame httpDataFrame = (HttpDataFrame) msg;
        int streamId = httpDataFrame.getStreamId();
        StreamedHttpMessage message = messageMap.get(streamId);

        // If message is not in map discard Data Frame.
        if (message == null) {
            return;
        }

        ByteBuf content = httpDataFrame.content();
        if (content.isReadable()) {
            content.retain();
            message.addContent(new DefaultHttpContent(content));
        }

        if (httpDataFrame.isLast()) {
            messageMap.remove(streamId);
            message.addContent(LastHttpContent.EMPTY_LAST_CONTENT);
            message.setDecoderResult(DecoderResult.SUCCESS);
        }

    } else if (msg instanceof HttpRstStreamFrame) {

        HttpRstStreamFrame httpRstStreamFrame = (HttpRstStreamFrame) msg;
        int streamId = httpRstStreamFrame.getStreamId();
        StreamedHttpMessage message = messageMap.remove(streamId);

        if (message != null) {
            message.getContent().close();
            message.setDecoderResult(DecoderResult.failure(CANCELLATION_EXCEPTION));
        }

    } else {
        // HttpGoAwayFrame
        out.add(msg);
    }
}

From source file:divconq.http.multipart.HttpPostRequestEncoder.java

License:Apache 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.//from   www  .  ja  v  a2s .c o 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
 */
public 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(HttpHeaders.Names.CONTENT_TYPE);
    List<String> transferEncoding = headers.getAll(HttpHeaders.Names.TRANSFER_ENCODING);
    if (contentTypes != null) {
        headers.remove(HttpHeaders.Names.CONTENT_TYPE);
        for (String contentType : contentTypes) {
            // "multipart/form-data; boundary=--89421926422648"
            if (contentType.toLowerCase().startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA.toString())) {
                // ignore
            } else if (contentType.toLowerCase()
                    .startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED.toString())) {
                // ignore
            } else {
                headers.add(HttpHeaders.Names.CONTENT_TYPE, contentType);
            }
        }
    }
    if (isMultipart) {
        String value = HttpHeaders.Values.MULTIPART_FORM_DATA + "; " + HttpHeaders.Values.BOUNDARY + '='
                + multipartDataBoundary;
        headers.add(HttpHeaders.Names.CONTENT_TYPE, value);
    } else {
        // Not multipart
        headers.add(HttpHeaders.Names.CONTENT_TYPE, HttpHeaders.Values.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(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(realSize));
    if (realSize > HttpPostBodyUtil.chunkSize || isMultipart) {
        isChunked = true;
        if (transferEncoding != null) {
            headers.remove(HttpHeaders.Names.TRANSFER_ENCODING);
            for (String v : transferEncoding) {
                if (HttpHeaders.equalsIgnoreCase(v, HttpHeaders.Values.CHUNKED)) {
                    // ignore
                } else {
                    headers.add(HttpHeaders.Names.TRANSFER_ENCODING, v);
                }
            }
        }
        HttpHeaders.setTransferEncodingChunked(request);

        // 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:io.advantageous.conekt.http.impl.HttpClientRequestImpl.java

License:Open Source License

private void prepareHeaders() {
    HttpHeaders headers = request.headers();
    headers.remove(io.advantageous.conekt.http.HttpHeaders.TRANSFER_ENCODING);
    if (!headers.contains(io.advantageous.conekt.http.HttpHeaders.HOST)) {
        request.headers().set(io.advantageous.conekt.http.HttpHeaders.HOST, conn.hostHeader());
    }// w  ww  .  ja v a  2  s . c  o  m
    if (chunked) {
        HttpHeaders.setTransferEncodingChunked(request);
    }
    if (client.getOptions().isTryUseCompression()
            && request.headers().get(io.advantageous.conekt.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.advantageous.conekt.http.HttpHeaders.ACCEPT_ENCODING,
                io.advantageous.conekt.http.HttpHeaders.DEFLATE_GZIP);
    }
    if (!client.getOptions().isKeepAlive()
            && client.getOptions().getProtocolVersion() == io.advantageous.conekt.http.HttpVersion.HTTP_1_1) {
        request.headers().set(io.advantageous.conekt.http.HttpHeaders.CONNECTION,
                io.advantageous.conekt.http.HttpHeaders.CLOSE);
    } else if (client.getOptions().isKeepAlive()
            && client.getOptions().getProtocolVersion() == io.advantageous.conekt.http.HttpVersion.HTTP_1_0) {
        request.headers().set(io.advantageous.conekt.http.HttpHeaders.CONNECTION,
                io.advantageous.conekt.http.HttpHeaders.KEEP_ALIVE);
    }
}

From source file:io.reactivex.netty.protocol.http.client.HttpRequestHeaders.java

License:Apache License

public void setTransferEncodingChunked() {
    HttpHeaders.setTransferEncodingChunked(nettyRequest);
}