List of usage examples for io.netty.buffer ByteBuf resetReaderIndex
public abstract ByteBuf resetReaderIndex();
From source file:com.mpush.netty.codec.PacketDecoder.java
License:Apache License
private void decodeFrames(ByteBuf in, List<Object> out) { if (in.readableBytes() >= Packet.HEADER_LEN) { //1.????.??frame,????,? in.markReaderIndex();//from w ww. j ava 2 s. c o m Packet packet = decodeFrame(in); if (packet != null) { out.add(packet); } else { //2.??frame,????,? in.resetReaderIndex(); } } }
From source file:com.navercorp.nbasearc.gcp.RedisDecoder.java
License:Apache License
void getFrames(ByteBuf in, List<byte[]> out) { while (true) { in.markReaderIndex();//w w w. j av a2s . c om final int stx = in.readerIndex(); if (hasFrame(in) == false) { in.resetReaderIndex(); break; } int length = in.readerIndex() - stx; byte[] readBytes = new byte[length]; in.resetReaderIndex(); in.readBytes(readBytes); out.add(readBytes); } }
From source file:com.newlandframework.avatarmq.netty.MessageObjectDecoder.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (in.readableBytes() < MessageObjectDecoder.MESSAGE_LENGTH) { return;/*from w w w. j a va2 s . c om*/ } in.markReaderIndex(); int messageLength = in.readInt(); if (messageLength < 0) { ctx.close(); } if (in.readableBytes() < messageLength) { in.resetReaderIndex(); return; } else { byte[] messageBody = new byte[messageLength]; in.readBytes(messageBody); try { Object obj = util.decode(messageBody); out.add(obj); } catch (IOException ex) { Logger.getLogger(MessageObjectDecoder.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.newlandframework.rpc.serialize.MessageDecoder.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (in.readableBytes() < MessageDecoder.MESSAGE_LENGTH) { return;//ww w .jav a 2 s .c o m } in.markReaderIndex(); int messageLength = in.readInt(); if (messageLength < 0) { ctx.close(); } if (in.readableBytes() < messageLength) { in.resetReaderIndex(); return; } else { byte[] messageBody = new byte[messageLength]; in.readBytes(messageBody); try { Object obj = util.decode(messageBody); out.add(obj); } catch (IOException ex) { Logger.getLogger(MessageDecoder.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.ns.netty.gcd.server.BigIntegerDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { System.out.println("Decoder received event"); // Wait until the length prefix is available. if (in.readableBytes() < 5) { return;// w w w . java 2 s . c o m } in.markReaderIndex(); // Check the magic number. int magicNumber = in.readUnsignedByte(); if (magicNumber != 'F') { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid magic number: " + magicNumber); } // Wait until the whole data is available. int dataLength = in.readInt(); if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } // Convert the received data into a new BigInteger. byte[] decoded = new byte[dataLength]; in.readBytes(decoded); out.add(new BigInteger(decoded)); }
From source file:com.ogarproject.ogar.server.net.PacketDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { ByteBuf buf = frame.content().order(ByteOrder.LITTLE_ENDIAN); if (buf.capacity() < 1) { // Discard empty messages return;//from ww w . j a v a2 s . c o m } buf.resetReaderIndex(); int packetId = buf.readUnsignedByte(); Packet packet = PacketRegistry.SERVERBOUND.constructPacket(packetId); if (packet == null) { throw new UnknownPacketException("Unknown packet ID: " + packetId); } OgarServer.log.finest("Received packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") from " + ctx.channel().remoteAddress()); packet.readData(buf); out.add(packet); }
From source file:com.openddal.server.mysql.MySQLProtocolDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // Make sure if the length field was received. if (in.readableBytes() < FRAME_LENGTH_FIELD_LENGTH) { // The length field was not received yet - return. // This method will be invoked again when more packets are // received and appended to the buffer. return;//from w w w.ja v a2 s . co m } // The length field is in the buffer. // Mark the current buffer position before reading the length field // because the whole frame might not be in the buffer yet. // We will reset the buffer position to the marked position if // there's not enough bytes in the buffer. in.markReaderIndex(); int frameLength = readLength(in);// in.readInt(); // Make sure if there's enough bytes in the buffer. if (in.readableBytes() < frameLength) { // The whole bytes were not received yet - return. // This method will be invoked again when more packets are // received and appended to the buffer. // Reset to the marked position to read the length field again // next time. in.resetReaderIndex(); return; } // There's enough bytes in the buffer. Read it. ByteBuf frame = in.resetReaderIndex().readSlice(frameLength + 4).retain(); // Successfully decoded a frame. Add the decoded frame. out.add(frame); }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.ConnectDecoder.java
License:Open Source License
@Override public AbstractMessage decode(AttributeMap ctx, ByteBuf in) throws UnsupportedEncodingException { in.resetReaderIndex(); //Common decoding part ConnectMessage message = new ConnectMessage(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex();//from w ww . ja va 2 s. c om return null; } int remainingLength = message.getRemainingLength(); int start = in.readerIndex(); int protocolNameLen = in.readUnsignedShort(); byte[] encProtoName; String protoName; Attribute<Integer> versionAttr = ctx.attr(MQTTDecoder.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) 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) 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.setProcotolVersion(in.readByte()); if (message.getProcotolVersion() == 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"); } } //PKMPConnection flag byte connFlags = in.readByte(); if (message.getProcotolVersion() == 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.getProcotolVersion() == VERSION_3_1) || (remainingLength == 10 && message.getProcotolVersion() == 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) { String willMessage = Utils.decodeString(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) { String password = Utils.decodeString(in); if (password == null) { in.resetReaderIndex(); return null; } message.setPassword(password); } return message; }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.MQTTDecoder.java
License:Open Source License
public AbstractMessage decode(AttributeMap ctx, ByteBuf byteBuf) throws Exception { byteBuf.markReaderIndex();/*from w w w .j ava2 s . c o m*/ if (!Utils.checkHeaderAvailability(byteBuf)) { byteBuf.resetReaderIndex(); return null; } byteBuf.resetReaderIndex(); byte messageType = Utils.readMessageType(byteBuf); DemuxDecoder decoder = m_decoderMap.get(messageType); if (decoder == null) { throw new CorruptedFrameException("Can't find any suitable decoder for message type: " + messageType); } return decoder.decode(ctx, byteBuf); }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.PublishDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { LOG.info("decode invoked with buffer {}", in); in.resetReaderIndex(); int startPos = in.readerIndex(); //Common decoding part PublishMessage message = new PublishMessage(); if (!decodeCommonHeader(message, in)) { LOG.info("decode ask for more data after {}", in); in.resetReaderIndex();/* ww w . ja v a2 s . c om*/ return; } if (Utils.isMQTT3_1_1(ctx)) { if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) { //bad protocol, if QoS=0 => DUP = 0 throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation"); } if (message.getQos() == AbstractMessage.QOSType.RESERVED) { throw new CorruptedFrameException( "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation"); } } int remainingLength = message.getRemainingLength(); //Topic name String topic = Utils.decodeString(in); if (topic == null) { in.resetReaderIndex(); return; } if (topic.contains("+") || topic.contains("#")) { throw new CorruptedFrameException( "Received a PUBLISH with topic containting wild card chars, topic: " + topic); } 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; } // byte[] b = new byte[payloadSize]; ByteBuf bb = Unpooled.buffer(payloadSize); in.readBytes(bb); message.setPayload(bb.nioBuffer()); out.add(message); }