List of usage examples for io.netty.buffer ByteBuf readByte
public abstract byte readByte();
From source file:com.Da_Technomancer.crossroads.API.packets.Message.java
License:Creative Commons License
private static byte[][] readByte2DArray(ByteBuf buf) { int outerSize = buf.readInt(); int innerSize = buf.readInt(); byte[][] out = new byte[outerSize][innerSize]; for (int i = 0; i < outerSize; i++) { for (int j = 0; j < innerSize; j++) { out[i][j] = buf.readByte(); }// ww w. j a v a2s.c o m } return out; }
From source file:com.dempe.chat.common.mqtt.codec.ConnectDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException { in.resetReaderIndex();// ww w .j av a 2 s. co m //Common decoding part ConnectMessage message = new ConnectMessage(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex(); 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) Utils.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) 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)) { out.add(message); return; } //Decode the ClientID String clientID = Utils.decodeString(in); if (clientID == null) { in.resetReaderIndex(); return; } message.setClientID(clientID); //Decode willTopic if (willFlag) { String willTopic = Utils.decodeString(in); if (willTopic == null) { in.resetReaderIndex(); return; } message.setWillTopic(willTopic); } //Decode willMessage if (willFlag) { byte[] willMessage = Utils.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 = Utils.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 = Utils.readFixedLengthContent(in); if (password == null) { in.resetReaderIndex(); return; } message.setPassword(password); } out.add(message); }
From source file:com.dempe.chat.common.mqtt.codec.DemuxDecoder.java
License:Open Source License
private boolean genericDecodeCommonHeader(AbstractMessage message, Integer expectedFlagsOpt, ByteBuf in) { //Common decoding part if (in.readableBytes() < 2) { return false; }/*from w w w .j a v a 2s . c om*/ byte h1 = in.readByte(); byte messageType = (byte) ((h1 & 0x00F0) >> 4); byte flags = (byte) (h1 & 0x0F); if (expectedFlagsOpt != null) { int expectedFlags = expectedFlagsOpt; if ((byte) expectedFlags != flags) { String hexExpected = Integer.toHexString(expectedFlags); String hexReceived = Integer.toHexString(flags); throw new CorruptedFrameException( String.format("Received a message with fixed header flags (%s) != expected (%s)", hexReceived, hexExpected)); } } boolean dupFlag = ((byte) ((h1 & 0x0008) >> 3) == 1); byte qosLevel = (byte) ((h1 & 0x0006) >> 1); boolean retainFlag = ((byte) (h1 & 0x0001) == 1); int remainingLength = Utils.decodeRemainingLenght(in); if (remainingLength == -1) { return false; } message.setMessageType(messageType); message.setDupFlag(dupFlag); try { message.setQos(AbstractMessage.QOSType.valueOf(qosLevel)); } catch (IllegalArgumentException e) { throw new CorruptedFrameException(String.format("Received an invalid QOS: %s", e.getMessage()), e); } message.setRetainFlag(retainFlag); message.setRemainingLength(remainingLength); return true; }
From source file:com.dempe.chat.common.mqtt.codec.SubAckDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { //Common decoding part in.resetReaderIndex();/* www . jav a 2 s. co m*/ SubAckMessage message = new SubAckMessage(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex(); return; } int remainingLength = message.getRemainingLength(); //MessageID message.setMessageID(in.readUnsignedShort()); remainingLength -= 2; //Qos array if (in.readableBytes() < remainingLength) { in.resetReaderIndex(); return; } for (int i = 0; i < remainingLength; i++) { byte qos = in.readByte(); message.addType(AbstractMessage.QOSType.valueOf(qos)); } out.add(message); }
From source file:com.dempe.chat.common.mqtt.codec.SubscribeDecoder.java
License:Open Source License
/** * Populate the message with couple of Qos, topic *//*from w w w . j a v a 2 s . c om*/ private void decodeSubscription(ByteBuf in, SubscribeMessage message) throws UnsupportedEncodingException { String topic = Utils.decodeString(in); //check topic is at least one char [MQTT-4.7.3-1] if (topic.length() == 0) { throw new CorruptedFrameException("Received a SUBSCRIBE with empty topic filter"); } byte qosByte = in.readByte(); if ((qosByte & 0xFC) > 0) { //the first 6 bits is reserved => has to be 0 throw new CorruptedFrameException( "subscribe MUST have QoS byte with reserved buts to 0, found " + Integer.toHexString(qosByte)); } byte qos = (byte) (qosByte & 0x03); //TODO check qos id 000000xx message.addSubscription(new SubscribeMessage.Couple(qos, topic)); }
From source file:com.dempe.chat.common.mqtt.codec.Utils.java
License:Open Source License
static byte readMessageType(ByteBuf in) { byte h1 = in.readByte(); byte messageType = (byte) ((h1 & 0x00F0) >> 4); return messageType; }
From source file:com.dempe.chat.common.mqtt.codec.Utils.java
License:Open Source License
/** * Decode the variable remaining length as defined in MQTT v3.1 specification * (section 2.1)./*w ww .j a v a 2 s . co m*/ * * @return the decoded length or -1 if needed more data to decode the length field. */ static int decodeRemainingLenght(ByteBuf in) { int multiplier = 1; int value = 0; byte digit; do { if (in.readableBytes() < 1) { return -1; } digit = in.readByte(); value += (digit & 0x7F) * multiplier; multiplier *= 128; } while ((digit & 0x80) != 0); return value; }
From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { LogMgr.debug("channelRead0()", "channelRead0"); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);/* ww w . jav a 2s. c o m*/ } } if (msg instanceof HttpContent) { String type = request.getUri().split("/")[1]; if (type.equals("email_activate") == true) { // GET? String[] tmp = request.getUri().split("="); String acode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}"); return; } else if (type.equals("email_pwd_reset") == true) { //? String[] tmp = request.getUri().split("="); String vcode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}"); return; } //email_active email_pwd_reset, //??? HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); InterfaceHttpData postData = decoder.getBodyHttpData("val"); if (postData instanceof FileUpload == false) {//outerProxy???? ctx.close(); return; } FileUpload binData = (FileUpload) postData; ByteBuf content = null; try { content = binData.getByteBuf(); } catch (IOException e) { e.printStackTrace(); } //content??. , 0. ?(head)?id, json?, ?. ??, ???. //?content?head int index = content.bytesBefore((byte) 0); if (index < 0) { LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request."); ctx.channel().close(); return; } byte[] head = new byte[index]; content.readBytes(head); String strHead = new String(head); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead); JSONObject jo = JSONObject.parseObject(strHead); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version")); content.readByte();//0 //?content?tail byte[] tail = new byte[content.readableBytes()]; content.readBytes(tail); String sjsonmsg = null; if (jo.getString("version").equals("0")) { //?0 byte[] bjsonmsg = XXTEA.decrypt(tail, key); int data_len = bjsonmsg.length; for (int i = bjsonmsg.length - 1; i != 0; --i) { if (bjsonmsg[i] == 0) { data_len--; continue; } else { break; } } try { sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { //TODO?0, app_id. ??? LogMgr.error(OuterProxyHttpServerHandler.class.getName(), "?0, ??"); ctx.close(); return; } sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//? LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg); //debug code //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model")); /* debug code //b.getBytes(n+1, tail, 0, b.g-n-1); for(int i=0; i< tail.length; ++i) { System.out.print(String.format("%x ", tail[i])); } */ //debug code //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg); // ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg); } }
From source file:com.digitalpetri.modbus.codec.ModbusRequestDecoder.java
License:Apache License
@Override public ModbusPdu decode(ByteBuf buffer) throws DecoderException { int code = buffer.readByte(); FunctionCode functionCode = FunctionCode.fromCode(code); if (functionCode == null) { throw new DecoderException("invalid function code: " + code); }/* w ww . j a v a 2s.c om*/ return decodeResponse(functionCode, buffer); }
From source file:com.digitalpetri.modbus.codec.ModbusRequestDecoder.java
License:Apache License
private WriteMultipleRegistersRequest decodeWriteMultipleRegisters(ByteBuf buffer) { int address = buffer.readUnsignedShort(); int quantity = buffer.readUnsignedShort(); int byteCount = buffer.readByte(); ByteBuf values = buffer.readSlice(byteCount).retain(); return new WriteMultipleRegistersRequest(address, quantity, values); }