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

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

Introduction

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

Prototype

public static long getContentLength(HttpMessage message) 

Source Link

Document

Returns the length of the content.

Usage

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);/* w  w w.  ja  v  a 2s .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;/*from   ww w  . j  a v  a 2 s.c o m*/
    }

    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:org.glassfish.jersey.netty.connector.JerseyClientHandler.java

License:Open Source License

@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/*  ww  w  . j a  v  a  2s.  c om*/
            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);
        }
    }
}

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

License:Open Source License

/**
 * Create Jersey {@link ContainerRequest} based on Netty {@link HttpRequest}.
 *
 * @param ctx Netty channel context./*from ww  w . j a v a  2 s  . co m*/
 * @param req Netty Http request.
 * @return created Jersey Container Request.
 */
private ContainerRequest createContainerRequest(ChannelHandlerContext ctx, HttpRequest req) {

    String s = req.uri().startsWith("/") ? req.uri().substring(1) : req.uri();
    URI requestUri = URI.create(baseUri + ContainerUtils.encodeUnsafeCharacters(s));

    ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, req.method().name(),
            getSecurityContext(), new PropertiesDelegate() {

                private final Map<String, Object> properties = new HashMap<>();

                @Override
                public Object getProperty(String name) {
                    return properties.get(name);
                }

                @Override
                public Collection<String> getPropertyNames() {
                    return properties.keySet();
                }

                @Override
                public void setProperty(String name, Object object) {
                    properties.put(name, object);
                }

                @Override
                public void removeProperty(String name) {
                    properties.remove(name);
                }
            });

    // request entity handling.
    if ((req.headers().contains(HttpHeaderNames.CONTENT_LENGTH) && HttpUtil.getContentLength(req) > 0)
            || HttpUtil.isTransferEncodingChunked(req)) {

        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);
            }
        });

        requestContext.setEntityStream(new NettyInputStream(isList));
    } else {
        requestContext.setEntityStream(new InputStream() {
            @Override
            public int read() throws IOException {
                return -1;
            }
        });
    }

    // copying headers from netty request to jersey container request context.
    for (String name : req.headers().names()) {
        requestContext.headers(name, req.headers().getAll(name));
    }

    return requestContext;
}