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

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

Introduction

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

Prototype

@Deprecated
public static long getContentLength(HttpMessage message, long defaultValue) 

Source Link

Usage

From source file:cn.wantedonline.puppy.httpserver.component.HttpObjectAggregator.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    AggregatedFullHttpMessage currentMessage = this.currentMessage;

    if (msg instanceof HttpMessage) {
        tooLongFrameFound = false;// w  ww .j av  a 2  s  .  c o  m
        assert currentMessage == null;

        HttpMessage m = (HttpMessage) msg;

        // Handle the 'Expect: 100-continue' header if necessary.
        if (is100ContinueExpected(m)) {
            if (HttpHeaders.getContentLength(m, 0) > maxContentLength) {
                tooLongFrameFound = true;
                final ChannelFuture future = ctx.writeAndFlush(EXPECTATION_FAILED.duplicate().retain());
                future.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            ctx.fireExceptionCaught(future.cause());
                        }
                    }
                });
                if (closeOnExpectationFailed) {
                    future.addListener(ChannelFutureListener.CLOSE);
                }
                ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
                return;
            }
            ctx.writeAndFlush(CONTINUE.duplicate().retain()).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }

        if (!m.getDecoderResult().isSuccess()) {
            removeTransferEncodingChunked(m);
            out.add(toFullMessage(m));
            this.currentMessage = null;
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest header = (HttpRequest) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpRequest(header,
                    ctx.alloc().compositeBuffer(maxCumulationBufferComponents), null);
        } else if (msg instanceof HttpResponse) {
            HttpResponse header = (HttpResponse) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpResponse(header,
                    Unpooled.compositeBuffer(maxCumulationBufferComponents), null);
        } else {
            throw new Error();
        }

        // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
        removeTransferEncodingChunked(currentMessage);
    } else if (msg instanceof HttpContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastHttpContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        HttpContent chunk = (HttpContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastHttpContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) chunk;
                currentMessage.setTrailingHeaders(trailer.trailingHeaders());
            } else {
                currentMessage.setTrailingHeaders(new DefaultHttpHeaders());
            }

            // Set the 'Content-Length' header. If one isn't already set.
            // This is important as HEAD responses will use a 'Content-Length' header which
            // does not match the actual body, but the number of bytes that would be
            // transmitted if a GET would have been used.
            //
            // See rfc2616 14.13 Content-Length
            if (!isContentLengthSet(currentMessage)) {
                currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(content.readableBytes()));
            }
            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

From source file:com.aerofs.baseline.http.HttpRequestHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (ctx.channel().closeFuture().isDone()) {
        LOGGER.warn("{}: drop http message - channel closed", Channels.getHexText(ctx));
        return;/*from w  w w .  java2s  . c  om*/
    }

    if (!(msg instanceof HttpObject)) {
        super.channelRead(ctx, msg);
    }

    //
    // netty http decoding:
    //
    // 1. normal case: HttpRequest (headers), HttpContent (0+), LastHttpContent (trailing headers)
    //    NOTE: with chunked transfer encoding or content-length non-zero you get an arbitrary number of HttpContent objects
    // 2. error case (failed to decode an HTTP message): HttpRequest with NETTY_HTTP_DECODING_FAILED_URI
    //

    if (msg instanceof HttpRequest) {
        // this is the first object netty generates:
        // an HttpRequest containing a number of headers

        // we should not have another request pending
        Preconditions.checkState(pendingRequest == null, "previous request pending:%s", pendingRequest);

        // cast it
        HttpRequest nettyRequest = (HttpRequest) msg;

        // get the request id
        String requestId = nettyRequest.headers().get(Headers.REQUEST_TRACING_HEADER);
        Preconditions.checkState(requestId != null, "http request on %s has no request id",
                Channels.getHexText(ctx));

        // check if http decoding failed and if so, abort early
        if (nettyRequest.uri().equals(NETTY_HTTP_DECODING_FAILED_URI)) {
            LOGGER.warn("{}: [{}] fail http decoding", Channels.getHexText(ctx), requestId);
            ctx.read();
            return;
        }

        // get a few headers we really care about
        HttpVersion httpVersion = nettyRequest.protocolVersion();
        boolean keepAlive = HttpHeaders.isKeepAlive(nettyRequest);
        boolean transferEncodingChunked = HttpHeaders.isTransferEncodingChunked(nettyRequest);
        boolean continueExpected = HttpHeaders.is100ContinueExpected(nettyRequest);
        long contentLength = HttpHeaders.getContentLength(nettyRequest, ZERO_CONTENT_LENGTH);
        boolean hasContent = transferEncodingChunked || contentLength > ZERO_CONTENT_LENGTH;
        LOGGER.trace("{}: [{}] rq:{} ka:{} ck:{} ce:{} cl:{}", Channels.getHexText(ctx), requestId,
                nettyRequest, keepAlive, transferEncodingChunked, continueExpected, contentLength);

        // create the input stream used to read content
        ContentInputStream entityInputStream;
        if (hasContent) {
            entityInputStream = new EntityInputStream(httpVersion, continueExpected, ctx);
        } else {
            entityInputStream = EmptyEntityInputStream.EMPTY_ENTITY_INPUT_STREAM;
        }

        // create the object with which to write the response body
        PendingRequest pendingRequest = new PendingRequest(requestId, httpVersion, keepAlive, entityInputStream,
                ctx);

        // create the jersey request object
        final ContainerRequest jerseyRequest = new ContainerRequest(baseUri, URI.create(nettyRequest.uri()),
                nettyRequest.method().name(), DEFAULT_SECURITY_CONTEXT, PROPERTIES_DELEGATE);
        jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_CHANNEL_ID_PROPERTY,
                new ChannelId(Channels.getHexText(ctx)));
        jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_REQUEST_ID_PROPERTY,
                new RequestId(requestId));
        jerseyRequest.header(Headers.REQUEST_TRACING_HEADER, requestId); // add request id to headers
        copyHeaders(nettyRequest.headers(), jerseyRequest); // copy headers from message
        jerseyRequest.setEntityStream(entityInputStream);
        jerseyRequest.setWriter(pendingRequest);

        // now we've got all the initial headers and are waiting for the entity
        this.pendingRequest = pendingRequest;

        // store the runnable that we want jersey to execute
        saveRequestRunnable(() -> {
            // all throwables caught by jersey internally -
            // handled by the ResponseWriter below
            // if, for some reason there's some weird error it'll be handled
            // by the default exception handler, which kills the process
            applicationHandler.handle(jerseyRequest);
        });

        // IMPORTANT:
        // we pass this request up to be processed by
        // jersey before we've read any content. This allows
        // the resource to read from the InputStream
        // directly, OR, to use an @Consumes annotation with an
        // input objectType to invoke the appropriate parser
        //
        // since the request is consumed *before* the content
        // has been received readers may block. to prevent the
        // IO thread from blocking we have to execute all
        // request processing in an application threadpool
        if (hasContent) {
            submitPendingRunnable();
        }

        // indicate that we want to keep reading
        // this is always the case when we receive headers
        // because we want to receive everything until
        // LastHttpContent
        ctx.read();
    } else {
        // after receiving the http headers we get
        // a series of HttpContent objects that represent
        // the entity or a set of chunks

        // we should have received the headers already
        Preconditions.checkState(pendingRequest != null, "no pending request");
        // we're not expecting anything other than content objects right now
        Preconditions.checkArgument(msg instanceof HttpContent, "HttpContent expected, not %s",
                msg.getClass().getSimpleName());

        // handle the content
        HttpContent content = (HttpContent) msg;
        boolean last = msg instanceof LastHttpContent;
        LOGGER.trace("{}: [{}] handling content:{} last:{}", Channels.getHexText(ctx), pendingRequest.requestId,
                content.content().readableBytes(), last);
        pendingRequest.entityInputStream.addBuffer(content.content(), last); // transfers ownership to the HttpContentInputStream

        // FIXME (AG): support trailing headers
        // if it's the last piece of content, then we're done
        if (last) {
            // submit the request to jersey if we haven't yet
            if (savedRequestRunnable != null) {
                submitPendingRunnable();
            }
        }
    }
}

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

License:BSD License

@Override
public long getContentLength() {
    return HttpHeaders.getContentLength(nettyRequest, 0);
}

From source file:com.cu.http.container.core.adaptor.NettyServletRequest.java

License:Apache License

@Override
public int getContentLength() {
    return (int) HttpHeaders.getContentLength(this.originalRequest, -1);
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Combines all the parts in {@code contents} into one {@link ByteBuffer}.
 * @param response the {@link HttpResponse} containing headers.
 * @param contents the content of the response.
 * @return a {@link ByteBuffer} that contains all the data in {@code contents}.
 *///from w ww . j a  v a  2 s. co  m
private ByteBuffer getContent(HttpResponse response, Queue<HttpObject> contents) {
    long contentLength = HttpHeaders.getContentLength(response, -1);
    if (contentLength == -1) {
        contentLength = HttpHeaders.getIntHeader(response, RestUtils.Headers.BLOB_SIZE, 0);
    }
    ByteBuffer buffer = ByteBuffer.allocate((int) contentLength);
    for (HttpObject object : contents) {
        HttpContent content = (HttpContent) object;
        buffer.put(content.content().nioBuffer());
        ReferenceCountUtil.release(content);
    }
    return buffer;
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Combines all the parts in {@code contents} into one {@link ByteBuffer}.
 * @param response the {@link HttpResponse} containing headers.
 * @param contents the content of the response.
 * @return a {@link ByteBuffer} that contains all the data in {@code contents}.
 */// w  w w .  jav a 2  s  .co m
private ByteBuffer getContent(HttpResponse response, Queue<HttpObject> contents) {
    long contentLength = HttpHeaders.getContentLength(response, -1);
    if (contentLength == -1) {
        contentLength = HttpHeaders.getIntHeader(response, RestUtils.Headers.BLOB_SIZE, 0);
    }
    ByteBuffer buffer = ByteBuffer.allocate((int) contentLength);
    boolean endMarkerFound = false;
    for (HttpObject object : contents) {
        assertFalse("There should have been no more data after the end marker was found", endMarkerFound);
        HttpContent content = (HttpContent) object;
        buffer.put(content.content().nioBuffer());
        endMarkerFound = object instanceof LastHttpContent;
        ReferenceCountUtil.release(content);
    }
    return buffer;
}

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

License:Open Source License

/**
 * Wraps the {@code request} in an implementation of {@link RestRequest} so that other layers can understand the
 * request.//from   w  w  w .j  av  a 2s .  co m
 * <p/>
 * Note on content size: The content size is deduced in the following order:-
 * 1. From the {@link RestUtils.Headers#BLOB_SIZE} header.
 * 2. If 1 fails, from the {@link HttpHeaders.Names#CONTENT_LENGTH} header.
 * 3. If 2 fails, it is set to -1 which means that the content size is unknown.
 * If content size is set in the header (i.e. not -1), the actual content size should match that value. Otherwise, an
 * exception will be thrown.
 * @param request the {@link HttpRequest} that needs to be wrapped.
 * @param nettyMetrics the {@link NettyMetrics} instance to use.
 * @throws IllegalArgumentException if {@code request} is null.
 * @throws RestServiceException if the {@link HttpMethod} defined in {@code request} is not recognized as a
 *                                {@link RestMethod}.
 */
public NettyRequest(HttpRequest request, NettyMetrics nettyMetrics) throws RestServiceException {
    if (request == null) {
        throw new IllegalArgumentException("Received null HttpRequest");
    }
    restRequestMetricsTracker.nioMetricsTracker.markRequestReceived();
    HttpMethod httpMethod = request.getMethod();
    if (httpMethod == HttpMethod.GET) {
        restMethod = RestMethod.GET;
    } else if (httpMethod == HttpMethod.POST) {
        restMethod = RestMethod.POST;
    } else if (httpMethod == HttpMethod.DELETE) {
        restMethod = RestMethod.DELETE;
    } else if (httpMethod == HttpMethod.HEAD) {
        restMethod = RestMethod.HEAD;
    } else {
        nettyMetrics.unsupportedHttpMethodError.inc();
        throw new RestServiceException("http method not supported: " + httpMethod,
                RestServiceErrorCode.UnsupportedHttpMethod);
    }
    this.request = request;
    this.query = new QueryStringDecoder(request.getUri());
    this.nettyMetrics = nettyMetrics;

    if (HttpHeaders.getHeader(request, RestUtils.Headers.BLOB_SIZE, null) != null) {
        size = Long.parseLong(HttpHeaders.getHeader(request, RestUtils.Headers.BLOB_SIZE));
    } else {
        size = HttpHeaders.getContentLength(request, -1);
    }

    // query params.
    for (Map.Entry<String, List<String>> e : query.parameters().entrySet()) {
        StringBuilder value = null;
        if (e.getValue() != null) {
            StringBuilder combinedValues = combineVals(new StringBuilder(), e.getValue());
            if (combinedValues.length() > 0) {
                value = combinedValues;
            }
        }
        allArgs.put(e.getKey(), value);
    }

    Set<io.netty.handler.codec.http.Cookie> nettyCookies = null;
    // headers.
    for (Map.Entry<String, String> e : request.headers()) {
        StringBuilder sb;
        if (e.getKey().equals(HttpHeaders.Names.COOKIE)) {
            String value = e.getValue();
            if (value != null) {
                nettyCookies = CookieDecoder.decode(value);
            }
        } else {
            boolean valueNull = request.headers().get(e.getKey()) == null;
            if (!valueNull && allArgs.get(e.getKey()) == null) {
                sb = new StringBuilder(e.getValue());
                allArgs.put(e.getKey(), sb);
            } else if (!valueNull) {
                sb = (StringBuilder) allArgs.get(e.getKey());
                sb.append(MULTIPLE_HEADER_VALUE_DELIMITER).append(e.getValue());
            } else if (!allArgs.containsKey(e.getKey())) {
                allArgs.put(e.getKey(), null);
            }
        }
    }

    // turn all StringBuilders into String
    for (Map.Entry<String, Object> e : allArgs.entrySet()) {
        if (allArgs.get(e.getKey()) != null) {
            allArgs.put(e.getKey(), (e.getValue()).toString());
        }
    }
    // add cookies to the args as java cookies
    if (nettyCookies != null) {
        Set<javax.servlet.http.Cookie> cookies = convertHttpToJavaCookies(nettyCookies);
        allArgs.put(RestUtils.Headers.COOKIE, cookies);
    }
    allArgsReadOnly = Collections.unmodifiableMap(allArgs);
}

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

License:Apache License

public long getContentLength(long defaultValue) {
    return HttpHeaders.getContentLength(nettyRequest, defaultValue);
}

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

License:Apache License

public long getContentLength(long defaultValue) {
    return HttpHeaders.getContentLength(nettyResponse, defaultValue);
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private AtmosphereRequest createAtmosphereRequest(final ChannelHandlerContext ctx, final HttpRequest request,
        byte[] body) throws URISyntaxException, UnsupportedEncodingException, MalformedURLException {
    final String base = getBaseUri(request);
    final URI requestUri = new URI(base.substring(0, base.length() - 1) + request.getUri());
    final String ct = HttpHeaders.getHeader(request, "Content-Type", "text/plain");
    final long cl = HttpHeaders.getContentLength(request, 0);
    String method = request.getMethod().name();

    String queryString = requestUri.getQuery();
    Map<String, String[]> qs = new HashMap<String, String[]>();
    if (queryString != null) {
        parseQueryString(qs, queryString);
    }//  www  . j a  v  a 2 s  . c  om

    if (ct.equalsIgnoreCase("application/x-www-form-urlencoded")) {
        if (FullHttpRequest.class.isAssignableFrom(request.getClass())) {
            parseQueryString(qs, new String(body));
        }
    }

    String u = requestUri.toURL().toString();
    int last = u.indexOf("?") == -1 ? u.length() : u.indexOf("?");
    String url = u.substring(0, last);
    int l;

    if (url.contains(config.mappingPath())) {
        l = requestUri.getAuthority().length() + requestUri.getScheme().length() + 3
                + config.mappingPath().length();
    } else {
        l = requestUri.getAuthority().length() + requestUri.getScheme().length() + 3;
    }

    HttpSession session = null;
    if (framework.getAtmosphereConfig().isSupportSession()) {
        String[] transport = qs.get(HeaderConfig.X_ATMOSPHERE_TRANSPORT);
        if (transport != null && transport.length > 0) {
            String[] uuid = qs.get(HeaderConfig.X_ATMOSPHERE_TRACKING_ID);
            if (uuid != null && uuid.length > 0) {
                // TODO: Session is only supported until an unsubscribe is received.
                if (transport[0].equalsIgnoreCase(HeaderConfig.DISCONNECT_TRANSPORT_MESSAGE)) {
                    sessions.remove(uuid[0]);
                } else {
                    session = sessions.get(uuid[0]);

                    if (session == null) {
                        session = new FakeHttpSession("-1", null, System.currentTimeMillis(), -1);
                    }
                }
            }
        }
    }

    final Map<String, Object> attributes = new HashMap<String, Object>();
    AtmosphereRequestImpl.Builder requestBuilder = new AtmosphereRequestImpl.Builder();
    requestBuilder.requestURI(url.substring(l)).requestURL(url).pathInfo(url.substring(l))
            .headers(getHeaders(request)).method(method).contentType(ct).contentLength(cl)
            // We need to read attribute after doComet
            .destroyable(false).attributes(attributes).servletPath(config.mappingPath()).session(session)
            .cookies(getCookies(request)).queryStrings(qs)
            .remoteInetSocketAddress(new Callable<InetSocketAddress>() {
                @Override
                public InetSocketAddress call() throws Exception {
                    return (InetSocketAddress) ctx.channel().remoteAddress();
                }
            }).localInetSocketAddress(new Callable<InetSocketAddress>() {

                @Override
                public InetSocketAddress call() throws Exception {
                    return (InetSocketAddress) ctx.channel().localAddress();
                }
            });

    if (body.length > 0) {
        requestBuilder.body(body);
    }

    return requestBuilder.build();

}