List of usage examples for io.netty.buffer ByteBuf markReaderIndex
public abstract ByteBuf markReaderIndex();
From source file:com.feihong.newzxclient.tcp.IntLengthDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // Wait until the length prefix is available. if (in.readableBytes() < 4) { //String strError = String.format("Read length data error, in.readableBytes(): %d, length: %d", in.readableBytes(), 4); //writeLog(strError); return;/*from w w w. j a v a2 s .c o m*/ } in.markReaderIndex(); // Wait until the whole data is available. int dataLength = in.readInt(); if (in.readableBytes() < dataLength) { //String strError = String.format("Read length data error, in.readableBytes(): %d, length: %d", in.readableBytes(), dataLength + 4); //writeLog(strError); in.resetReaderIndex(); return; } // Convert the received data into a new BigInteger. byte[] decoded = new byte[dataLength]; in.readBytes(decoded); try { Msg.CommonMessage commonMessage = Msg.CommonMessage.parseFrom(decoded); out.add(commonMessage); } catch (InvalidProtocolBufferException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { Command c = null;/*from w w w. jav a 2 s .c om*/ do { in.markReaderIndex(); c = parse(in); if (c == null) { in.resetReaderIndex(); return; } out.add(c); } while (in.isReadable()); // Try to take advantage of pipelining if it is being used }
From source file:com.github.jrialland.ajpclient.impl.handlers.AjpMessagesHandler.java
License:Apache License
protected Long readHeaders(final ChannelHandlerContext ctx, final ByteBuf in) throws Exception { final int statusCode = in.readUnsignedShort(); final String statusMessage = readString(in); final int numHeaders = in.readUnsignedShort(); if (getLog().isDebugEnabled()) { getLog().debug(" | HTTP/1.1 " + statusCode + " " + statusMessage); }//from w ww. jav a 2 s.co m Long expected = null; final List<Header> headers = new ArrayList<Header>(numHeaders); for (int i = 0; i < numHeaders; i++) { in.markReaderIndex(); final int code = in.readUnsignedShort(); String headerName = ResponseHeader.getHeader(code); if (headerName == null) { in.resetReaderIndex(); headerName = readString(in); } final String value = readString(in); if (getLog().isDebugEnabled()) { getLog().debug(" | " + headerName + ": " + value); } if (headerName.equalsIgnoreCase("Content-Length")) { expected = Long.parseLong(value); } headers.add(new Header(headerName, value)); } getCallback(ctx.channel()).handleSendHeadersMessage(statusCode, statusMessage, headers); return expected; }
From source file:com.github.jrialland.ajpclient.impl.handlers.AjpMessagesHandler.java
License:Apache License
protected String readString(final ByteBuf in) { in.markReaderIndex(); final int b0 = in.readUnsignedByte(); if (b0 == 0xff) { return null; }//from w w w. j av a 2 s. co m in.resetReaderIndex(); final int length = in.readUnsignedShort(); final byte[] data = new byte[length]; in.readBytes(data); // skip trailing \0 in.readByte(); return new String(data); }
From source file:com.github.jrialland.ajpclient.impl.handlers.OutgoingFramesLogger.java
License:Apache License
@Override public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception { if (msg == null) { getLog().debug(">>> (null)"); } else if (msg instanceof ByteBuf) { final ByteBuf buf = (ByteBuf) msg; buf.markReaderIndex(); final byte[] data = new byte[buf.readableBytes()]; buf.readBytes(data);//from ww w . j a v a 2s . co m getLog().debug(">>> " + bytesToHex(data)); buf.resetReaderIndex(); } else { getLog().debug(">>> " + msg.toString()); } // pass to the next handler in the chain super.write(ctx, msg, promise); }
From source file:com.heliosapm.utils.buffer.BufferManager.java
License:Apache License
/** * Reads a UTF string from the passed ByteBuff * @param offset int The offset in the buffer to read from * @param in The ByteBuf to read from/*from w w w. j ava 2s. com*/ * @return the read string */ public final static String readUTF(final int offset, final ByteBuf in) { try { in.markReaderIndex(); in.readerIndex(offset); return readUTF(in); } finally { in.resetReaderIndex(); } }
From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceRconPacketDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { final String separator = "================================================================================================="; //TODO: Move all code logic below to SourceRconPacketBuilder log.debug(separator);/* w w w . jav a 2s. c o m*/ log.debug(" ({}) DECODING INCOMING DATA : Bytes Received = {} {}", index.incrementAndGet(), in.readableBytes(), index.get() > 1 ? "[Continuation]" : ""); log.debug(separator); String desc = StringUtils.rightPad("Minimum allowable size?", PAD_SIZE); //Verify we have the minimum allowable size if (in.readableBytes() < 14) { log.debug(" [ ] {} = NO (Actual Readable Bytes: {})", desc, in.readableBytes()); return; } log.debug(" [x] {} = YES (Actual Readable Bytes: {})", desc, in.readableBytes()); //Reset if this happens to be not a valid source rcon packet in.markReaderIndex(); //Read and Verify size desc = StringUtils.rightPad("Bytes received at least => than the \"declared\" size?", PAD_SIZE); int size = in.readIntLE(); int readableBytes = in.readableBytes(); if (readableBytes < size) { log.debug(" [ ] {} = NO (Declared Size: {}, Actual Bytes Read: {})", desc, readableBytes, size); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Declared Size: {}, Actual Bytes Read: {})", desc, readableBytes, size); //Read and verify request id desc = StringUtils.rightPad("Request Id within the valid range?", PAD_SIZE); int id = in.readIntLE(); if (!(id == -1 || id == SourceRconUtil.RCON_TERMINATOR_RID || SourceRconUtil.isValidRequestId(id))) { log.debug(" [ ] {} = NO (Actual: {})", desc, id); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Actual: {})", desc, id); //Read and verify request type desc = StringUtils.rightPad("Valid response type?", PAD_SIZE); int type = in.readIntLE(); if (get(type) == null) { log.debug(" [ ] {} = NO (Actual: {})", desc, type); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Actual: {} = {})", desc, type, SourceRconResponseType.get(type)); //Read and verify body desc = StringUtils.rightPad("Contains Body?", PAD_SIZE); int bodyLength = in.bytesBefore((byte) 0); String body = StringUtils.EMPTY; if (bodyLength <= 0) log.debug(" [ ] {} = NO", desc); else { body = in.readCharSequence(bodyLength, StandardCharsets.UTF_8).toString(); log.debug(" [x] {} = YES (Length: {}, Body: {})", desc, bodyLength, StringUtils.replaceAll(StringUtils.truncate(body, 30), "\n", "\\\\n")); } //Peek at the last two bytes and verify that they are null-bytes byte bodyTerminator = in.getByte(in.readerIndex()); byte packetTerminator = in.getByte(in.readerIndex() + 1); desc = StringUtils.rightPad("Contains TWO null-terminating bytes at the end?", PAD_SIZE); //Make sure the last two bytes are NULL bytes (request id: 999 is reserved for split packet responses) if ((bodyTerminator != 0 || packetTerminator != 0) && (id == SourceRconUtil.RCON_TERMINATOR_RID)) { log.debug("Skipping {} bytes", in.readableBytes()); in.skipBytes(in.readableBytes()); return; } else if (bodyTerminator != 0 || packetTerminator != 0) { log.debug(" [ ] {} = NO (Actual: Body Terminator = {}, Packet Terminator = {})", desc, bodyTerminator, packetTerminator); in.resetReaderIndex(); return; } else { log.debug(" [x] {} = YES (Actual: Body Terminator = {}, Packet Terminator = {})", desc, bodyTerminator, packetTerminator); //All is good, skip the last two bytes if (in.readableBytes() >= 2) in.skipBytes(2); } //At this point, we can now construct a packet log.debug(" [x] Status: PASS (Size = {}, Id = {}, Type = {}, Remaining Bytes = {}, Body Size = {})", size, id, type, in.readableBytes(), bodyLength); log.debug(separator); //Reset the index index.set(0); //Construct the response packet and send to the next handlers SourceRconResponsePacket responsePacket; //Did we receive a terminator packet? if (this.terminatingPacketsEnabled && id == SourceRconUtil.RCON_TERMINATOR_RID && StringUtils.isBlank(body)) { responsePacket = new SourceRconTermResponsePacket(); } else { responsePacket = SourceRconPacketBuilder.getResponsePacket(type); } if (responsePacket != null) { responsePacket.setSize(size); responsePacket.setId(id); responsePacket.setType(type); responsePacket.setBody(body); log.debug( "Decode Complete. Passing response for request id : '{}' to the next handler. Remaining bytes ({})", id, in.readableBytes()); out.add(responsePacket); } }
From source file:com.ibasco.agql.protocols.valve.source.query.SourcePacketBuilder.java
License:Open Source License
@Override public <T extends SourceServerPacket> T construct(ByteBuf data) { //Mark Index// w w w. j av a2 s . c om data.markReaderIndex(); try { //Reset the index data.readerIndex(0); //Verify size if (data.readableBytes() < 5) throw new IllegalStateException( "Cannot continue processing buffer with less than or equal to 4 bytes"); //Read protocol header int protocolHeader = data.readIntLE(); //Check if this is a split packet if (protocolHeader == 0xFFFFFFFE) throw new IllegalStateException("Cannot construct a response from a partial/split packet."); //Verify that we have a valid header if (protocolHeader != 0xFFFFFFFF) throw new IllegalStateException("Protocol header not supported."); //Read packet header byte packetHeader = data.readByte(); //Read payload byte[] payload = new byte[data.readableBytes()]; data.readBytes(payload); //Verify if packet header is valid SourceServerPacket packet = createResponsePacketFromHeader(packetHeader); //If packet is empty, means the supplied packet header is not supported if (packet == null) return null; packet.setProtocolHeader(ByteUtils.byteArrayFromInteger(protocolHeader)); packet.setHeader(packetHeader); packet.setPayload(payload); return (T) packet; } finally { data.resetReaderIndex(); } }
From source file:com.ibasco.agql.protocols.valve.source.query.SourceRconPacketBuilder.java
License:Open Source License
@SuppressWarnings("unchecked") @Override//from ww w . j a v a2 s . com public <T extends SourceRconPacket> T construct(ByteBuf data) { try { if (data.readableBytes() < 14) { log.warn("Packet is less than 10 bytes. Unsupported packet."); if (log.isDebugEnabled()) log.debug("Unrecognized Packet: \n{}", ByteBufUtil.prettyHexDump(data)); return null; } //Remember the reader index data.markReaderIndex(); //Read from the listen data.readerIndex(0); int size = data.readIntLE(); int id = data.readIntLE(); int type = data.readIntLE(); String body = data.readCharSequence(data.readableBytes() - 2, StandardCharsets.UTF_8).toString(); SourceRconResponsePacket packet = getResponsePacket(type); if (packet != null) { //Ok, we have a valid response packet. Lets keep reading. packet.setId(id); packet.setSize(size); packet.setType(type); packet.setBody(body); return (T) packet; } } finally { //Reset the index data.resetReaderIndex(); } return null; }
From source file:com.ibasco.agql.protocols.valve.steam.master.MasterServerPacketBuilder.java
License:Open Source License
@Override public <T extends MasterServerPacket> T construct(ByteBuf data) { //Mark Index/*from www. ja v a 2s . c o m*/ data.markReaderIndex(); try { //Reset the index data.readerIndex(0); //Verify size if (data.readableBytes() <= 6) throw new IllegalStateException( "Cannot continue processing buffer with less than or equal to 6 bytes"); //Read header byte[] header = new byte[6]; data.readBytes(header); //Read payload byte[] payload = new byte[data.readableBytes()]; data.readBytes(payload); //Verify if packet header is valid MasterServerResponsePacket packet = new MasterServerResponsePacket(); packet.setHeader(header); packet.setPayload(payload); return (T) packet; } finally { data.resetReaderIndex(); } }