List of usage examples for io.netty.buffer ByteBuf readerIndex
public abstract int readerIndex();
From source file:com.datastax.driver.core.CBUtil.java
License:Apache License
private static String readString(ByteBuf cb, int length) { try {/*ww w . ja v a 2 s . c o m*/ String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8); cb.readerIndex(cb.readerIndex() + length); return str; } catch (IllegalStateException e) { // That's the way netty encapsulate a CCE if (e.getCause() instanceof CharacterCodingException) throw new DriverInternalError("Cannot decode string as UTF8"); else throw e; } }
From source file:com.datastax.driver.core.FrameCompressor.java
License:Apache License
protected static ByteBuffer inputNioBuffer(ByteBuf buf) { // Using internalNioBuffer(...) as we only hold the reference in this method and so can // reduce Object allocations. int index = buf.readerIndex(); int len = buf.readableBytes(); return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len); }
From source file:com.datastax.driver.core.LZ4Compressor.java
License:Apache License
private ByteBuf compressHeap(ByteBuf input) throws IOException { int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes()); // Not a direct buffer so use byte arrays... int inOffset = input.arrayOffset() + input.readerIndex(); byte[] in = input.array(); int len = input.readableBytes(); // Increase reader index. input.readerIndex(input.writerIndex()); // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so // can eliminate the overhead of allocate a new byte[]. ByteBuf output = input.alloc().heapBuffer(INTEGER_BYTES + maxCompressedLength); try {//w w w . j a v a 2 s . com output.writeInt(len); // calculate the correct offset. int offset = output.arrayOffset() + output.writerIndex(); byte[] out = output.array(); int written = compressor.compress(in, inOffset, len, out, offset); // Set the writer index so the amount of written bytes is reflected output.writerIndex(output.writerIndex() + written); } catch (Exception e) { // release output buffer so we not leak and rethrow exception. output.release(); throw new IOException(e); } return output; }
From source file:com.datastax.driver.core.LZ4Compressor.java
License:Apache License
private ByteBuf decompressHeap(ByteBuf input) throws IOException { // Not a direct buffer so use byte arrays... byte[] in = input.array(); int len = input.readableBytes(); int uncompressedLength = input.readInt(); int inOffset = input.arrayOffset() + input.readerIndex(); // Increase reader index. input.readerIndex(input.writerIndex()); // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so // can eliminate the overhead of allocate a new byte[]. ByteBuf output = input.alloc().heapBuffer(uncompressedLength); try {/*from w w w . j a v a2s.c om*/ int offset = output.arrayOffset() + output.writerIndex(); byte out[] = output.array(); int read = decompressor.decompress(in, inOffset, out, offset, uncompressedLength); if (read != len - INTEGER_BYTES) throw new IOException("Compressed lengths mismatch"); // Set the writer index so the amount of written bytes is reflected output.writerIndex(output.writerIndex() + uncompressedLength); } catch (Exception e) { // release output buffer so we not leak and rethrow exception. output.release(); throw new IOException(e); } return output; }
From source file:com.datastax.driver.core.SnappyCompressor.java
License:Apache License
private ByteBuf compressHeap(ByteBuf input) throws IOException { int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes()); int inOffset = input.arrayOffset() + input.readerIndex(); byte[] in = input.array(); int len = input.readableBytes(); // Increase reader index. input.readerIndex(input.writerIndex()); // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so // can eliminate the overhead of allocate a new byte[]. ByteBuf output = input.alloc().heapBuffer(maxCompressedLength); try {// ww w . j a va2 s. co m // Calculate the correct offset. int offset = output.arrayOffset() + output.writerIndex(); byte[] out = output.array(); int written = Snappy.compress(in, inOffset, len, out, offset); // Increase the writerIndex with the written bytes. output.writerIndex(output.writerIndex() + written); } catch (IOException e) { // release output buffer so we not leak and rethrow exception. output.release(); throw e; } return output; }
From source file:com.datastax.driver.core.SnappyCompressor.java
License:Apache License
private ByteBuf decompressHeap(ByteBuf input) throws IOException { // Not a direct buffer so use byte arrays... int inOffset = input.arrayOffset() + input.readerIndex(); byte[] in = input.array(); int len = input.readableBytes(); // Increase reader index. input.readerIndex(input.writerIndex()); if (!Snappy.isValidCompressedBuffer(in, inOffset, len)) throw new DriverInternalError("Provided frame does not appear to be Snappy compressed"); // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so // can eliminate the overhead of allocate a new byte[]. ByteBuf output = input.alloc().heapBuffer(Snappy.uncompressedLength(in, inOffset, len)); try {/* w w w . ja v a 2 s . c o m*/ // Calculate the correct offset. int offset = output.arrayOffset() + output.writerIndex(); byte[] out = output.array(); int written = Snappy.uncompress(in, inOffset, len, out, offset); // Increase the writerIndex with the written bytes. output.writerIndex(output.writerIndex() + written); } catch (IOException e) { // release output buffer so we not leak and rethrow exception. output.release(); throw e; } return output; }
From source file:com.dc.gameserver.ServerCore.Controller.AbstractController.AbstractController.java
License:Apache License
/** * fastjson??javaBean </br>/*from w ww . j a v a2s. c om*/ * ??javaBean </br> * * @param buffer buffer * @param clazz class sub-class * @return Object javaBean */ public static Object parseObject(ByteBuf buffer, Class clazz) { Object o = JSON.parseObject(buffer.toString(buffer.readerIndex(), buffer.writerIndex() - buffer.readerIndex(), Charset.defaultCharset()), clazz); buffer.release();//buf byteBuffer +buf? buffer = null; return o; }
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();/*from w ww . j a v a 2s .c o 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.PublishDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { LOG.debug("decode invoked with buffer {}", in); in.resetReaderIndex();//from ww w .ja v a 2s . 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; } 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; } //[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; } ByteBuf bb = Unpooled.buffer(payloadSize); in.readBytes(bb); message.setPayload(bb.nioBuffer()); out.add(message); }
From source file:com.dempe.chat.common.mqtt.codec.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();//ww w .j a va2 s . c o m if (!decodeCommonHeader(message, 0x02, in)) { in.resetReaderIndex(); return; } //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"); } out.add(message); }