List of usage examples for io.netty.buffer ByteBuf markReaderIndex
public abstract ByteBuf markReaderIndex();
From source file:com.newlandframework.rpc.serialize.MessageDecoder.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (in.readableBytes() < MessageDecoder.MESSAGE_LENGTH) { return;//ww w .j av a 2s . co m } in.markReaderIndex(); int messageLength = in.readInt(); if (messageLength < 0) { ctx.close(); } if (in.readableBytes() < messageLength) { in.resetReaderIndex(); return; } else { byte[] messageBody = new byte[messageLength]; in.readBytes(messageBody); try { Object obj = util.decode(messageBody); out.add(obj); } catch (IOException ex) { Logger.getLogger(MessageDecoder.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.ns.netty.gcd.server.BigIntegerDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { System.out.println("Decoder received event"); // Wait until the length prefix is available. if (in.readableBytes() < 5) { return;/*from ww w . j ava 2 s . c om*/ } in.markReaderIndex(); // Check the magic number. int magicNumber = in.readUnsignedByte(); if (magicNumber != 'F') { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid magic number: " + magicNumber); } // Wait until the whole data is available. int dataLength = in.readInt(); if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } // Convert the received data into a new BigInteger. byte[] decoded = new byte[dataLength]; in.readBytes(decoded); out.add(new BigInteger(decoded)); }
From source file:com.openddal.server.mysql.MySQLProtocolDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // Make sure if the length field was received. if (in.readableBytes() < FRAME_LENGTH_FIELD_LENGTH) { // The length field was not received yet - return. // This method will be invoked again when more packets are // received and appended to the buffer. return;/*from w w w .ja v a2 s. co m*/ } // The length field is in the buffer. // Mark the current buffer position before reading the length field // because the whole frame might not be in the buffer yet. // We will reset the buffer position to the marked position if // there's not enough bytes in the buffer. in.markReaderIndex(); int frameLength = readLength(in);// in.readInt(); // Make sure if there's enough bytes in the buffer. if (in.readableBytes() < frameLength) { // The whole bytes were not received yet - return. // This method will be invoked again when more packets are // received and appended to the buffer. // Reset to the marked position to read the length field again // next time. in.resetReaderIndex(); return; } // There's enough bytes in the buffer. Read it. ByteBuf frame = in.resetReaderIndex().readSlice(frameLength + 4).retain(); // Successfully decoded a frame. Add the decoded frame. out.add(frame); }
From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.MQTTDecoder.java
License:Open Source License
public AbstractMessage decode(AttributeMap ctx, ByteBuf byteBuf) throws Exception { byteBuf.markReaderIndex(); if (!Utils.checkHeaderAvailability(byteBuf)) { byteBuf.resetReaderIndex();//from w w w . jav a2 s .co m return null; } byteBuf.resetReaderIndex(); byte messageType = Utils.readMessageType(byteBuf); DemuxDecoder decoder = m_decoderMap.get(messageType); if (decoder == null) { throw new CorruptedFrameException("Can't find any suitable decoder for message type: " + messageType); } return decoder.decode(ctx, byteBuf); }
From source file:com.rs3e.utility.ByteBufUtils.java
License:Open Source License
public static String readString(ByteBuf buffer) { buffer.markReaderIndex(); int len = 0;//w w w . j a v a 2 s . c om 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(); // Wait until the length prefix is available // (magic ('F') + proto-msg-size + value-size) if (in.readableBytes() < 9) { in.resetReaderIndex();/* w w w . j av a 2 s .c o m*/ 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.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 ww . j a va2 s . c o m*/ 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; }/*from w ww .j av a 2s .c o m*/ 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.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 ww w . j a v a2s . 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; }
From source file:com.spotify.netty.handler.codec.zmtp.ZMTPMessageParser.java
License:Apache License
/** * Discard frames for current message./*from w w w.j a va 2 s .c om*/ * * @return A truncated message if done discarding, null if not yet done. */ private ZMTPParsedMessage discardFrames(final ByteBuf buffer) throws ZMTPMessageParsingException { while (buffer.readableBytes() > 0) { // Parse header if necessary if (!headerParsed) { buffer.markReaderIndex(); headerParsed = parseZMTPHeader(buffer); if (!headerParsed) { // Wait for more data to decode buffer.resetReaderIndex(); return null; } size += frameSize; frameRemaining = frameSize; } // Discard bytes final int discardBytes = min(frameRemaining, buffer.readableBytes()); frameRemaining -= discardBytes; buffer.skipBytes(discardBytes); // Check if this frame is completely discarded final boolean done = frameRemaining == 0; if (done) { headerParsed = false; } // Check if this message is done discarding if (done && !hasMore) { // We're done discarding return finish(true); } } return null; }