List of usage examples for io.netty.buffer ByteBuf resetReaderIndex
public abstract ByteBuf resetReaderIndex();
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 www. j a v 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.datty.unit.test.DattyStreamTest.java
License:Apache License
@Test public void testSingle() { String majorKey = UUID.randomUUID().toString(); DattyKey key = new DattyKey().setSetName(SET_NAME).setMajorKey(majorKey).setMinorKey(minorKey); Observable<ByteBuf> input = Observable.just(value.resetReaderIndex()); Long written = dattyManager.getDatty().streamIn(key, input).toBlocking().value(); Assert.assertEquals(written, Long.valueOf(value.resetReaderIndex().readableBytes())); final ByteBuf destBuffer = UnitConstants.ALLOC.buffer(); dattyManager.getDatty().streamOut(key).reduce(destBuffer, new Func2<ByteBuf, ByteBuf, ByteBuf>() { @Override/*from ww w . ja va 2s. com*/ public ByteBuf call(ByteBuf dest, ByteBuf chunk) { dest.writeBytes(chunk); return dest; } }).toBlocking().subscribe(); Assert.assertEquals(value, destBuffer.resetReaderIndex()); }
From source file:io.datty.unit.test.DattyStreamTest.java
License:Apache License
@Test public void testTwo() { String majorKey = UUID.randomUUID().toString(); DattyKey key = new DattyKey().setSetName(SET_NAME).setMajorKey(majorKey).setMinorKey(minorKey); Observable<ByteBuf> input = Observable.just(value.resetReaderIndex(), newValue.resetReaderIndex()); Long written = dattyManager.getDatty().streamIn(key, input).toBlocking().value(); Assert.assertEquals(written, Long .valueOf(value.resetReaderIndex().readableBytes() + newValue.resetReaderIndex().readableBytes())); final ByteBuf destBuffer = UnitConstants.ALLOC.buffer(); dattyManager.getDatty().streamOut(key).reduce(destBuffer, new Func2<ByteBuf, ByteBuf, ByteBuf>() { @Override/* www.ja va 2s. c o m*/ public ByteBuf call(ByteBuf dest, ByteBuf chunk) { dest.writeBytes(chunk); return dest; } }).toBlocking().subscribe(); ByteBuf expected = UnitConstants.ALLOC.buffer(); expected.writeBytes(value.resetReaderIndex()); expected.writeBytes(newValue.resetReaderIndex()); Assert.assertEquals(expected.resetReaderIndex(), destBuffer.resetReaderIndex()); }
From source file:io.github.lordakkarin.nbt.event.TagReader.java
License:Apache License
public TagReader(@NonNull ReadableByteChannel channel) throws IOException { this.buffer = Unpooled.directBuffer(); {/*from www . j a v a2 s . c o m*/ ByteBuffer tmp = ByteBuffer.allocateDirect(128); ByteBuf wrapped = Unpooled.wrappedBuffer(tmp); int length; while ((length = channel.read(tmp)) > 0) { tmp.flip(); this.buffer.writeBytes(wrapped, length); wrapped.resetReaderIndex(); tmp.rewind(); } } }
From source file:io.github.lordakkarin.nbt.event.TagWriterTest.java
License:Apache License
@NonNull private ByteBuf readResource(@NonNull ReadableByteChannel channel) throws IOException { ByteBuf target = Unpooled.directBuffer(); ByteBuffer tmp = ByteBuffer.allocateDirect(128); ByteBuf wrapped = Unpooled.wrappedBuffer(tmp); int length;//from w ww . j ava2s.c o m while ((length = channel.read(tmp)) > 0) { tmp.flip(); target.writeBytes(wrapped, length); wrapped.resetReaderIndex(); tmp.rewind(); } return target; }
From source file:io.github.stormcloud_dev.stormcloud.seralization.RORObjectDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> objects) throws Exception { ByteBuf leBuf = buf.order(LITTLE_ENDIAN); byte[] bytes = new byte[leBuf.readableBytes()]; leBuf.readBytes(bytes);//w w w.j a v a2 s.c o m leBuf.resetReaderIndex(); while (leBuf.readableBytes() > 0) { Object obj = readNextObject(leBuf); if (obj != null) { objects.add(obj); } } }
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();//from w ww . j av a2 s . com if (nonNewlineBytes > 0) { ByteBuf lineBuffer = in.readBytes(nonNewlineBytes); String line = lineBuffer.toString(UTF_8); //SslHandler sslHandler = context.getPipeline().writeState( SslHandler.class ); in.resetReaderIndex(); 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.moquette.parser.netty.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();//from w w w .j av a2 s . c o m return; } //check qos level if (message.getQos() != 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); }
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;/*ww w.j a v a 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"); }
From source file:io.netlibs.bgp.handlers.BGPv4Reframer.java
License:Apache License
/** * reframe the received packet to completely contain the next BGPv4 packet. It peeks into the first four bytes of the TCP stream which * contain a 16-bit marker and a 16-bit length field. The marker must be all one's and the length value must be between 19 and 4096 * according to RFC 4271. The marker and length constraints are verified and if either is violated the connection is closed early. * //ww w.java 2s . c o m * Any packets that are added start on the type byte. The buffer will contain the full message payload. * */ @Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf buffer, final List<Object> out) throws Exception { if (buffer.readableBytes() < (BGPv4Constants.BGP_PACKET_MIN_LENGTH - 1)) { // need more bytes for a full read. return; } buffer.markReaderIndex(); // confirm that the next BGP_PACKET_MARKER_LENGTH bytes are all 0xff. if (buffer.forEachByte(buffer.readerIndex(), BGPv4Constants.BGP_PACKET_MARKER_LENGTH, value -> value == (byte) 0xff) != -1) { log.error("received invalid marker, closing connection"); NotificationHelper.sendEncodedNotification(ctx, new ConnectionNotSynchronizedNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } // skip the marker. buffer.skipBytes(BGPv4Constants.BGP_PACKET_MARKER_LENGTH); // read the packet length. final int length = buffer.readUnsignedShort(); if ((length < BGPv4Constants.BGP_PACKET_MIN_LENGTH) || (length > BGPv4Constants.BGP_PACKET_MAX_LENGTH)) { log.error("received illegal packet size {}, must be between {} and {}. closing connection", new Object[] { length, BGPv4Constants.BGP_PACKET_MIN_LENGTH, BGPv4Constants.BGP_PACKET_MAX_LENGTH }); NotificationHelper.sendEncodedNotification(ctx, new BadMessageLengthNotificationPacket(length), new BgpEventFireChannelFutureListener(ctx)); return; } final int mustRead = (length - (BGPv4Constants.BGP_PACKET_MARKER_LENGTH + 2)); // we have consumed marker and length at this point // must if we don't have the right amount, abort. if (buffer.readableBytes() < mustRead) { buffer.resetReaderIndex(); return; } out.add(buffer.readBytes(mustRead)); }