List of usage examples for io.netty.buffer ByteBuf resetReaderIndex
public abstract ByteBuf resetReaderIndex();
From source file:org.dna.mqtt.moquette.parser.netty.PublishDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { if (log.isTraceEnabled()) { log.trace("decode invoked with buffer {}", in); }//from ww w .ja v a 2 s .c om in.resetReaderIndex(); int startPos = in.readerIndex(); //Common decoding part PublishMessage message = new PublishMessage(); if (!decodeCommonHeader(message, in)) { if (log.isDebugEnabled()) { log.debug("decode ask for more data after {}", in); } in.resetReaderIndex(); 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); }
From source file:org.dna.mqtt.moquette.parser.netty.SubscribeDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { //Common decoding part SubscribeMessage message = new SubscribeMessage(); in.resetReaderIndex(); if (!decodeCommonHeader(message, 0x02, in)) { in.resetReaderIndex();//from www .j a va 2 s. c om return; } //check qos level if (message.getQos() != 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 readed = in.readerIndex() - start; while (readed < message.getRemainingLength()) { decodeSubscription(in, message); readed = in.readerIndex() - start; } if (message.subscriptions().isEmpty()) { throw new CorruptedFrameException("subscribe MUST have got at least 1 couple topic/QoS"); } out.add(message); }
From source file:org.evilco.network.rcon.common.codec.FrameCodec.java
License:Apache License
/** * {@inheritDoc}/* w ww . jav a 2 s . c om*/ */ @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> objects) throws Exception { // set order byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN); // read all available packets while (byteBuf.readableBytes() >= 4) { // log getLogger().trace("Decoding frame with maximal size of " + byteBuf.readableBytes() + " bytes."); // mark reader index byteBuf.markReaderIndex(); // read length int length = byteBuf.readInt(); // log getLogger().trace("Detected frame length of " + length + " bytes."); // check whether enough data is available if (length > byteBuf.readableBytes()) { // log getLogger().debug("There are only " + byteBuf.readableBytes() + " out of " + length + " bytes available. Skipping frame until more data is available."); // reset buffer byteBuf.resetReaderIndex(); // exit loop break; } // log getLogger().trace("Frame seems to be complete reading data."); // construct buffer ByteBuf packetBuffer = channelHandlerContext.alloc().buffer(length); // read data byteBuf.readBytes(packetBuffer, length); // add to list objects.add(packetBuffer); // log getLogger().trace("Frame decoded. " + byteBuf.readableBytes() + " bytes left in buffer."); } }
From source file:org.herry2038.scadb.db.util.BufferDumper.java
License:Open Source License
public static final String dumpAsHex(ByteBuf buffer) { int length = buffer.readableBytes(); byte[] byteBuffer = new byte[length]; buffer.markReaderIndex();/*from w ww . j av a 2s.c o m*/ buffer.readBytes(byteBuffer); buffer.resetReaderIndex(); StringBuffer outputBuf = new StringBuffer(length * 4); int p = 0; int rows = length / 8; for (int i = 0; (i < rows) && (p < length); i++) { int ptemp = p; outputBuf.append(i + ": "); for (int j = 0; j < 8; j++) { String hexVal = Integer.toHexString(byteBuffer[ptemp] & 0xff); if (hexVal.length() == 1) { hexVal = "0" + hexVal; //$NON-NLS-1$ } outputBuf.append(hexVal + " "); //$NON-NLS-1$ ptemp++; } outputBuf.append(" "); //$NON-NLS-1$ for (int j = 0; j < 8; j++) { int b = 0xff & byteBuffer[p]; if (b > 32 && b < 127) { outputBuf.append((char) b + " "); //$NON-NLS-1$ } else { outputBuf.append(". "); //$NON-NLS-1$ } p++; } outputBuf.append("\n"); //$NON-NLS-1$ } outputBuf.append(rows + ": "); int n = 0; for (int i = p; i < length; i++) { String hexVal = Integer.toHexString(byteBuffer[i] & 0xff); if (hexVal.length() == 1) { hexVal = "0" + hexVal; //$NON-NLS-1$ } outputBuf.append(hexVal + " "); //$NON-NLS-1$ n++; } for (int i = n; i < 8; i++) { outputBuf.append(" "); //$NON-NLS-1$ } outputBuf.append(" "); //$NON-NLS-1$ for (int i = p; i < length; i++) { int b = 0xff & byteBuffer[i]; if (b > 32 && b < 127) { outputBuf.append((char) b + " "); //$NON-NLS-1$ } else { outputBuf.append(". "); //$NON-NLS-1$ } } outputBuf.append("\n"); //$NON-NLS-1$ outputBuf.append("Total " + byteBuffer.length + " bytes read\n"); return outputBuf.toString(); }
From source file:org.inspirenxe.pulse.network.protocol.ServerProtocol.java
License:MIT License
@Override public Codec<?> readHeader(ByteBuf buf) throws UnknownPacketException { int length = -1; int opcode = -1; try {//from ww w.ja v a2 s . co m length = ByteBufUtils.readVarInt(buf); buf.markReaderIndex(); opcode = ByteBufUtils.readVarInt(buf); return getCodecLookupService(INBOUND).find(opcode); } catch (IOException e) { throw new UnknownPacketException("Failed to read packet data (corrupt?)", opcode, length); } catch (IllegalOpcodeException e) { buf.resetReaderIndex(); throw new UnknownPacketException("Opcode received is not a registered codec on the pulse!", opcode, length); } }
From source file:org.jfxvnc.net.rfb.codec.decoder.ServerCutTextDecoder.java
License:Apache License
@Override public boolean decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!in.isReadable(8)) { return false; }//from ww w . j a v a2 s .co m in.markReaderIndex(); in.skipBytes(4); int length = in.readInt(); if (!in.isReadable(length)) { in.resetReaderIndex(); return false; } byte[] text = new byte[length]; in.readBytes(text); out.add(new ServerCutTextEvent(new String(text, StandardCharsets.ISO_8859_1))); return true; }
From source file:org.jmqtt.core.codec.ConnectDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException { in.resetReaderIndex(); //Common decoding part ConnectPacket message = new ConnectPacket(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex();/*from w ww .java 2 s . c o m*/ return; } 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; } 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) MqttUtils.VERSION_3_1); break; case 4: //MQTT version 3.1.1 "MQTT" //ProtocolName 6 bytes if (in.readableBytes() < 8) { in.resetReaderIndex(); return; } 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) MqttUtils.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() == MqttUtils.VERSION_3_1_1) { //if 3.1.1, check the flags (dup, retain and qos == 0) if (message.isDupFlag() || message.isRetainFlag() || message.getQos() != 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() == MqttUtils.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 = MqttUtils.readWord(in); int keepAlive = in.readUnsignedShort(); message.setKeepAlive(keepAlive); if ((remainingLength == 12 && message.getProtocolVersion() == MqttUtils.VERSION_3_1) || (remainingLength == 10 && message.getProtocolVersion() == MqttUtils.VERSION_3_1_1)) { out.add(message); return; } //Decode the ClientID String clientID = MqttUtils.decodeString(in); if (clientID == null) { in.resetReaderIndex(); return; } message.setClientID(clientID); //Decode willTopic if (willFlag) { String willTopic = MqttUtils.decodeString(in); if (willTopic == null) { in.resetReaderIndex(); return; } message.setWillTopic(willTopic); } //Decode willMessage if (willFlag) { byte[] willMessage = MqttUtils.readFixedLengthContent(in); if (willMessage == null) { in.resetReaderIndex(); return; } 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) { out.add(message); return; } //Decode username if (userFlag) { String userName = MqttUtils.decodeString(in); if (userName == null) { in.resetReaderIndex(); return; } message.setUsername(userName); } readed = in.readerIndex() - start; if (readed == remainingLength) { out.add(message); return; } //Decode password if (passwordFlag) { byte[] password = MqttUtils.readFixedLengthContent(in); if (password == null) { in.resetReaderIndex(); return; } message.setPassword(password); } out.add(message); }
From source file:org.jmqtt.core.codec.DisconnectDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { //Common decoding part in.resetReaderIndex(); DisconnectPacket message = new DisconnectPacket(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex();//from w ww. jav a 2s. co m return; } out.add(message); }
From source file:org.jmqtt.core.codec.MessageIDDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { in.resetReaderIndex(); //Common decoding part PacketIdPacket message = createMessage(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex();//from www.j a v a2s .c o m return; } //read messageIDs message.setPacketId(in.readUnsignedShort()); out.add(message); }
From source file:org.jmqtt.core.codec.MQTTDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { in.markReaderIndex();// w w w. j ava 2s .c o m if (!MqttUtils.checkHeaderAvailability(in)) { in.resetReaderIndex(); return; } in.resetReaderIndex(); byte messageType = MqttUtils.readMessageType(in); DemuxDecoder decoder = decoderMap.get(messageType); if (decoder == null) { throw new CorruptedFrameException("Can't find any suitable decoder for message type: " + messageType); } decoder.decode(ctx, in, out); }