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

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

Introduction

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

Prototype

public static boolean isContentLengthSet(HttpMessage m) 

Source Link

Usage

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (!msg.decoderResult().isSuccess()) {
        failAndClose(new IOException("Failed to parse the HTTP response."), ctx);
        return;/*from  ww  w.j a  v a 2s. c o  m*/
    }
    if (!(msg instanceof HttpResponse) && !(msg instanceof HttpContent)) {
        failAndClose(
                new IllegalArgumentException("Unsupported message type: " + StringUtil.simpleClassName(msg)),
                ctx);
        return;
    }
    checkState(userPromise != null, "response before request");

    if (msg instanceof HttpResponse) {
        response = (HttpResponse) msg;
        if (!response.protocolVersion().equals(HttpVersion.HTTP_1_1)) {
            HttpException error = new HttpException(response,
                    "HTTP version 1.1 is required, was: " + response.protocolVersion(), null);
            failAndClose(error, ctx);
            return;
        }
        if (!HttpUtil.isContentLengthSet(response) && !HttpUtil.isTransferEncodingChunked(response)) {
            HttpException error = new HttpException(response,
                    "Missing 'Content-Length' or 'Transfer-Encoding: chunked' header", null);
            failAndClose(error, ctx);
            return;
        }
        downloadSucceeded = response.status().equals(HttpResponseStatus.OK);
        if (!downloadSucceeded) {
            out = new ByteArrayOutputStream();
        }
        keepAlive = HttpUtil.isKeepAlive((HttpResponse) msg);
    }

    if (msg instanceof HttpContent) {
        checkState(response != null, "content before headers");

        ByteBuf content = ((HttpContent) msg).content();
        content.readBytes(out, content.readableBytes());
        if (msg instanceof LastHttpContent) {
            if (downloadSucceeded) {
                succeedAndReset(ctx);
            } else {
                String errorMsg = response.status() + "\n";
                errorMsg += new String(((ByteArrayOutputStream) out).toByteArray(),
                        HttpUtil.getCharset(response));
                out.close();
                HttpException error = new HttpException(response, errorMsg, null);
                failAndReset(error, ctx);
            }
        }
    }
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpClientRequestHandler.java

License:Open Source License

private void parseRequestHeaders(ChannelHandlerContext ctx, Operation request, HttpRequest nettyRequest) {

    HttpHeaders headers = nettyRequest.headers();
    boolean hasHeaders = !headers.isEmpty();

    String referer = getAndRemove(headers, Operation.REFERER_HEADER);
    if (referer != null) {
        request.setReferer(referer);//from  w  ww .jav  a  2 s  .c  om
    }

    if (!hasHeaders) {
        return;
    }

    request.setKeepAlive(HttpUtil.isKeepAlive(nettyRequest));
    if (HttpUtil.isContentLengthSet(nettyRequest)) {
        request.setContentLength(HttpUtil.getContentLength(nettyRequest));
        getAndRemove(headers, Operation.CONTENT_LENGTH_HEADER);
    }

    String pragma = getAndRemove(headers, Operation.PRAGMA_HEADER);
    if (Operation.PRAGMA_DIRECTIVE_REPLICATED.equals(pragma)) {
        // replication requests will have a single PRAGMA directive. Set the right
        // options and remove the header to avoid further allocations
        request.setFromReplication(true).setTargetReplicated(true);
    } else if (pragma != null) {
        request.addRequestHeader(Operation.PRAGMA_HEADER, pragma);
    }

    if (request.hasPragmaDirective(Operation.PRAGMA_DIRECTIVE_REPLICATED)) {
        // synchronization requests will have additional directives, so check again here
        // if the request is replicated
        request.setFromReplication(true).setTargetReplicated(true);
    }

    request.setContextId(getAndRemove(headers, Operation.CONTEXT_ID_HEADER));

    request.setTransactionId(getAndRemove(headers, Operation.TRANSACTION_ID_HEADER));

    String contentType = getAndRemove(headers, Operation.CONTENT_TYPE_HEADER);
    if (contentType != null) {
        request.setContentType(contentType);
    }

    String cookie = getAndRemove(headers, Operation.COOKIE_HEADER);
    if (cookie != null) {
        request.setCookies(CookieJar.decodeCookies(cookie));
    }

    String host = getAndRemove(headers, Operation.HOST_HEADER);

    for (Entry<String, String> h : headers) {
        String key = h.getKey();
        String value = h.getValue();
        if (Operation.STREAM_ID_HEADER.equals(key)) {
            continue;
        }
        if (Operation.HTTP2_SCHEME_HEADER.equals(key)) {
            continue;
        }

        request.addRequestHeader(key, value);
    }

    if (host != null) {
        request.addRequestHeader(Operation.HOST_HEADER, host);
    }

    if (request.getRequestHeader(Operation.RESPONSE_CALLBACK_STATUS_HEADER) != null) {
        request.setReferer(request.getUri());
    }

    if (!request.hasReferer() && request.isFromReplication()) {
        // we assume referrer is the same service, but from the remote node. Do not
        // bother with rewriting the URI with the remote host, at avoid allocations
        request.setReferer(request.getUri());
    }

    if (this.sslHandler == null) {
        return;
    }
    try {
        if (this.sslHandler.engine().getWantClientAuth() || this.sslHandler.engine().getNeedClientAuth()) {
            SSLSession session = this.sslHandler.engine().getSession();
            request.setPeerCertificates(session.getPeerPrincipal(), session.getPeerCertificateChain());
        }
    } catch (Exception e) {
        this.host.log(Level.WARNING, "Failed to get peer principal " + Utils.toString(e));
    }
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpServerResponseHandler.java

License:Open Source License

private void parseResponseHeaders(Operation request, HttpResponse nettyResponse) {
    HttpHeaders headers = nettyResponse.headers();
    if (headers.isEmpty()) {
        return;//  w  w  w  . j  a v  a 2 s.c om
    }

    request.setKeepAlive(HttpUtil.isKeepAlive(nettyResponse));
    if (HttpUtil.isContentLengthSet(nettyResponse)) {
        request.setContentLength(HttpUtil.getContentLength(nettyResponse));
        headers.remove(HttpHeaderNames.CONTENT_LENGTH);
    }

    String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
    headers.remove(HttpHeaderNames.CONTENT_TYPE);
    if (contentType != null) {
        request.setContentType(contentType);
    }

    for (Entry<String, String> h : headers) {
        String key = h.getKey();
        String value = h.getValue();
        if (Operation.STREAM_ID_HEADER.equals(key)) {
            // Prevent allocation of response headers in Operation and hide the stream ID
            // header, since it is manipulated by the HTTP layer, not services
            continue;
        }
        request.addResponseHeader(key, value);
    }
}

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

License:Open Source License

@Override
public NettyOutbound send(Publisher<? extends ByteBuf> source) {
    if (method() == HttpMethod.GET || method() == HttpMethod.HEAD) {
        ByteBufAllocator alloc = channel().alloc();
        Flux.from(source).doOnNext(ByteBuf::retain).collect(alloc::buffer, ByteBuf::writeBytes).then(agg -> {
            if (!hasSentHeaders() && !HttpUtil.isTransferEncodingChunked(outboundHttpMessage())
                    && !HttpUtil.isContentLengthSet(outboundHttpMessage())) {
                outboundHttpMessage().headers().setInt(HttpHeaderNames.CONTENT_LENGTH, agg.readableBytes());
            }//from  w  ww  .  j  av a2s . c  om
            return sendHeaders().send(Mono.just(agg)).then();
        });
    }
    return super.send(source);
}

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

License:Open Source License

public NettyOutbound sendHeaders() {
    if (markHeadersAsSent()) {
        if (HttpUtil.isContentLengthSet(outboundHttpMessage())) {
            outboundHttpMessage().headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
        } else if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage())) {
            HttpUtil.setContentLength(outboundHttpMessage(), 0L);
        }//from www  .j  a va 2  s. c  o  m
        HttpMessage message;
        if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage())
                && HttpUtil.getContentLength(outboundHttpMessage(), 0L) == 0L) {
            message = newFullEmptyBodyMessage();
        } else {
            message = outboundHttpMessage();
        }
        return then(FutureMono.deferFuture(() -> channel().writeAndFlush(message)));
    } else {
        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   ww  w.ja  v a2s .  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);
    }// w ww  . j a v a  2  s .co  m
    if (!HttpUtil.isContentLengthSet(outboundHttpMessage())
            && !outboundHttpMessage().headers().contains(HttpHeaderNames.TRANSFER_ENCODING)) {
        HttpUtil.setTransferEncodingChunked(outboundHttpMessage(), true);
    }
    return sendHeaders().then(super.sendObject(source));
}

From source file:reactor.ipc.netty.http.server.HttpServerOperations.java

License:Open Source License

@Override
protected void onOutboundError(Throwable err) {
    discreteRemoteClose(err);//from   w w w.  ja v  a  2s  . com

    if (markHeadersAsSent()) {
        log.error("Error starting response. Replying error status", err);

        HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.INTERNAL_SERVER_ERROR);
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        channel().writeAndFlush(response).addListener(r -> onHandlerTerminate());
        onOutboundReadMore();
        return;
    }

    if (HttpUtil.isContentLengthSet(nettyResponse)) {
        channel().writeAndFlush(EMPTY_BUFFER).addListener(r -> onHandlerTerminate());
        onOutboundReadMore();
        return;
    }
    channel().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(r -> onHandlerTerminate());
    if (isKeepAlive()) {
        onOutboundReadMore();
    }
}