List of usage examples for io.netty.handler.codec.http HttpContent retain
@Override HttpContent retain();
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;//from w w w. j ava2 s . co 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.mastfrog.acteur.server.HttpObjectAggregator.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { FullHttpMessage currentMessage = this.currentMessage; if (msg instanceof HttpMessage) { tooLongFrameFound = false;// w w w . j a v a 2 s . c o m assert currentMessage == null; HttpMessage m = (HttpMessage) msg; // Handle the 'Expect: 100-continue' header if necessary. // TODO: Respond with 413 Request Entity Too Large // and discard the traffic or close the connection. // No need to notify the upstream handlers - just log. // If decoding a response, just throw an exception. if (is100ContinueExpected(m)) { ByteBuf buf = CONTINUE_LINE.duplicate(); buf.retain(); ctx.writeAndFlush(buf).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 DefaultFullHttpRequest(header.getProtocolVersion(), header.getMethod(), header.getUri(), Unpooled.compositeBuffer(maxCumulationBufferComponents)); } else if (msg instanceof HttpResponse) { HttpResponse header = (HttpResponse) msg; this.currentMessage = currentMessage = new DefaultFullHttpResponse(header.getProtocolVersion(), header.getStatus(), Unpooled.compositeBuffer(maxCumulationBufferComponents)); } else { throw new Error(); } currentMessage.headers().set(m.headers()); // 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.headers().add(trailer.trailingHeaders()); } // Set the 'Content-Length' header. currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(content.readableBytes())); // All done out.add(currentMessage); } } else { throw new Error(); } }
From source file:io.nebo.container.HttpContentInputStream.java
License:Apache License
public void addContent(HttpContent httpContent) { checkNotClosed(); this.queue.offer(httpContent.retain()); }
From source file:org.ebayopensource.scc.filter.NettyResponseProxyFilter.java
License:Apache License
@Override public HttpObject filterResponse(HttpObject orignal, ChannelHandlerContext ctx) { HttpObject httpObject = orignal;/*ww w. j a v a 2 s. com*/ if (httpObject instanceof HttpResponse) { String uri = ctx.attr(NettyRequestProxyFilter.REQUEST_URI).get(); LOGGER.info("Received a response from: " + uri); if (((HttpResponse) httpObject).getStatus().code() >= 300) { ctx.attr(NettyRequestProxyFilter.IS_CACHABLE).set(false); } } if (!ctx.attr(NettyRequestProxyFilter.IS_CACHABLE).get()) { return httpObject; } final String key = ctx.attr(NettyRequestProxyFilter.CACHE_KEY).get(); if (key == null) { return httpObject; } if (httpObject instanceof HttpResponse) { LOGGER.debug("Response code: " + ((HttpResponse) httpObject).getStatus().code()); } if (httpObject instanceof FullHttpResponse) { m_policyManager.getCacheManager().put(key, httpObject); } else { final List<HttpObject> chunkedResponses = m_chunkedResponses.get(); if (httpObject instanceof HttpContent) { HttpContent httpContent = ((HttpContent) httpObject).duplicate(); httpContent.retain(); httpObject = httpContent; } chunkedResponses.add(httpObject); if (httpObject instanceof LastHttpContent) { Runnable runnable = new Runnable() { @Override public void run() { try { m_policyManager.getCacheManager().put(key, chunkedResponses); } catch (Throwable t) { LOGGER.error(t.getMessage(), t); return; } for (HttpObject obj : chunkedResponses) { if (obj instanceof HttpContent) { HttpContent httpContent = (HttpContent) obj; httpContent.release(); } } chunkedResponses.clear(); LOGGER.debug("Cache response to: " + key); } }; m_execService.submit(runnable); } } return orignal; }
From source file:org.nosceon.titanite.body.AbstractRawBodyParser.java
License:Apache License
@Override public final void doOffer(HttpContent chunk) { chunk.retain(); content.addComponent(chunk.content()); content.writerIndex(content.writerIndex() + chunk.content().readableBytes()); }
From source file:org.springframework.boot.context.embedded.netty.HttpContentInputStream.java
License:Apache License
public void addContent(HttpContent httpContent) { checkNotClosed();/* www . ja v a 2 s .c om*/ queue.offer(httpContent.retain()); // TODO limit the number of queued inputs, stop handler from reading from channel }
From source file:org.thingsplode.synapse.endpoint.handlers.ResponseIntrospector.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg == null) { logger.warn("Message@Endpoint <to be sent> is NULL."); } else if (logger.isDebugEnabled() && ((msg instanceof HttpResponse) || (msg instanceof HttpContent))) { if (!(msg instanceof HttpResponse)) { HttpContent content = (HttpContent) msg; logger.debug("Message@Endpoint to be sent: http content -> " + content.toString()); } else {/* w w w . j av a2s. com*/ final StringBuilder hb = new StringBuilder(); ((HttpResponse) msg).headers().entries().forEach(e -> { hb.append(e.getKey()).append(" : ").append(e.getValue()).append("\n"); }); String payloadAsSring = null; if (msg instanceof FullHttpResponse) { ByteBuf content = ((FullHttpResponse) msg).content(); byte[] dst = content.copy().array(); //content.copy().getBytes(0, dst); content.retain(); payloadAsSring = new String(dst, Charset.forName("UTF-8")); } String msgStatus = (((HttpResponse) msg).status() != null ? ((HttpResponse) msg).status().toString() : "NULL"); logger.debug("Message@Endpoint [" + msg.getClass().getSimpleName() + "] to be sent: \n\n" + "Status: " + msgStatus + "\n" + hb.toString() + "\n" + "Payload: [" + (!Util.isEmpty(payloadAsSring) ? payloadAsSring : "EMPTY") + "]\n"); } } else if (logger.isDebugEnabled() && (msg instanceof WebSocketFrame)) { if (msg instanceof TextWebSocketFrame) { logger.debug("Message@Endpoint [" + msg.getClass().getSimpleName() + "] to be sent: " + msg.getClass().getSimpleName() + " \n\n" + ((TextWebSocketFrame) msg).text()); } else { logger.debug("Message@Endpoint [" + msg.getClass().getSimpleName() + "] to be sent: \n\n {" + msg.getClass().getSimpleName() + " -> " + msg.toString() + "}"); } } else { logger.debug( "Unknown message (" + msg.getClass().getSimpleName() + ") will be dispatched to the client."); } ctx.write(msg, promise); }
From source file:org.wso2.carbon.gateway.internal.mediation.camel.CarbonMessageTypeConverter.java
License:Open Source License
private CompositeByteBuf aggregateChunks(Pipe pipe) { ByteBufInputStream byteBufInputStream = null; //Create an instance of composite byte buffer to hold the content chunks CompositeByteBuf content = new UnpooledByteBufAllocator(true).compositeBuffer(); try {//ww w . j a v a 2s . co m //Check whether the pipe is filled with HTTP content chunks up to last chunk while (pipe.isEmpty() || !pipe.isLastChunkAdded()) { Thread.sleep(10); } //Get a clone of content chunk queue from the pipe BlockingQueue<ContentChunk> clonedContent = pipe.getClonedContentQueue(); //Traverse through the http content chunks and create the composite buffer while (true) { if (!clonedContent.isEmpty()) { //Retrieve the HTTP content chunk from cloned queue HttpContent chunk = ((HTTPContentChunk) clonedContent.take()).getHttpContent(); // Append the content of the chunk to the composite buffer if (chunk.content().isReadable()) { chunk.retain(); content.addComponent(chunk.content()); content.writerIndex(content.writerIndex() + chunk.content().readableBytes()); } } else { //When all the content chunks are read, break from the loop break; } } } catch (Exception e) { log.error("Error occurred during conversion from CarbonMessage", e); } //Return the composite buffer return content; }