use of io.netty.buffer.ByteBufHolder in project riposte by Nike-Inc.
the class HttpUtils method convertContentChunksToRawBytes.
@Nullable
public static byte[] convertContentChunksToRawBytes(@Nullable Collection<HttpContent> contentChunks) {
if (contentChunks == null || contentChunks.size() == 0) {
return null;
}
ByteBuf[] chunkByteBufs = contentChunks.stream().map(ByteBufHolder::content).toArray(ByteBuf[]::new);
int totalNumBytes = contentChunks.stream().mapToInt(chunk -> chunk.content().readableBytes()).sum();
if (totalNumBytes == 0) {
return null;
}
byte[] comboBytes = new byte[totalNumBytes];
int bytesWrittenSoFar = 0;
for (ByteBuf chunk : chunkByteBufs) {
int numBytesInThisChunk = chunk.readableBytes();
chunk.getBytes(chunk.readerIndex(), comboBytes, bytesWrittenSoFar, chunk.readableBytes());
bytesWrittenSoFar += numBytesInThisChunk;
}
return comboBytes;
}
use of io.netty.buffer.ByteBufHolder in project netty-socketio by mrniko.
the class WebSocketTransport method channelRead.
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof CloseWebSocketFrame) {
ctx.channel().writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE);
} else if (msg instanceof BinaryWebSocketFrame || msg instanceof TextWebSocketFrame) {
ByteBufHolder frame = (ByteBufHolder) msg;
ClientHead client = clientsBox.get(ctx.channel());
if (client == null) {
log.debug("Client with was already disconnected. Channel closed!");
ctx.channel().close();
frame.release();
return;
}
ctx.pipeline().fireChannelRead(new PacketsMessage(client, frame.content(), Transport.WEBSOCKET));
frame.release();
} else if (msg instanceof FullHttpRequest) {
FullHttpRequest req = (FullHttpRequest) msg;
QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
String path = queryDecoder.path();
List<String> transport = queryDecoder.parameters().get("transport");
List<String> sid = queryDecoder.parameters().get("sid");
if (transport != null && NAME.equals(transport.get(0))) {
try {
if (!configuration.getTransports().contains(Transport.WEBSOCKET)) {
log.debug("{} transport not supported by configuration.", Transport.WEBSOCKET);
ctx.channel().close();
return;
}
if (sid != null && sid.get(0) != null) {
final UUID sessionId = UUID.fromString(sid.get(0));
handshake(ctx, sessionId, path, req);
} else {
ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get();
// first connection
handshake(ctx, client.getSessionId(), path, req);
}
} finally {
req.release();
}
} else {
ctx.fireChannelRead(msg);
}
} else {
ctx.fireChannelRead(msg);
}
}
use of io.netty.buffer.ByteBufHolder in project netty by netty.
the class MessageAggregator method decode.
@Override
protected void decode(final ChannelHandlerContext ctx, I msg, List<Object> out) throws Exception {
assert aggregating;
if (isStartMessage(msg)) {
handlingOversizedMessage = false;
if (currentMessage != null) {
currentMessage.release();
currentMessage = null;
throw new MessageAggregationException();
}
@SuppressWarnings("unchecked") S m = (S) msg;
// Send the continue response if necessary (e.g. 'Expect: 100-continue' header)
// Check before content length. Failing an expectation may result in a different response being sent.
Object continueResponse = newContinueResponse(m, maxContentLength, ctx.pipeline());
if (continueResponse != null) {
// Cache the write listener for reuse.
ChannelFutureListener listener = continueResponseWriteListener;
if (listener == null) {
continueResponseWriteListener = listener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
ctx.fireExceptionCaught(future.cause());
}
}
};
}
// Make sure to call this before writing, otherwise reference counts may be invalid.
boolean closeAfterWrite = closeAfterContinueResponse(continueResponse);
handlingOversizedMessage = ignoreContentAfterContinueResponse(continueResponse);
final ChannelFuture future = ctx.writeAndFlush(continueResponse).addListener(listener);
if (closeAfterWrite) {
future.addListener(ChannelFutureListener.CLOSE);
return;
}
if (handlingOversizedMessage) {
return;
}
} else if (isContentLengthInvalid(m, maxContentLength)) {
// if content length is set, preemptively close if it's too large
invokeHandleOversizedMessage(ctx, m);
return;
}
if (m instanceof DecoderResultProvider && !((DecoderResultProvider) m).decoderResult().isSuccess()) {
O aggregated;
if (m instanceof ByteBufHolder) {
aggregated = beginAggregation(m, ((ByteBufHolder) m).content().retain());
} else {
aggregated = beginAggregation(m, EMPTY_BUFFER);
}
finishAggregation0(aggregated);
out.add(aggregated);
return;
}
// A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
CompositeByteBuf content = ctx.alloc().compositeBuffer(maxCumulationBufferComponents);
if (m instanceof ByteBufHolder) {
appendPartialContent(content, ((ByteBufHolder) m).content());
}
currentMessage = beginAggregation(m, content);
} else if (isContentMessage(msg)) {
if (currentMessage == null) {
// until the begging of the next request/response.
return;
}
// Merge the received chunk into the content of the current message.
CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();
@SuppressWarnings("unchecked") final C m = (C) msg;
// Handle oversized message.
if (content.readableBytes() > maxContentLength - m.content().readableBytes()) {
// By convention, full message type extends first message type.
@SuppressWarnings("unchecked") S s = (S) currentMessage;
invokeHandleOversizedMessage(ctx, s);
return;
}
// Append the content of the chunk.
appendPartialContent(content, m.content());
// Give the subtypes a chance to merge additional information such as trailing headers.
aggregate(currentMessage, m);
final boolean last;
if (m instanceof DecoderResultProvider) {
DecoderResult decoderResult = ((DecoderResultProvider) m).decoderResult();
if (!decoderResult.isSuccess()) {
if (currentMessage instanceof DecoderResultProvider) {
((DecoderResultProvider) currentMessage).setDecoderResult(DecoderResult.failure(decoderResult.cause()));
}
last = true;
} else {
last = isLastContentMessage(m);
}
} else {
last = isLastContentMessage(m);
}
if (last) {
finishAggregation0(currentMessage);
// All done
out.add(currentMessage);
currentMessage = null;
}
} else {
throw new MessageAggregationException();
}
}
use of io.netty.buffer.ByteBufHolder in project netty by netty.
the class MessageAggregatorTest method testReadFlowManagement.
@SuppressWarnings("unchecked")
@Test
public void testReadFlowManagement() throws Exception {
ReadCounter counter = new ReadCounter();
ByteBufHolder first = message("first");
ByteBufHolder chunk = message("chunk");
ByteBufHolder last = message("last");
MockMessageAggregator agg = spy(MockMessageAggregator.class);
when(agg.isStartMessage(first)).thenReturn(true);
when(agg.isContentMessage(chunk)).thenReturn(true);
when(agg.isContentMessage(last)).thenReturn(true);
when(agg.isLastContentMessage(last)).thenReturn(true);
EmbeddedChannel embedded = new EmbeddedChannel(counter, agg);
embedded.config().setAutoRead(false);
assertFalse(embedded.writeInbound(first));
assertFalse(embedded.writeInbound(chunk));
assertTrue(embedded.writeInbound(last));
// 2 reads issued from MockMessageAggregator
assertEquals(3, counter.value);
// 1 read issued from EmbeddedChannel constructor
ByteBufHolder all = new DefaultByteBufHolder(Unpooled.wrappedBuffer(first.content().retain(), chunk.content().retain(), last.content().retain()));
ByteBufHolder out = embedded.readInbound();
assertEquals(all, out);
assertTrue(all.release() && out.release());
assertFalse(embedded.finish());
}
use of io.netty.buffer.ByteBufHolder in project netty by netty.
the class DnsAddressDecoder method decodeAddress.
/**
* Decodes an {@link InetAddress} from an A or AAAA {@link DnsRawRecord}.
*
* @param record the {@link DnsRecord}, most likely a {@link DnsRawRecord}
* @param name the host name of the decoded address
* @param decodeIdn whether to convert {@code name} to a unicode host name
*
* @return the {@link InetAddress}, or {@code null} if {@code record} is not a {@link DnsRawRecord} or
* its content is malformed
*/
static InetAddress decodeAddress(DnsRecord record, String name, boolean decodeIdn) {
if (!(record instanceof DnsRawRecord)) {
return null;
}
final ByteBuf content = ((ByteBufHolder) record).content();
final int contentLen = content.readableBytes();
if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) {
return null;
}
final byte[] addrBytes = new byte[contentLen];
content.getBytes(content.readerIndex(), addrBytes);
try {
return InetAddress.getByAddress(decodeIdn ? IDN.toUnicode(name) : name, addrBytes);
} catch (UnknownHostException e) {
// Should never reach here.
throw new Error(e);
}
}
Aggregations