List of usage examples for io.netty.buffer ByteBuf readerIndex
public abstract int readerIndex();
From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java
License:Apache License
/** * Reads a C-String (null terminated) from a buffer. This method will * attempt to find the null byte and read all data up to and including * the null byte. The returned String does not include the null byte. * Will throw an exception if no null byte is found and it runs out of data * in the buffer to read.//from w w w.j av a 2 s . c o m * @param buffer * @return * @throws TerminatingNullByteNotFoundException */ static public String readNullTerminatedString(ByteBuf buffer) throws TerminatingNullByteNotFoundException { // maximum possible length are the readable bytes in buffer int maxLength = buffer.readableBytes(); // if there are no readable bytes, return null if (maxLength == 0) { return null; } // the reader index is defaulted to the readerIndex int offset = buffer.readerIndex(); int zeroPos = 0; // search for NULL byte until we hit end or find it while ((zeroPos < maxLength) && (buffer.getByte(zeroPos + offset) != 0x00)) { zeroPos++; } if (zeroPos >= maxLength) { // a NULL byte was not found throw new TerminatingNullByteNotFoundException( "Terminating null byte not found after searching [" + maxLength + "] bytes"); } // at this point, we found a terminating zero String result = null; if (zeroPos > 0) { // read a new byte array byte[] bytes = new byte[zeroPos]; buffer.readBytes(bytes); try { result = new String(bytes, "ISO-8859-1"); } catch (UnsupportedEncodingException e) { logger.error("Impossible error", e); } } else { result = ""; } // at this point, we have just one more byte to skip over (the null byte) byte b = buffer.readByte(); if (b != 0x00) { logger.error("Impossible error: last byte read SHOULD have been a null byte, but was [" + b + "]"); } return result; }
From source file:com.codnos.dbgp.internal.handlers.DBGpCommandDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception { int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL); if (nullPosition < 0) return;//from w w w.j a va 2 s .c o m int length = nullPosition - in.readerIndex(); ByteBuf msgBuffer = in.readBytes(length); in.readByte(); objects.add(msgBuffer.toString(UTF_8)); msgBuffer.release(); }
From source file:com.codnos.dbgp.internal.handlers.DBGpResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception { final int length = in.readableBytes(); LOGGER.fine("got something from engine (" + length + " bytes)"); int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL); int readerIndex = in.readerIndex(); int numberOfBytes = nullPosition - readerIndex; LOGGER.fine("found nullposition on " + nullPosition + " and readerIndex is " + readerIndex + " calculated number of bytes " + numberOfBytes); if (numberOfBytes <= 0) { LOGGER.fine("not enough to read, finishing"); in.resetReaderIndex();//from w ww .ja v a2 s. com return; } if (nullPosition > length) { LOGGER.fine("have null position further than length, finishing"); in.resetReaderIndex(); return; } ByteBuf sizeBuf = in.readBytes(numberOfBytes); in.readByte(); String sizeBufAsString = sizeBuf.toString(UTF_8); int size = Integer.parseInt(sizeBufAsString); int expectedSize = sizeBuf.readableBytes() + NULL_BYTE_SIZE + size + NULL_BYTE_SIZE; if (length < expectedSize) { LOGGER.fine("don't have the whole message yet (expected " + expectedSize + "), finishing"); in.resetReaderIndex(); sizeBuf.release(); return; } ByteBuf messageBuf = in.readBytes(size); in.readByte(); objects.add(messageBuf.toString(UTF_8)); sizeBuf.release(); messageBuf.release(); }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private long parseLong(ByteBuf chars) { return parseLong(chars, chars.readerIndex() + chars.readableBytes()); }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private long parseLong(ByteBuf chars, int length) { long result = 0; for (int i = chars.readerIndex(); i < length; i++) { int digit = ((int) chars.getByte(i) & 0xF); for (int j = 0; j < length - 1 - i; j++) { digit *= 10;//from w ww . j a va 2 s . co m } result += digit; } return result; }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private Packet decodePacket(ByteBuf buffer, UUID uuid) throws IOException { if (buffer.readableBytes() < 3) { throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8)); }/*from w w w.ja v a2 s . c om*/ PacketType type = getType(buffer); int readerIndex = buffer.readerIndex() + 1; // 'null' to avoid unnecessary StringBuilder creation boolean hasData = false; StringBuilder messageId = null; for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) { if (messageId == null) { messageId = new StringBuilder(4); } byte msg = buffer.getByte(readerIndex); if (msg == Packet.SEPARATOR) { break; } if (msg != (byte) '+') { messageId.append((char) msg); } else { hasData = true; } } Long id = null; if (messageId != null && messageId.length() > 0) { id = Long.valueOf(messageId.toString()); } // 'null' to avoid unnecessary StringBuilder creation StringBuilder endpointBuffer = null; for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) { if (endpointBuffer == null) { endpointBuffer = new StringBuilder(); } byte msg = buffer.getByte(readerIndex); if (msg == Packet.SEPARATOR) { break; } endpointBuffer.append((char) msg); } String endpoint = Namespace.DEFAULT_NAME; if (endpointBuffer != null && endpointBuffer.length() > 0) { endpoint = endpointBuffer.toString(); } if (buffer.readableBytes() == readerIndex) { buffer.readerIndex(buffer.readableBytes()); } else { readerIndex += 1; buffer.readerIndex(readerIndex); } Packet packet = new Packet(type); packet.setEndpoint(endpoint); if (id != null) { packet.setId(id); if (hasData) { packet.setAck(Packet.ACK_DATA); } else { packet.setAck(true); } } switch (type) { case ERROR: { if (!buffer.isReadable()) { break; } String[] pieces = buffer.toString(CharsetUtil.UTF_8).split("\\+"); if (pieces.length > 0 && pieces[0].trim().length() > 0) { ErrorReason reason = ErrorReason.valueOf(Integer.valueOf(pieces[0])); packet.setReason(reason); if (pieces.length > 1) { ErrorAdvice advice = ErrorAdvice.valueOf(Integer.valueOf(pieces[1])); packet.setAdvice(advice); } } break; } case MESSAGE: { if (buffer.isReadable()) { packet.setData(buffer.toString(CharsetUtil.UTF_8)); } else { packet.setData(""); } break; } case EVENT: { ByteBufInputStream in = new ByteBufInputStream(buffer); Event event = jsonSupport.readValue(in, Event.class); packet.setName(event.getName()); if (event.getArgs() != null) { packet.setArgs(event.getArgs()); } break; } case JSON: { ByteBufInputStream in = new ByteBufInputStream(buffer); JsonObject obj = jsonSupport.readValue(in, JsonObject.class); if (obj != null) { packet.setData(obj.getObject()); } else { in.reset(); Object object = jsonSupport.readValue(in, Object.class); packet.setData(object); } break; } case CONNECT: { if (buffer.isReadable()) { packet.setQs(buffer.toString(CharsetUtil.UTF_8)); } break; } case ACK: { if (!buffer.isReadable()) { break; } boolean validFormat = true; int plusIndex = -1; for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) { byte dataChar = buffer.getByte(i); if (!Character.isDigit(dataChar)) { if (dataChar == '+') { plusIndex = i; break; } else { validFormat = false; break; } } } if (!validFormat) { break; } if (plusIndex == -1) { packet.setAckId(parseLong(buffer)); break; } else { packet.setAckId(parseLong(buffer, plusIndex)); buffer.readerIndex(plusIndex + 1); ByteBufInputStream in = new ByteBufInputStream(buffer); AckCallback<?> callback = ackManager.getCallback(uuid, packet.getAckId()); AckArgs args = jsonSupport.readAckArgs(in, callback); packet.setArgs(args.getArgs()); } break; } case DISCONNECT: case HEARTBEAT: case NOOP: break; } buffer.readerIndex(buffer.readerIndex() + buffer.readableBytes()); return packet; }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private PacketType getType(ByteBuf buffer) { int typeId = buffer.getByte(buffer.readerIndex()) & 0xF; if (typeId >= PacketType.VALUES.length || buffer.getByte(buffer.readerIndex() + 1) != Packet.SEPARATOR) { throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8)); }//from w w w . j a v a 2 s . c o m return PacketType.valueOf(typeId); }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
public Packet decodePackets(ByteBuf buffer, UUID uuid) throws IOException { if (isCurrentDelimiter(buffer, buffer.readerIndex())) { buffer.readerIndex(buffer.readerIndex() + Packet.DELIMITER_BYTES.length); Integer len = extractLength(buffer); int startIndex = buffer.readerIndex(); ByteBuf frame = buffer.slice(startIndex, len); Packet packet = decodePacket(frame, uuid); buffer.readerIndex(startIndex + len); return packet; } else {/*from www .j av a 2 s.c o m*/ Packet packet = decodePacket(buffer, uuid); return packet; } }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private Integer extractLength(ByteBuf buffer) { int len = (int) parseLengthHeader(buffer); // scan utf8 symbols if needed if (buffer.capacity() > buffer.readerIndex() + len && !isCurrentDelimiter(buffer, buffer.readerIndex() + len)) { int index = charsScanner.findTailIndex(buffer, buffer.readerIndex(), buffer.capacity(), len); len = index - buffer.readerIndex(); }//ww w . j a v a 2s . co m return len; }
From source file:com.corundumstudio.socketio.parser.Decoder.java
License:Apache License
private long parseLengthHeader(ByteBuf buffer) { int delimiterIndex = delimiterIndexOf(buffer, buffer.readerIndex(), buffer.readableBytes()); if (delimiterIndex == -1) { throw new DecoderException("Can't find tail delimiter"); }// w ww . j a v a 2s .co m long len = parseLong(buffer, delimiterIndex); buffer.readerIndex(delimiterIndex + Packet.DELIMITER_BYTES.length); return len; }