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

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

Introduction

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

Prototype

@Deprecated
public static boolean isTransferEncodingChunked(HttpMessage message) 

Source Link

Usage

From source file:HttpUploadServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//from  ww w.j a v  a2 s. c o m
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : headers) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                readHttpDataAllReceive(ctx.channel());
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}

From source file:cc.io.lessons.server.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

    if (msg instanceof HttpRequest) {
        System.out.println(msg.toString());
    } else {// w  w w.  j ava 2s. c  o m
        System.out.println(ByteBufUtil.hexDump(((HttpContent) msg).content()));
        //System.out.println(((HttpContent) msg).content().toString(Charset.defaultCharset()));
    }

    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : headers) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}

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;//  w  w  w  .ja  v a  2  s.com
    }

    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.ahanda.techops.noty.clientTest.ClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    assert msg instanceof FullHttpResponse;
    l.info(" Got a message from server !!! {}", msg);
    ++state;/*from   w w  w.  j  a  v  a  2 s.  co m*/

    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.out.println("STATUS: " + response.getStatus());
        System.out.println("VERSION: " + response.getProtocolVersion());
        System.out.println();

        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    System.out.println("HEADER: " + name + " = " + value);
                }
            }
            System.out.println();
        }

        if (HttpHeaders.isTransferEncodingChunked(response)) {
            System.out.println("CHUNKED CONTENT {");
        } else {
            System.out.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.out.print(content.content().toString(CharsetUtil.UTF_8));
        System.out.flush();

        if (content instanceof LastHttpContent) {
            System.out.println("} END OF CONTENT");
        }
    }

    switch (state) {
    case 1:
        FullHttpResponse resp = (FullHttpResponse) msg;
        for (String cookiestr : resp.headers().getAll(HttpHeaders.Names.SET_COOKIE)) {
            Set<Cookie> tmp = CookieDecoder.decode(cookiestr);
            sessCookies = tmp;
        }
        //login( ctx.channel(), credential );
        pubEvent(ctx.channel(), event, (FullHttpResponse) msg);
        break;
    case 2:
        getEvents(ctx.channel(), (FullHttpResponse) msg);
        break;
    case 3:
        logout(ctx.channel());
        break;
    default:
        ctx.close();
        break;
    }
}

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

License:BSD License

@Override
public boolean isChunkedEncoding() {
    return HttpHeaders.isTransferEncodingChunked(nettyRequest);
}

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

License:BSD License

@Override
public boolean isChunkedEncoding() {
    return HttpHeaders.isTransferEncodingChunked(this);
}

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

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    long startTimeInMs = System.currentTimeMillis();
    boolean shouldReset = msg instanceof LastHttpContent;
    if (request != null) {
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            logHeaders("Response", response, publicAccessLogger.getResponseHeaders());
            logMessage.append(", ");
            logMessage.append("status=").append(response.getStatus().code());
            logMessage.append(", ");
            if (HttpHeaders.isTransferEncodingChunked(response)) {
                responseFirstChunkStartTimeInMs = System.currentTimeMillis();
            } else {
                shouldReset = true;/*from w  ww.  ja  v a 2 s.com*/
            }
        } else if (!(msg instanceof HttpContent)) {
            logger.error(
                    "Sending response that is not of type HttpResponse or HttpContent. Sending response to "
                            + ctx.channel().remoteAddress() + ". Request is of type " + msg.getClass()
                            + ". No action being taken other than logging this unexpected state.");
        }
        if (shouldReset) {
            logDurations();
            publicAccessLogger.logInfo(logMessage.toString());
            reset();
        }
    }
    nettyMetrics.publicAccessLogResponseProcessingTimeInMs.update(System.currentTimeMillis() - startTimeInMs);
    super.write(ctx, msg, promise);
}

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

License:Open Source License

/**
 * Appends specified headers to the log message if those headers are not null
 * @param tag pretty name for set of headers to append
 * @param message http message from which to log headers
 * @param headers array of headers to log
 *///from   w ww . j a  v a 2s.c om
private void logHeaders(String tag, HttpMessage message, String[] headers) {
    logMessage.append(tag).append(" (");
    for (String header : headers) {
        if (message.headers().get(header) != null) {
            logMessage.append("[").append(header).append("=").append(message.headers().get(header))
                    .append("] ");
        }
    }
    boolean isChunked = HttpHeaders.isTransferEncodingChunked(message);
    logMessage.append("[isChunked=").append(isChunked).append("]");
    logMessage.append(")");
}

From source file:com.digisky.innerproxy.testclient.HttpSnoopClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    TestTimer.add("channelRead0()::37");
    TestTimer.print();/*from www .  j ava 2s  .co m*/
    System.out.println("http CLient received a package!");
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.getStatus());
        System.err.println("VERSION: " + response.getProtocolVersion());
        System.err.println();

        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }
            }
            System.err.println();
        }

        if (HttpHeaders.isTransferEncodingChunked(response)) {
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.err.print(content.content().toString(CharsetUtil.UTF_8));
        System.err.flush();

        if (content instanceof LastHttpContent) {
            System.err.println("} END OF CONTENT");
            ctx.close();
        }
    }

}

From source file:com.digisky.stresstest.HttpSnoopClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println("http CLient received a package!");
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;

        System.err.println("STATUS: " + response.getStatus());
        System.err.println("VERSION: " + response.getProtocolVersion());
        System.err.println();/*from   w  w  w. j a va 2s. co  m*/

        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    System.err.println("HEADER: " + name + " = " + value);
                }
            }
            System.err.println();
        }

        if (HttpHeaders.isTransferEncodingChunked(response)) {
            System.err.println("CHUNKED CONTENT {");
        } else {
            System.err.println("CONTENT {");
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;

        System.err.print(content.content().toString(CharsetUtil.UTF_8));
        System.err.flush();

        if (content instanceof LastHttpContent) {
            System.err.println("} END OF CONTENT");
            ctx.close();
        }
    }

}