List of usage examples for io.netty.buffer ByteBuf resetReaderIndex
public abstract ByteBuf resetReaderIndex();
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubAckDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { //Common decoding part in.resetReaderIndex(); SubAckMessage message = new SubAckMessage(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex();/* w ww. j av a2 s. c o m*/ 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.values()[qos]); } out.add(message); }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.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();//ww w .j a va 2 s. co m return; } //check qos level if (message.getQos() != QOSType.LEAST_ONE) { throw new CorruptedFrameException( "Received PKMPSubscribe 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:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.UnsubscribeDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception { //Common decoding part in.resetReaderIndex(); UnsubscribeMessage message = new UnsubscribeMessage(); if (!decodeCommonHeader(message, 0x02, in)) { in.resetReaderIndex();/*from ww w . j a v a 2 s . c om*/ return; } //check qos level if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) { throw new CorruptedFrameException( "Found an Usubscribe 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()) { message.addTopicFilter(Utils.decodeString(in)); readed = in.readerIndex() - start; } if (message.topicFilters().isEmpty()) { throw new CorruptedFrameException("unsubscribe MUST have got at least 1 topic"); } out.add(message); }
From source file:com.rs3e.utility.ByteBufUtils.java
License:Open Source License
public static String readString(ByteBuf buffer) { buffer.markReaderIndex();// ww w .ja va 2s . com int len = 0; while (buffer.readUnsignedByte() != 0) len++; buffer.resetReaderIndex(); byte[] bytes = new byte[len]; buffer.readBytes(bytes); buffer.readerIndex(buffer.readerIndex() + 1); return new String(bytes, Charsets.ASCII_LATIN1_CHARSET); }
From source file:com.seagate.kinetic.common.protocol.codec.KineticDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { in.markReaderIndex();/*from ww w .j a v a 2s. co m*/ // Wait until the length prefix is available // (magic ('F') + proto-msg-size + value-size) if (in.readableBytes() < 9) { in.resetReaderIndex(); return; } // 1. Read magic number. int magicNumber = in.readUnsignedByte(); if (magicNumber != 'F') { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid magic number: " + magicNumber); } // 2. protobuf message size int protoMessageLength = in.readInt(); // 3. attched value size int attachedValueLength = in.readInt(); // wait until whole message is available if (in.readableBytes() < (protoMessageLength + attachedValueLength)) { in.resetReaderIndex(); return; } // 4. read protobuf message byte[] decoded = new byte[protoMessageLength]; in.readBytes(decoded); // kinetic message KineticMessage km = new KineticMessage(); // construct protobuf message Message.Builder mbuilder = Message.newBuilder(); try { mbuilder.mergeFrom(decoded); } catch (Exception e) { in.resetReaderIndex(); logger.log(Level.WARNING, e.getMessage(), e); throw new RuntimeException(e); } // 5. read attched value if any if (attachedValueLength > 0) { // construct byte[] byte[] attachedValue = new byte[attachedValueLength]; // read from buffer in.readBytes(attachedValue); // set to message // mbuilder.setValue(ByteString.copyFrom(attachedValue)); km.setValue(attachedValue); } Message message = mbuilder.build(); km.setMessage(message); // get command bytes ByteString commandBytes = message.getCommandBytes(); // build command Command.Builder commandBuilder = Command.newBuilder(); try { commandBuilder.mergeFrom(commandBytes); km.setCommand(commandBuilder.build()); } catch (InvalidProtocolBufferException e) { logger.log(Level.WARNING, e.getMessage(), e); } // the whole message out.add(km); // print inbound message if (printMessage) { logger.info("Inbound protocol message: "); String printMsg = ProtocolMessageUtil.toString(km); logger.info(printMsg); } }
From source file:com.seventh_root.ld33.client.network.LD33ClientBoundPacketDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { byte[] output = new byte[in.readableBytes()]; in.readBytes(output);/*from www.j a va2 s . c om*/ System.out.println(Arrays.toString(output)); in.resetReaderIndex(); while (in.isReadable()) { int id = in.readInt(); switch (id) { case 0: byte[] encodedPublicKey = new byte[in.readInt()]; in.readBytes(encodedPublicKey); out.add(new PublicKeyClientBoundPacket(encodedPublicKey)); break; case 1: out.add(new PlayerLoginClientBoundPacket()); break; case 2: String joiningPlayerUUID = readString(in); String joiningPlayerName = readString(in); int joiningPlayerResources = in.readInt(); out.add(new PlayerJoinClientBoundPacket(UUID.fromString(joiningPlayerUUID), joiningPlayerName, joiningPlayerResources)); break; case 3: String quittingPlayerUUID = readString(in); String quittingPlayerName = readString(in); out.add(new PlayerQuitClientBoundPacket(UUID.fromString(quittingPlayerUUID), quittingPlayerName)); break; case 4: String loginResponseMessage = readString(in); boolean loginSuccess = in.readBoolean(); out.add(new PlayerLoginResponseClientBoundPacket(loginResponseMessage, loginSuccess)); break; case 5: String spawningUnitUUID = readString(in); String spawningUnitPlayerUUID = readString(in); int spawningUnitX = in.readInt(); int spawningUnitY = in.readInt(); String type = readString(in); long spawningUnitCompletionTime = in.readLong(); Unit unit; switch (type) { case "wall": unit = new Wall(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; case "dragon": unit = new Dragon(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; case "flag": unit = new Flag(UUID.fromString(spawningUnitUUID), Player.getByUUID(null, UUID.fromString(spawningUnitPlayerUUID)), client.getWorldPanel().getWorld().getTileAt(spawningUnitX, spawningUnitY), spawningUnitCompletionTime); break; default: unit = null; break; } out.add(new UnitSpawnClientBoundPacket(unit)); break; case 6: String movingUnitUUID = readString(in); int movingUnitX = in.readInt(); int movingUnitY = in.readInt(); int movingUnitTargetX = in.readInt(); int movingUnitTargetY = in.readInt(); out.add(new UnitMoveClientBoundPacket( Unit.getByUUID(null, client.getWorldPanel().getWorld(), UUID.fromString(movingUnitUUID)), movingUnitX, movingUnitY, movingUnitTargetX, movingUnitTargetY)); break; case 7: String chatMessage = readString(in); out.add(new ChatMessageClientBoundPacket(chatMessage)); break; case 8: String purchasingPlayerUUID = readString(in); int purchasedUnitX = in.readInt(); int purchasedUnitY = in.readInt(); String purchasedUnitType = readString(in); out.add(new UnitPurchaseClientBoundPacket(UUID.fromString(purchasingPlayerUUID), purchasedUnitX, purchasedUnitY, purchasedUnitType)); break; } } }
From source file:com.splicemachine.stream.KryoDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // LOG.warn("Decoding"); if (in.readableBytes() < 2) return;// w w w. j a v a2 s.com in.markReaderIndex(); int len = in.readUnsignedShort(); // LOG.warn("Read lenght " + len); if (in.readableBytes() < len) { // LOG.warn("Not enough data "); in.resetReaderIndex(); return; } // LOG.warn("Decoding object "); byte[] buf = new byte[len]; in.readBytes(buf); Input input = new Input(buf); Kryo decoder = kp.get(); try { Object object = decoder.readClassAndObject(input); out.add(object); } finally { kp.returnInstance(decoder); } // LOG.warn("Decoded " + object); }
From source file:com.spotify.folsom.client.binary.BinaryMemcacheDecoder.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf buf, final List<Object> out) throws Exception { for (int i = 0; i < BATCH_SIZE; i++) { if (buf.readableBytes() < 24) { return; }// ww w. j a v a2 s . com buf.markReaderIndex(); final int magicNumber = buf.readUnsignedByte(); // byte 0 if (magicNumber != 0x81) { throw fail(buf, String.format("Invalid magic number: 0x%2x", magicNumber)); } final int opcode = buf.readByte(); // byte 1 final int keyLength = buf.readUnsignedShort(); // byte 2-3 final int extrasLength = buf.readUnsignedByte(); // byte 4 buf.skipBytes(1); final int statusCode = buf.readUnsignedShort(); // byte 6-7 final MemcacheStatus status = MemcacheStatus.fromInt(statusCode); final int totalLength = buf.readInt(); // byte 8-11 final int opaque = buf.readInt(); final long cas = buf.readLong(); if (buf.readableBytes() < totalLength) { buf.resetReaderIndex(); return; } buf.skipBytes(extrasLength); buf.skipBytes(keyLength); final int valueLength = totalLength - keyLength - extrasLength; byte[] valueBytes; if (valueLength == 0) { valueBytes = NO_BYTES; } else { valueBytes = new byte[valueLength]; } buf.readBytes(valueBytes); replies.add(new ResponsePacket((byte) opcode, status, opaque, cas, valueBytes)); if ((opaque & 0xFF) == 0) { out.add(replies); replies = new BinaryResponse(); } } }
From source file:com.spotify.folsom.client.binary.BinaryMemcacheDecoder.java
License:Apache License
private IOException fail(final ByteBuf buf, final String message) { buf.resetReaderIndex(); return new IOException(message); }
From source file:com.spotify.netty.handler.codec.zmtp.ZMTPMessageParser.java
License:Apache License
/** * Parses as many whole frames from the buffer as possible, until the final frame is encountered. * If the message was completed, it returns the frames of the message. Otherwise it returns null * to indicate that more data is needed. * <p/>//from w w w.j a va 2 s.c om * <p> Oversized messages will be truncated by discarding frames that would make the message size * exceeed the specified size limit. * * @param buffer Buffer with data * @return A {@link ZMTPMessage} if it was completely parsed, otherwise null. */ public ZMTPParsedMessage parse(final ByteBuf buffer) throws ZMTPMessageParsingException { // If we're in discarding mode, continue discarding data if (isOversized(size)) { return discardFrames(buffer); } while (buffer.readableBytes() > 0) { buffer.markReaderIndex(); // Parse frame header final boolean parsedHeader = parseZMTPHeader(buffer); if (!parsedHeader) { // Wait for more data to decode buffer.resetReaderIndex(); return null; } // Check if the message size limit is reached if (isOversized(size + frameSize)) { // Enter discarding mode buffer.resetReaderIndex(); return discardFrames(buffer); } if (frameSize > buffer.readableBytes()) { // Wait for more data to decode buffer.resetReaderIndex(); return null; } size += frameSize; // Read frame content final ZMTPFrame frame = ZMTPFrame.read(buffer, frameSize); if (!frame.hasData() && part == envelope) { // Skip the delimiter part = content; } else { part.add(frame); } if (!hasMore) { return finish(false); } } return null; }