List of usage examples for io.netty.buffer ByteBuf readBytes
public abstract ByteBuf readBytes(ByteBuffer dst);
From source file:com.github.spapageo.jannel.channel.ChannelBufferUtils.java
License:Open Source License
/** * Reads a data segment from the byte buffer * @param byteBuffer the bytes to read from * @return the data segment/*from www . j a va2 s . c om*/ */ @Nonnull public static ByteBuf readOctetStringToBytes(ByteBuf byteBuffer) { if (byteBuffer.readableBytes() < 4) throw new NotEnoughDataDecoderException("Not enough bytes to read the octet string size"); int dataSize = byteBuffer.readInt(); if (dataSize == -1) return Unpooled.EMPTY_BUFFER; checkOctetStringSize(byteBuffer, dataSize); return byteBuffer.readBytes(dataSize); }
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();/*ww w .ja v a 2 s . c om*/ //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();/*from ww w. j ava2 s . co 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.wens.netty.web.impl.RequestImp.java
License:Apache License
private void readBody() { try {//from w ww. j a v a2 s.c o m ByteBuf content = httpRequest.content(); int readableBytes = content.readableBytes(); bodyBytes = new byte[readableBytes]; content.readBytes(bodyBytes); bodyString = new String(bodyBytes); } catch (Exception e) { throw new WebException("Exception when reading body", e); } }
From source file:com.heliosapm.ohcrs.impls.oracle.OracleDriverCodec.java
License:Apache License
@Override public Datum read(final DBType d, final ByteBuf b) throws SQLException { final short typeCode = b.readShort(); if (checkNull(b)) return null; final int size = b.readInt(); final byte[] bytes = new byte[size]; b.readBytes(bytes); final DBType dbType = DBType.forCode(typeCode); switch (dbType) { case BIT://from w w w. j a va 2 s . com case BIGINT: case DECIMAL: case DOUBLE: case FLOAT: case INTEGER: case NUMERIC: case TINYINT: case SMALLINT: return new NUMBER(bytes); case DATE: case TIME: return new oracle.sql.DATE(bytes); case TIMESTAMP: return new oracle.sql.TIMESTAMP(bytes); case ROWID: return new oracle.sql.ROWID(bytes); case CHAR: case NCHAR: case VARCHAR: case LONGVARCHAR: case LONGNVARCHAR: case NVARCHAR: final int charsetCode = b.readInt(); final CharacterSet cs = CharacterSet.make(charsetCode); return new oracle.sql.CHAR(bytes, cs); default: throw new UnsupportedOperationException(dbType.name()); // case STRUCT: // case BINARY: // case BIT: // case BLOB: // case BOOLEAN: // case CLOB: // case DATALINK: // case DISTINCT: // case JAVA_OBJECT: // case LONGVARBINARY: // case NCLOB: // case NULL: // case OTHER: // case REAL: // case REF: // case SQLXML: // case VARBINARY: } }
From source file:com.hiido.eagle.hes.transfer.FileTransferServer.java
License:Apache License
protected FileStoreInfo createAndStoreFile(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; int filePathSize = in.readInt(); String fileName = new String(in.readBytes(filePathSize).array()); long fileSize = in.readLong(); String localPath = TransferServerConfig.class.getResource("/").getPath() + fileName; logger.info("Start to handler the file [{}] with size [{}b] which be writen to local disk [{}]", fileName, fileSize, localPath);/*w w w .j a v a 2s .c om*/ long currFileSize = in.readableBytes(); ByteBuffer buf = ByteBuffer.allocate((int) currFileSize); in.readBytes(buf); RandomAccessFile accessfile = new RandomAccessFile(localPath, "rw"); FileChannel fileChannel = accessfile.getChannel(); fileChannel.write(buf); return new FileStoreInfo(accessfile, fileChannel, fileName, fileSize, currFileSize); }
From source file:com.hipishare.chat.test.EchoClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; int len = buf.readableBytes(); byte[] temp = new byte[len]; ByteBuffer bb = ByteBuffer.allocate(len); buf.readBytes(temp); bb.put(temp);//w ww . ja va 2s . c o m String message = new String(bb.array()); if ("ping".equals(message)) { buf = Unpooled.copiedBuffer(("[id=" + ctx.channel().id() + "]" + "ok").getBytes()); ctx.writeAndFlush(buf); } }
From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceQueryPacketAssembler.java
License:Open Source License
/** * Process split-packet data//ww w . j a va 2s.c o m * * @param data * The {@link ByteBuf} containing the split-packet data * @param allocator * The {@link ByteBufAllocator} used to create/allocate pooled buffers * * @return Returns a non-null {@link ByteBuf} if the split-packets have been assembled. Null if the * * @throws Exception */ private ByteBuf processSplitPackets(ByteBuf data, ByteBufAllocator allocator, InetSocketAddress senderAddress) throws Exception { int packetCount, packetNumber, requestId, splitSize, packetChecksum = 0; boolean isCompressed; //Start processing requestId = data.readIntLE(); //read the most significant bit is set isCompressed = ((requestId & 0x80000000) != 0); //The total number of packets in the response. packetCount = data.readByte(); //The number of the packet. Starts at 0. packetNumber = data.readByte(); //Create our key for this request (request id + sender ip) final SplitPacketKey key = new SplitPacketKey(requestId, senderAddress); log.debug("Processing split packet {}", key); log.debug( "Split Packet Received = (AbstractRequest {}, Packet Number {}, Packet Count {}, Is Compressed: {})", requestId, packetNumber, packetCount, isCompressed); //Try to retrieve the split packet container for this request (if existing) //If request is not yet on the map, create and retrieve SplitPacketContainer splitPackets = this.requestMap.computeIfAbsent(key, k -> new SplitPacketContainer(packetCount)); //As per protocol specs, the size is only present in the first packet of the response and only if the response is being compressed. //split size = Maximum size of packet before packet switching occurs. The default value is 1248 bytes (0x04E0 if (isCompressed) { splitSize = data.readIntLE(); packetChecksum = data.readIntLE(); } else { splitSize = data.readShortLE(); } //TODO: Handle compressed split packets int bufferSize = Math.min(splitSize, data.readableBytes()); byte[] splitPacket = new byte[bufferSize]; data.readBytes(splitPacket); //transfer the split data into this buffer //Add the split packet to the container splitPackets.addPacket(packetNumber, splitPacket); //Have we received all packets for this request? if (splitPackets.isComplete()) { log.debug( "Split Packets have all been successfully received from AbstractRequest {}. Re-assembling packets.", requestId); //Retrieve total split packets received based on their length int packetSize = splitPackets.getPacketSize(); //Allocate a new buffer to store the re-assembled packets final ByteBuf packetBuffer = allocator.buffer(packetSize); boolean done = false; try { //Start re-assembling split-packets from the container done = reassembleSplitPackets(splitPackets, packetBuffer, isCompressed, splitSize, packetChecksum); } catch (Exception e) { //If an error occurs during re-assembly, make sure we release the allocated buffer packetBuffer.release(); throw e; } finally { if (done) requestMap.remove(key); } return packetBuffer; } //Return null, indicating that we still don't have a complete packet return null; }
From source file:com.ibasco.agql.protocols.valve.source.query.logger.SourceLogListenHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { ByteBuf data = msg.content(); if (data.readableBytes() > 6 && data.readIntLE() == -1) { byte[] raw = new byte[data.readableBytes() - 2]; data.readBytes(raw); data.skipBytes(2);// ww w . j a va2s.c o m //Pass to the callback if (logEventCallback != null) logEventCallback.accept(new SourceLogEntry(new String(raw, Charsets.UTF_8), msg.sender())); } }
From source file:com.ibasco.agql.protocols.valve.source.query.SourcePacketBuilder.java
License:Open Source License
@Override public <T extends SourceServerPacket> T construct(ByteBuf data) { //Mark Index/*from w ww . j a v a 2 s . c om*/ data.markReaderIndex(); try { //Reset the index data.readerIndex(0); //Verify size if (data.readableBytes() < 5) throw new IllegalStateException( "Cannot continue processing buffer with less than or equal to 4 bytes"); //Read protocol header int protocolHeader = data.readIntLE(); //Check if this is a split packet if (protocolHeader == 0xFFFFFFFE) throw new IllegalStateException("Cannot construct a response from a partial/split packet."); //Verify that we have a valid header if (protocolHeader != 0xFFFFFFFF) throw new IllegalStateException("Protocol header not supported."); //Read packet header byte packetHeader = data.readByte(); //Read payload byte[] payload = new byte[data.readableBytes()]; data.readBytes(payload); //Verify if packet header is valid SourceServerPacket packet = createResponsePacketFromHeader(packetHeader); //If packet is empty, means the supplied packet header is not supported if (packet == null) return null; packet.setProtocolHeader(ByteUtils.byteArrayFromInteger(protocolHeader)); packet.setHeader(packetHeader); packet.setPayload(payload); return (T) packet; } finally { data.resetReaderIndex(); } }