List of usage examples for io.netty.buffer ByteBuf markReaderIndex
public abstract ByteBuf markReaderIndex();
From source file:impl.underdark.transport.bluetooth.BtLink.java
License:Open Source License
private boolean formFrames(ByteBuf inputData) { final int headerSize = 4; while (true) { if (inputData.readableBytes() < headerSize) break; inputData.markReaderIndex(); int frameSize = inputData.readInt(); if (frameSize > Config.frameSizeMax) { Logger.warn("bt frame size limit reached."); return false; }//from w w w. jav a2s. c om if (inputData.readableBytes() < frameSize) { inputData.resetReaderIndex(); break; } final Frames.Frame frame; { final byte[] frameBody = new byte[frameSize]; inputData.readBytes(frameBody, 0, frameSize); try { frame = Frames.Frame.parseFrom(frameBody); } catch (Exception ex) { continue; } } if (this.state == State.CONNECTING) { if (frame.getKind() != Frames.Frame.Kind.HELLO) continue; this.nodeId = frame.getHello().getNodeId(); this.state = State.CONNECTED; Logger.debug("bt connected {}", BtLink.this.toString()); transport.queue.dispatch(new Runnable() { @Override public void run() { transport.linkConnected(BtLink.this, frame.getHello().getPeer()); } }); continue; } if (frame.getKind() == Frames.Frame.Kind.PAYLOAD) { if (!frame.hasPayload() || !frame.getPayload().hasPayload()) continue; final byte[] frameData = frame.getPayload().getPayload().toByteArray(); if (frameData.length == 0) continue; transport.queue.dispatch(new Runnable() { @Override public void run() { transport.linkDidReceiveFrame(BtLink.this, frameData); } }); continue; } transport.queue.dispatch(new Runnable() { @Override public void run() { transport.linkDidReceiveLinkFrame(BtLink.this, frame); } }); } // while return true; }
From source file:impl.underdark.transport.nsd.NsdLink.java
License:Open Source License
private boolean formFrames(ByteBuf inputData) { final int headerSize = 4; while (true) { if (inputData.readableBytes() < headerSize) break; inputData.markReaderIndex(); int frameSize = inputData.readInt(); if (frameSize > Config.frameSizeMax) { Logger.warn("nsd frame size limit reached."); return false; }/* ww w . j a v a2 s . c o m*/ if (inputData.readableBytes() < frameSize) { inputData.resetReaderIndex(); break; } final Frames.Frame frame; { final byte[] frameBody = new byte[frameSize]; inputData.readBytes(frameBody, 0, frameSize); try { frame = Frames.Frame.parseFrom(frameBody); } catch (Exception ex) { continue; } } if (this.state == State.CONNECTING) { if (frame.getKind() != Frames.Frame.Kind.HELLO) continue; this.nodeId = frame.getHello().getNodeId(); this.state = State.CONNECTED; Logger.debug("nsd connected {}", NsdLink.this.toString()); server.queue.execute(new Runnable() { @Override public void run() { server.linkConnected(NsdLink.this); } }); continue; } if (frame.getKind() == Frames.Frame.Kind.PAYLOAD) { if (!frame.hasPayload() || !frame.getPayload().hasPayload()) continue; final byte[] frameData = frame.getPayload().getPayload().toByteArray(); if (frameData.length == 0) continue; server.queue.execute(new Runnable() { @Override public void run() { server.linkDidReceiveFrame(NsdLink.this, frameData); } }); continue; } if (frame.getKind() == Frames.Frame.Kind.HEARTBEAT) { continue; } /*server.queue.dispatch(new Runnable() { @Override public void run() { server.linkDidReceiveLinkFrame(NsdLink.this, frame); } });*/ } // while return true; }
From source file:io.atomix.cluster.messaging.impl.MessageDecoder.java
License:Apache License
@Override @SuppressWarnings("squid:S128") // suppress switch fall through warning protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) throws Exception { switch (currentState) { case READ_SENDER_VERSION: if (buffer.readableBytes() < SHORT_SIZE) { return; }/*from w w w . j av a 2s . c o m*/ version = buffer.readShort(); currentState = DecoderState.READ_SENDER_IP; case READ_SENDER_IP: if (buffer.readableBytes() < BYTE_SIZE) { return; } buffer.markReaderIndex(); int octetsLength = buffer.readByte(); if (buffer.readableBytes() < octetsLength) { buffer.resetReaderIndex(); return; } byte[] octets = new byte[octetsLength]; buffer.readBytes(octets); senderIp = InetAddress.getByAddress(octets); currentState = DecoderState.READ_SENDER_PORT; case READ_SENDER_PORT: if (buffer.readableBytes() < INT_SIZE) { return; } senderPort = buffer.readInt(); address = new Address(senderIp.getHostName(), senderPort, senderIp); currentState = DecoderState.READ_TYPE; case READ_TYPE: if (buffer.readableBytes() < BYTE_SIZE) { return; } type = InternalMessage.Type.forId(buffer.readByte()); currentState = DecoderState.READ_PREAMBLE; case READ_PREAMBLE: if (buffer.readableBytes() < INT_SIZE) { return; } preamble = buffer.readInt(); currentState = DecoderState.READ_MESSAGE_ID; case READ_MESSAGE_ID: if (buffer.readableBytes() < LONG_SIZE) { return; } messageId = buffer.readLong(); currentState = DecoderState.READ_CONTENT_LENGTH; case READ_CONTENT_LENGTH: if (buffer.readableBytes() < INT_SIZE) { return; } contentLength = buffer.readInt(); currentState = DecoderState.READ_CONTENT; case READ_CONTENT: if (buffer.readableBytes() < contentLength) { return; } if (contentLength > 0) { // TODO: Perform a sanity check on the size before allocating content = new byte[contentLength]; buffer.readBytes(content); } else { content = EMPTY_PAYLOAD; } switch (type) { case REQUEST: currentState = DecoderState.READ_SUBJECT_LENGTH; break; case REPLY: currentState = DecoderState.READ_STATUS; break; default: checkState(false, "Must not be here"); } break; default: break; } switch (type) { case REQUEST: switch (currentState) { case READ_SUBJECT_LENGTH: if (buffer.readableBytes() < SHORT_SIZE) { return; } subjectLength = buffer.readShort(); currentState = DecoderState.READ_SUBJECT; case READ_SUBJECT: if (buffer.readableBytes() < subjectLength) { return; } final String subject = readString(buffer, subjectLength, UTF_8); InternalRequest message = new InternalRequest(preamble, messageId, address, subject, content); out.add(message); currentState = DecoderState.READ_TYPE; break; default: break; } break; case REPLY: switch (currentState) { case READ_STATUS: if (buffer.readableBytes() < BYTE_SIZE) { return; } InternalReply.Status status = InternalReply.Status.forId(buffer.readByte()); InternalReply message = new InternalReply(preamble, messageId, content, status); out.add(message); currentState = DecoderState.READ_TYPE; break; default: break; } break; default: checkState(false, "Must not be here"); } }
From source file:io.awacs.protocol.binary.BinaryMessageDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int readable = in.readableBytes(); if (readable > BinaryMessage.MAX_PACKET_SIZE) { in.skipBytes(readable);//from w ww. j a v a 2s. co m throw new TooLongFrameException(); } //??? if (readable < 16) { return; } byte[] headerBytes = new byte[16]; in.readBytes(headerBytes, 0, 16); int bodyLength = BinaryMessage.bodyLength(headerBytes); //body??body if (in.readableBytes() < bodyLength) { in.resetReaderIndex(); return; } byte[] bodyBytes = new byte[bodyLength]; in.readBytes(bodyBytes, 0, bodyLength); // byte[] copy = new byte[16 + bodyLength]; // System.arraycopy(headerBytes, 0, copy, 0, 16); // System.arraycopy(bodyBytes, 0, copy, 16, bodyLength); Message m = BinaryMessage.parse(headerBytes, bodyBytes); in.markReaderIndex(); out.add(m); }
From source file:io.codis.nedis.handler.RedisResponseDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { in.markReaderIndex(); if (!decode(in, out, NULL_REPLY)) { in.resetReaderIndex();/*from ww w . j av a 2 s .com*/ } }
From source file:io.crate.protocols.postgres.SslReqHandler.java
License:Apache License
/** * Process receives incoming data from the Netty pipeline. It * may request more data by returning the WAITING_FOR_INPUT * state. The process method should return DONE when it has * finished processing. It may add additional elements to the * pipeline. The handler is responsible for to position the * buffer read marker correctly such that successive readers * see the correct data. The handler is expected to position the * marker after the SSLRequest payload./*from w w w . j av a 2 s . c om*/ * @param buffer The buffer with incoming data * @param pipeline The Netty pipeline which may be modified * @return The state of the handler */ public State process(ByteBuf buffer, ChannelPipeline pipeline) { if (buffer.readableBytes() < SSL_REQUEST_BYTE_LENGTH) { return State.WAITING_FOR_INPUT; } // mark the buffer so we can jump back if we don't handle this startup buffer.markReaderIndex(); // reads the total message length (int) and the SSL request code (int) if (buffer.readInt() == SSL_REQUEST_BYTE_LENGTH && buffer.readInt() == SSL_REQUEST_CODE) { // received optional SSL negotiation pkg if (sslContext != null) { writeByteAndFlushMessage(pipeline.channel(), 'S'); SslHandler sslHandler = sslContext.newHandler(pipeline.channel().alloc()); pipeline.addFirst(sslHandler); } else { writeByteAndFlushMessage(pipeline.channel(), 'N'); } buffer.markReaderIndex(); } else { buffer.resetReaderIndex(); } return State.DONE; }
From source file:io.lettuce.core.protocol.RedisStateMachine.java
License:Apache License
/** * Attempt to decode a redis response and return a flag indicating whether a complete response was read. * * @param buffer Buffer containing data from the server. * @param command the command itself/*from w w w . j a v a2 s . c o m*/ * @param output Current command output. * @return true if a complete response was read. */ public boolean decode(ByteBuf buffer, RedisCommand<?, ?, ?> command, CommandOutput<?, ?, ?> output) { int length, end; ByteBuffer bytes; if (debugEnabled) { logger.debug("Decode {}", command); } if (isEmpty(stack)) { add(stack, new State()); } if (output == null) { return isEmpty(stack); } loop: while (!isEmpty(stack)) { State state = peek(stack); if (state.type == null) { if (!buffer.isReadable()) { break; } state.type = readReplyType(buffer); buffer.markReaderIndex(); } switch (state.type) { case SINGLE: if ((bytes = readLine(buffer)) == null) { break loop; } if (!QUEUED.equals(bytes)) { safeSetSingle(output, bytes, command); } break; case ERROR: if ((bytes = readLine(buffer)) == null) { break loop; } safeSetError(output, bytes, command); break; case INTEGER: if ((end = findLineEnd(buffer)) == -1) { break loop; } long integer = readLong(buffer, buffer.readerIndex(), end); safeSet(output, integer, command); break; case BULK: if ((end = findLineEnd(buffer)) == -1) { break loop; } length = (int) readLong(buffer, buffer.readerIndex(), end); if (length == -1) { safeSet(output, null, command); } else { state.type = BYTES; state.count = length + 2; buffer.markReaderIndex(); continue loop; } break; case MULTI: if (state.count == -1) { if ((end = findLineEnd(buffer)) == -1) { break loop; } length = (int) readLong(buffer, buffer.readerIndex(), end); state.count = length; buffer.markReaderIndex(); safeMulti(output, state.count, command); } if (state.count <= 0) { break; } state.count--; addFirst(stack, new State()); continue loop; case BYTES: if ((bytes = readBytes(buffer, state.count)) == null) { break loop; } safeSet(output, bytes, command); break; default: throw new IllegalStateException("State " + state.type + " not supported"); } buffer.markReaderIndex(); remove(stack); output.complete(size(stack)); } if (debugEnabled) { logger.debug("Decoded {}, empty stack: {}", command, isEmpty(stack)); } return isEmpty(stack); }
From source file:io.lettuce.core.protocol.RedisStateMachine.java
License:Apache License
private ByteBuffer readLine(ByteBuf buffer) { ByteBuffer bytes = null;//from ww w . j a v a 2s. co m int end = findLineEnd(buffer); if (end > -1) { int start = buffer.readerIndex(); responseElementBuffer.clear(); int size = end - start - 1; if (responseElementBuffer.capacity() < size) { responseElementBuffer.capacity(size); } buffer.readBytes(responseElementBuffer, size); bytes = responseElementBuffer.internalNioBuffer(0, size); buffer.readerIndex(end + 1); buffer.markReaderIndex(); } return bytes; }
From source file:io.liveoak.container.protocols.ProtocolDetector.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int nonNewlineBytes = in.bytesBefore((byte) '\n'); in.markReaderIndex(); if (nonNewlineBytes > 0) { ByteBuf lineBuffer = in.readBytes(nonNewlineBytes); String line = lineBuffer.toString(UTF_8); //SslHandler sslHandler = context.getPipeline().writeState( SslHandler.class ); in.resetReaderIndex();//from w w w . j a v a 2s . c o m ByteBuf fullBuffer = in.readBytes(super.actualReadableBytes()); if (line.startsWith("CONNECT") || line.startsWith("STOMP")) { this.configurator.switchToPureStomp(ctx.pipeline()); } else { this.configurator.switchToHttpWebSockets(ctx.pipeline()); } ctx.pipeline().fireChannelRead(fullBuffer); } }
From source file:io.mycat.netty.mysql.MySQLProtocolDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { logger.info("MYSQLProtocolDecoder start"); // 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. logger.info("byate is too short, less than 4 : {}", in.readableBytes()); return;// w w w. j ava 2 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. logger.info("byte length is not xiangfu"); 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); logger.info("protocol decode success"); }