org.jboss.netty.handler.codec.http.HttpChunk Java Examples

The following examples show how to use org.jboss.netty.handler.codec.http.HttpChunk. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpServerHandler.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (!readingChunks) {
        request = (HttpRequest) e.getMessage();
        String uri = request.getUri();
        if (uri.equals("/exception")) {
            throw new Exception("Test");
        }
        if (request.isChunked()) {
            readingChunks = true;
        } else {
            writeResponse(e);
        }
    } else {
        HttpChunk chunk = (HttpChunk) e.getMessage();
        if (chunk.isLast()) {
            readingChunks = false;
            writeResponse(e);
        }
    }
}
 
Example #2
Source File: ClientTimingHandler.java    From zuul-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpChunk) {
        if (((HttpChunk) e.getMessage()).isLast()) {
            logDifference(System.nanoTime() - writeStart);
            exchangeContext.stop();
        }
    } else if (e.getMessage() instanceof HttpMessage) {
        if (!((HttpMessage) e.getMessage()).isChunked()) {
            logDifference(System.nanoTime() - writeStart);
            exchangeContext.stop();
        }
    } else {
        logDifference(System.nanoTime() - writeStart);
        exchangeContext.stop();
    }

    super.messageReceived(ctx, e);
}
 
Example #3
Source File: HttpRequestFrameworkHandler.java    From zuul-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) e.getMessage();
        InterruptsImpl callback = new InterruptsImpl(request, e.getChannel());
        LOG.debug("handler: {} is calling request-handler: {}", tag, requestHandler.getClass().getSimpleName());
        requestHandler.requestReceived(new HttpRequestFrameworkAdapter(request));


        if (callback.isInterrupted()) {
            //plugin requested that execution is interrupted i.e. not passed down the pipeline
            return;
        }
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("encountered a chunk, not passed to handler");
    }

    super.messageReceived(ctx, e);
}
 
Example #4
Source File: ServerTimingHandler.java    From zuul-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpChunk) {
        if (((HttpChunk) e.getMessage()).isLast()) {
            context.stop();
            logDifference(System.nanoTime() - start);
            LOG.debug("saw last chunk");
        }
    } else if (e.getMessage() instanceof HttpMessage) {
        if (!((HttpMessage) e.getMessage()).isChunked()) {
            context.stop();
            logDifference(System.nanoTime() - start);
        }
        LOG.debug("headers: {}", ((HttpMessage) e.getMessage()).getHeaders());
    } else {
        context.stop();
        logDifference(System.nanoTime() - start);
    }

    LOG.debug("saw message {}", e.getMessage());

    super.writeRequested(ctx, e);
}
 
Example #5
Source File: HttpResponseFrameworkHandler.java    From zuul-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e.getMessage();
        HttpRequest request = (HttpRequest) ctx.getAttachment();

        LOG.debug("handler: {} is calling response-handler: {}", tag, responseHandler.getClass().getSimpleName());
        responseHandler.responseReceived(new HttpRequestFrameworkAdapter(request), new HttpResponseFrameworkAdapter(response));

        ctx.setAttachment(null);
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("encountered a chunk, not passed to handler");
    }

    super.writeRequested(ctx, e);
}
 
Example #6
Source File: FileClientHandler.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	if (!this.readingChunks) {
		HttpResponse response = (HttpResponse) e.getMessage();
		LOGGER.info("STATUS: " + response.getStatus());
		if ((response.getStatus().getCode() == 200)
				&& (response.isChunked())) {
			this.readingChunks = true;
		} else {
			ChannelBuffer content = response.getContent();
			if (content.readable())
				this.responseContent.append(content
						.toString(CharsetUtil.UTF_8));
		}
	} else {
		HttpChunk chunk = (HttpChunk) e.getMessage();
		if (chunk.isLast()) {
			this.readingChunks = false;
			this.responseContent.append(chunk.getContent().toString(
					CharsetUtil.UTF_8));

			String json = this.responseContent.toString();
			this.result = ((Result) JSONUtil.parseObject(json,Result.class));
		} else {
			this.responseContent.append(chunk.getContent().toString(
					CharsetUtil.UTF_8));
		}
	}
}
 
Example #7
Source File: HttpProxyHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, final MessageEvent message) throws Exception {
    final Channel inboundChannel = message.getChannel();

    try {
        if (message.getMessage() instanceof HttpRequest) {

            final HttpRequest request = (HttpRequest) message.getMessage();
            handleRequest(request, inboundChannel);

        } else if (message.getMessage() instanceof HttpChunk) {

            if (!isChunkedRequestsSupported) {
                LOG.warn("requests with chunked transfer encoding are not supported");
                inboundChannel.close();
                return;
            }

            final HttpChunk chunk = (HttpChunk) message.getMessage();
            handleChunk(chunk, inboundChannel);

        }
    } catch (IllegalRouteException e) {
        //TODO: do something better than dropping the connection when the route is bad
        inboundChannel.close();
        LOG.warn("dropped connection for bad route: {}", e.getRoute());
    }
}
 
Example #8
Source File: HttpProxyHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
private void performChunkWrite(Channel inboundChannel, Channel outboundChannel, List<HttpChunk> buffer) {
    for (HttpChunk chunk : buffer) {
        LOG.debug("writing buffered chunk");
        performWrite(inboundChannel, outboundChannel, chunk);
    }
    buffer.clear();
}
 
Example #9
Source File: StreamChunkAggregator.java    From restcommander with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Object msg = e.getMessage();
    if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) {
        ctx.sendUpstream(e);
        return;
    }

    HttpMessage currentMessage = this.currentMessage;
    File localFile = this.file;
    if (currentMessage == null) {
        HttpMessage m = (HttpMessage) msg;
        if (m.isChunked()) {
            final String localName = UUID.randomUUID().toString();
            // A chunked message - remove 'Transfer-Encoding' header,
            // initialize the cumulative buffer, and wait for incoming chunks.
            List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING);
            encodings.remove(HttpHeaders.Values.CHUNKED);
            if (encodings.isEmpty()) {
                m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING);
            }
            this.currentMessage = m;
            this.file = new File(Play.tmpDir, localName);
            this.out = new FileOutputStream(file, true);
        } else {
            // Not a chunked message - pass through.
            ctx.sendUpstream(e);
        }
    } else {
        // TODO: If less that threshold then in memory
        // Merge the received chunk into the content of the current message.
        final HttpChunk chunk = (HttpChunk) msg;
        if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) {
            currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded");
        } else {
            IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out);

            if (chunk.isLast()) {
                this.out.flush();
                this.out.close();

                currentMessage.setHeader(
                        HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(localFile.length()));

                currentMessage.setContent(new FileChannelBuffer(localFile));
                this.out = null;
                this.currentMessage = null;
                this.file = null;
                Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress());
            }
        }
    }

}
 
Example #10
Source File: HttpInvocationContext.java    From elasticsearch-helper with Apache License 2.0 4 votes vote down vote up
HttpInvocationContext(HttpAction httpAction, ActionListener<Response> listener, List<HttpChunk> chunks, Request request) {
    this.httpAction = httpAction;
    this.listener = listener;
    this.chunks = chunks;
    this.request = request;
}
 
Example #11
Source File: HttpKeepAliveHandler.java    From zuul-netty with Apache License 2.0 4 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) ctx.getAttachment();

    if (e.getMessage() instanceof HttpResponse) {

        HttpResponse response = (HttpResponse) e.getMessage();

        if (!response.isChunked()) {

            if (isKeepAliveSupported && isKeepAlive(request)) {

                LOG.debug("keep-alive IS implemented for this connection");

                // Add 'Content-Length' header only for a keep-alive connection.
                response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
                // Add keep alive header as per:
                // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
                response.setHeader(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

            } else {

                //not chunked and keep alive not supported, closing connection
                LOG.debug("keep-alive NOT implemented for this connection");
                e.getFuture().addListener(ChannelFutureListener.CLOSE);

            }

        } else {
            //response is chunked

            //don't send a content-length for chunked transfer-encoding
            response.removeHeader(CONTENT_LENGTH);

            //keep-alive explicitly off
            if (!isKeepAliveSupported || !isKeepAlive(request)) {
                response.removeHeader(CONNECTION);
                LOG.debug("keep-alive NOT implemented for this connection as it is explicitly turned off");
            } else {
                LOG.debug("keep-alive IMPLIED for this connection as it is chunked");
            }
        }
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("found chunk");
        if (((HttpChunk) e.getMessage()).isLast()) {

            if (!isKeepAliveSupported || !isKeepAlive(request)) {
                //keep alive explicitly off
                LOG.debug("reached the last chunk and keep alive is turned off so closing the connection");
                e.getFuture().addListener(ChannelFutureListener.CLOSE);
            }

        }
    } else {
        LOG.debug("found something else");
    }

    super.writeRequested(ctx, e);
}
 
Example #12
Source File: HttpProxyHandler.java    From zuul-netty with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    //it is possible that the client has gone away so check before writing to the channel
    if (inboundChannel.isConnected()) {

        LOG.debug("return write isConnected:{}, type={} - {}", outboundNull() ? WENT_AWAY : outboundConnection.getChannel().isConnected(), e
                .getMessage().getClass().getSimpleName(), outboundNull() ? WENT_AWAY : outboundConnection.getId());

        //TODO: this is an extraordinarily bad idea as 1: it brings the buffer into user space and 2: it doesn't reset the buffer properly
        if (e.getMessage() instanceof HttpResponse) {
            final HttpResponse response = (HttpResponse) e.getMessage();
            //LOG.debug("response payload {} {}", outboundNull() ? WENT_AWAY : outboundConnection.getId(), dumpBuffer(response.getContent()));
        } else if (e.getMessage() instanceof HttpChunk) {
            final HttpChunk chunk = (HttpChunk) e.getMessage();
            //LOG.debug("chunk payload {} {}", outboundNull() ? WENT_AWAY : outboundConnection.getId(), dumpBuffer(chunk.getContent()));
        }

        if (e.getMessage() instanceof HttpResponse) {
            LOG.debug("response is chunked: {} {}", ((HttpResponse) e.getMessage()).isChunked(), outboundNull() ? WENT_AWAY
                    : outboundConnection.getId());
        }

        if (e.getMessage() instanceof HttpResponse && !((HttpResponse) e.getMessage()).isChunked()) {
            disposeConnection(); //not chunked so we're done
        } else if (e.getMessage() instanceof HttpChunk && ((HttpChunk) e.getMessage()).isLast()) {
            disposeConnection(); //chunked and is last chunk so we're done
        }

        //it is important to dispose of the outbound connection before writing here to stop the client sending the next request before it's finished
        inboundChannel.write(e.getMessage());

    } else {

        LOG.debug("client disconnected, assuming bad outbound state as well, closing connection {}", outboundNull() ? WENT_AWAY
                : outboundConnection.getId());

        inboundChannel.close();
        destroyConnection();

    }

}
 
Example #13
Source File: HttpProxyHandler.java    From zuul-netty with Apache License 2.0 4 votes vote down vote up
private void handleChunk(final HttpChunk chunk, final Channel inboundChannel) {

        //accept some lock acquisition here since request chunking is rare
        //need to lock before doneSendingRequestAndBuffer test to avoid race condition
        synchronized (queuedChunks) {

            if (!doneSendingRequestAndBuffer) {

                //buffer the chunks until the request has been sent
                queuedChunks.add(chunk);

                LOG.debug("buffering chunk");

            } else {

                //write onto established connection
                performWrite(inboundChannel, outboundConnection.getChannel(), chunk);

                LOG.debug("writing un-buffered chunk");

            }

        }
    }