List of usage examples for io.netty.buffer ByteBuf readerIndex
public abstract int readerIndex();
From source file:com.facebook.nifty.core.ThriftFrameDecoder.java
License:Apache License
private TTransport tryDecodeUnframedMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws TException { // Perform a trial decode, skipping through // the fields, to see whether we have an entire message available. int messageLength = 0; int messageStartReaderIndex = buffer.readerIndex(); try {//from w w w . j a v a 2 s . co m TNiftyTransport decodeAttemptTransport = new TNiftyTransport(ctx.channel(), buffer); TProtocol inputProtocol = this.inputProtocolFactory.getProtocol(decodeAttemptTransport); // Skip through the message inputProtocol.readMessageBegin(); TProtocolUtil.skip(inputProtocol, TType.STRUCT); inputProtocol.readMessageEnd(); messageLength = buffer.readerIndex() - messageStartReaderIndex; } catch (IndexOutOfBoundsException e) { // No complete message was decoded: ran out of bytes return null; } finally { if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) { ctx.fireExceptionCaught( new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded")); } buffer.readerIndex(messageStartReaderIndex); } if (messageLength <= 0) { return null; } // We have a full message in the read buffer, slice it off ByteBuf messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength); ThriftMessage message = new ThriftMessage(messageBuffer, ThriftTransportType.UNFRAMED); buffer.readerIndex(messageStartReaderIndex + messageLength); return new TNiftyTransport(ctx.channel(), message); }
From source file:com.flysoloing.learning.network.netty.portunification.PortUnificationServerHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // Will use the first five bytes to detect a protocol. if (in.readableBytes() < 5) { return;//from w ww .j a v a 2s . c o m } if (isSsl(in)) { enableSsl(ctx); } else { final int magic1 = in.getUnsignedByte(in.readerIndex()); final int magic2 = in.getUnsignedByte(in.readerIndex() + 1); if (isGzip(magic1, magic2)) { enableGzip(ctx); } else if (isHttp(magic1, magic2)) { switchToHttp(ctx); } else if (isFactorial(magic1)) { switchToFactorial(ctx); } else { // Unknown protocol; discard everything and close the connection. in.clear(); ctx.close(); } } }
From source file:com.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java
License:Apache License
/** * Helper method to parse the number at the beginning of the buffer * /*from w ww.j ava 2s. c om*/ * @param buffer Buffer to read * @return The number found at the beginning of the buffer */ private int parseCurrentNumber(ByteBuf buffer) { int number = 0; int readerIndex = buffer.readerIndex(); byte b = 0; while (true) { if (!buffer.isReadable()) return Integer.MIN_VALUE; b = buffer.readByte(); if (Character.isDigit(b)) { number = number * 10 + (int) (b - '0'); readerIndex++; } else { buffer.readerIndex(readerIndex); break; } } return number; }
From source file:com.github.lburgazzoli.quickfixj.transport.netty.codec.NettyMessageDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (m_msgLength == -1) { if (in.readableBytes() >= FIXCodecHelper.MSG_MIN_BYTES) { int ridx = in.readerIndex(); int bssohidx = in.indexOf(ridx, ridx + 12, FIXCodecHelper.BYTE_SOH); int blsohidx = in.indexOf(ridx + 12, ridx + 20, FIXCodecHelper.BYTE_SOH); // check the existence of: // - BeginString 8= // - BodyLength 9= if (in.getByte(ridx) == FIXCodecHelper.BYTE_BEGIN_STRING && in.getByte(ridx + 1) == FIXCodecHelper.BYTE_EQUALS && in.getByte(bssohidx + 1) == FIXCodecHelper.BYTE_BODY_LENGTH && in.getByte(bssohidx + 2) == FIXCodecHelper.BYTE_EQUALS) { int bodyLength = 0; for (int i = bssohidx + 3; i < blsohidx; i++) { bodyLength *= 10;//w w w .j a va 2 s . co m bodyLength += (in.getByte(i) - '0'); } m_msgLength = 1 + bodyLength + (blsohidx - ridx) + FIXCodecHelper.MSG_CSUM_LEN; } else { throw new Error("Unexpected state (header)"); } } } if (m_msgLength != -1 && in.readableBytes() >= m_msgLength) { if (in.readableBytes() >= m_msgLength) { byte[] rv = new byte[m_msgLength]; in.readBytes(rv); //TODO: validate checksum out.add(rv); m_msgLength = -1; } else { throw new Error("Unexpected state (body)"); } } }
From source file:com.github.lburgazzoli.quickfixj.transport.netty.codec.NettyRegExMessageDecoder.java
License:Apache License
/** * * @param in/* ww w .jav a 2s .c o m*/ * @return * @throws Exception */ private Object doDecodeBuffer(ByteBuf in) throws Exception { byte[] rv = null; int rindex = in.readerIndex(); String bs = in.toString(); Matcher mh = FIXCodecHelper.getCodecMatcher(bs); boolean reset = true; in.readerIndex(rindex); if (mh.find() && (mh.groupCount() == 4)) { int offset = mh.start(0); int size = mh.end(4) - mh.start(0) + 1; rv = new byte[size]; reset = false; in.readBytes(rv, offset, size); in.readerIndex(mh.end(4) + 1); } if (reset) { in.readerIndex(rindex); } return rv; }
From source file:com.github.nettybook.ch0.LoggingHandler.java
License:Apache License
/** * Appends the prettifies multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified * {@link StringBuilder}./* w w w .j a va2 s . co m*/ */ protected static void appendHexDump(StringBuilder dump, ByteBuf buf) { dump.append(NEWLINE + " +-------------------------------------------------+" + NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" + NEWLINE + "+--------+-------------------------------------------------+----------------+"); final int startIndex = buf.readerIndex(); final int endIndex = buf.writerIndex(); final int length = endIndex - startIndex; final int fullRows = length >>> 4; final int remainder = length & 0xF; // Dump the rows which have 16 bytes. for (int row = 0; row < fullRows; row++) { int rowStartIndex = row << 4; // Per-row prefix. appendHexDumpRowPrefix(dump, row, rowStartIndex); // Hex dump int rowEndIndex = rowStartIndex + 16; for (int j = rowStartIndex; j < rowEndIndex; j++) { dump.append(BYTE2HEX[buf.getUnsignedByte(j)]); } dump.append(" |"); // ASCII dump for (int j = rowStartIndex; j < rowEndIndex; j++) { dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]); } dump.append('|'); } // Dump the last row which has less than 16 bytes. if (remainder != 0) { int rowStartIndex = fullRows << 4; appendHexDumpRowPrefix(dump, fullRows, rowStartIndex); // Hex dump int rowEndIndex = rowStartIndex + remainder; for (int j = rowStartIndex; j < rowEndIndex; j++) { dump.append(BYTE2HEX[buf.getUnsignedByte(j)]); } dump.append(HEXPADDING[remainder]); dump.append(" |"); // Ascii dump for (int j = rowStartIndex; j < rowEndIndex; j++) { dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]); } dump.append(BYTEPADDING[remainder]); dump.append('|'); } dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+"); }
From source file:com.github.sylvek.wsmqttfwd.decoder.ConnectDecoder.java
License:Open Source License
@Override public ConnectMessage decode(AttributeMap ctx, ByteBuf in) throws UnsupportedEncodingException { in.resetReaderIndex();//from www .j a va 2 s.co m //Common decoding part ConnectMessage message = new ConnectMessage(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex(); return null; } int remainingLength = message.getRemainingLength(); int start = in.readerIndex(); int protocolNameLen = in.readUnsignedShort(); byte[] encProtoName; String protoName; Attribute<Integer> versionAttr = ctx.attr(PROTOCOL_VERSION); switch (protocolNameLen) { case 6: //MQTT version 3.1 "MQIsdp" //ProtocolName 8 bytes or 6 bytes if (in.readableBytes() < 10) { in.resetReaderIndex(); return null; } encProtoName = new byte[6]; in.readBytes(encProtoName); protoName = new String(encProtoName, "UTF-8"); if (!"MQIsdp".equals(protoName)) { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid protoName: " + protoName); } message.setProtocolName(protoName); versionAttr.set((int) Utils.VERSION_3_1); break; case 4: //MQTT version 3.1.1 "MQTT" //ProtocolName 6 bytes if (in.readableBytes() < 8) { in.resetReaderIndex(); return null; } encProtoName = new byte[4]; in.readBytes(encProtoName); protoName = new String(encProtoName, "UTF-8"); if (!"MQTT".equals(protoName)) { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid protoName: " + protoName); } message.setProtocolName(protoName); versionAttr.set((int) Utils.VERSION_3_1_1); break; default: //protocol broken throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen); } //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1) message.setProtocolVersion(in.readByte()); if (message.getProtocolVersion() == Utils.VERSION_3_1_1) { //if 3.1.1, check the flags (dup, retain and qos == 0) if (message.isDupFlag() || message.isRetainFlag() || message.getQos() != AbstractMessage.QOSType.MOST_ONE) { throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0"); } //check if this is another connect from the same client on the same session Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS); Boolean alreadyConnected = connectAttr.get(); if (alreadyConnected == null) { //never set connectAttr.set(true); } else if (alreadyConnected) { throw new CorruptedFrameException("Received a second CONNECT on the same network connection"); } } //Connection flag byte connFlags = in.readByte(); if (message.getProtocolVersion() == Utils.VERSION_3_1_1) { if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0 throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0"); } } boolean cleanSession = ((connFlags & 0x02) >> 1) == 1; boolean willFlag = ((connFlags & 0x04) >> 2) == 1; byte willQos = (byte) ((connFlags & 0x18) >> 3); if (willQos > 2) { in.resetReaderIndex(); throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos); } boolean willRetain = ((connFlags & 0x20) >> 5) == 1; boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1; boolean userFlag = ((connFlags & 0x80) >> 7) == 1; //a password is true iff user is true. if (!userFlag && passwordFlag) { in.resetReaderIndex(); throw new CorruptedFrameException( "Expected password flag to true if the user flag is true but was: " + passwordFlag); } message.setCleanSession(cleanSession); message.setWillFlag(willFlag); message.setWillQos(willQos); message.setWillRetain(willRetain); message.setPasswordFlag(passwordFlag); message.setUserFlag(userFlag); //Keep Alive timer 2 bytes //int keepAlive = Utils.readWord(in); int keepAlive = in.readUnsignedShort(); message.setKeepAlive(keepAlive); if ((remainingLength == 12 && message.getProtocolVersion() == Utils.VERSION_3_1) || (remainingLength == 10 && message.getProtocolVersion() == Utils.VERSION_3_1_1)) { return message; } //Decode the ClientID String clientID = Utils.decodeString(in); if (clientID == null) { in.resetReaderIndex(); return null; } message.setClientID(clientID); //Decode willTopic if (willFlag) { String willTopic = Utils.decodeString(in); if (willTopic == null) { in.resetReaderIndex(); return null; } message.setWillTopic(willTopic); } //Decode willMessage if (willFlag) { byte[] willMessage = Utils.readFixedLengthContent(in); if (willMessage == null) { in.resetReaderIndex(); return null; } message.setWillMessage(willMessage); } //Compatibility check with v3.0, remaining length has precedence over //the user and password flags int readed = in.readerIndex() - start; if (readed == remainingLength) { return message; } //Decode username if (userFlag) { String userName = Utils.decodeString(in); if (userName == null) { in.resetReaderIndex(); return null; } message.setUsername(userName); } readed = in.readerIndex() - start; if (readed == remainingLength) { return message; } //Decode password if (passwordFlag) { byte[] password = Utils.readFixedLengthContent(in); if (password == null) { in.resetReaderIndex(); return null; } message.setPassword(password); } return message; }
From source file:com.github.sylvek.wsmqttfwd.decoder.PublishDecoder.java
License:Open Source License
@Override public PublishMessage decode(AttributeMap ctx, ByteBuf in) throws Exception { LOG.debug("decode invoked with buffer {}", in); in.resetReaderIndex();// w w w. jav a 2 s.c o m int startPos = in.readerIndex(); //Common decoding part PublishMessage message = new PublishMessage(); if (!decodeCommonHeader(message, in)) { LOG.debug("decode ask for more data after {}", in); in.resetReaderIndex(); return null; } int remainingLength = message.getRemainingLength(); //Topic name String topic = Utils.decodeString(in); if (topic == null) { in.resetReaderIndex(); return null; } //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters. if (topic.contains("+") || topic.contains("#")) { throw new CorruptedFrameException( "Received a PUBLISH with topic containing wild card chars, topic: " + topic); } //check topic is at least one char [MQTT-4.7.3-1] if (topic.length() == 0) { throw new CorruptedFrameException("Received a PUBLISH with topic without any character"); } message.setTopicName(topic); if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) { message.setMessageID(in.readUnsignedShort()); } int stopPos = in.readerIndex(); //read the payload int payloadSize = remainingLength - (stopPos - startPos - 2) + (Utils.numBytesToEncode(remainingLength) - 1); if (in.readableBytes() < payloadSize) { in.resetReaderIndex(); return null; } ByteBuf bb = Unpooled.buffer(payloadSize); in.readBytes(bb); message.setPayload(bb.nioBuffer()); return message; }
From source file:com.github.sylvek.wsmqttfwd.decoder.SubscribeDecoder.java
License:Open Source License
@Override public SubscribeMessage decode(AttributeMap ctx, ByteBuf in) throws Exception { //Common decoding part SubscribeMessage message = new SubscribeMessage(); in.resetReaderIndex();/*w w w. j av a 2 s . co m*/ if (!decodeCommonHeader(message, 0x02, in)) { in.resetReaderIndex(); return null; } //check qos level if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) { throw new CorruptedFrameException( "Received SUBSCRIBE message with QoS other than LEAST_ONE, was: " + message.getQos()); } int start = in.readerIndex(); //read messageIDs message.setMessageID(in.readUnsignedShort()); int read = in.readerIndex() - start; while (read < message.getRemainingLength()) { decodeSubscription(in, message); read = in.readerIndex() - start; } if (message.subscriptions().isEmpty()) { throw new CorruptedFrameException("subscribe MUST have got at least 1 couple topic/QoS"); } return message; }
From source file:com.growcontrol.common.netty.JsonObjectDecoder.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception { if (this.state == ST_CORRUPTED) { in.skipBytes(in.readableBytes()); return;/* www . j av a 2 s . c om*/ } // index of next byte to process. int idx = this.idx; final int wrtIdx = in.writerIndex(); if (wrtIdx > this.maxObjectLength) { // buffer size exceeded maxObjectLength; discarding the complete buffer. in.skipBytes(in.readableBytes()); reset(); throw new TooLongFrameException( "object length exceeds " + this.maxObjectLength + ": " + wrtIdx + " bytes discarded"); } for (/* use current idx */; idx < wrtIdx; idx++) { final byte c = in.getByte(idx); if (this.state == ST_DECODING_NORMAL) { decodeByte(c, in, idx); // All opening braces/brackets have been closed. That's enough to conclude // that the JSON object/array is complete. if (this.openBraces == 0) { ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex()); if (json != null) { out.add(json); } // The JSON object/array was extracted => discard the bytes from // the input buffer. in.readerIndex(idx + 1); // Reset the object state to get ready for the next JSON object/text // coming along the byte stream. reset(); } } else if (this.state == ST_DECODING_ARRAY_STREAM) { decodeByte(c, in, idx); if (!this.insideString && (this.openBraces == 1 && c == ',' || this.openBraces == 0 && c == ']')) { // skip leading spaces. No range check is needed and the loop will terminate // because the byte at position idx is not a whitespace. for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) { in.skipBytes(1); } // skip trailing spaces. int idxNoSpaces = idx - 1; while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) { idxNoSpaces--; } ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex()); if (json != null) { out.add(json); } in.readerIndex(idx + 1); if (c == ']') { reset(); } } // JSON object/array detected. Accumulate bytes until all braces/brackets are closed. } else if (c == '{' || c == '[') { initDecoding(c); // Discard the array bracket if (this.state == ST_DECODING_ARRAY_STREAM) in.skipBytes(1); // Discard leading spaces in front of a JSON object/array. } else if (Character.isWhitespace(c)) { in.skipBytes(1); } else { this.state = ST_CORRUPTED; throw new CorruptedFrameException( "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in)); } } if (in.readableBytes() == 0) this.idx = 0; else this.idx = idx; }