Example usage for io.netty.buffer ByteBuf resetReaderIndex

List of usage examples for io.netty.buffer ByteBuf resetReaderIndex

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf resetReaderIndex.

Prototype

public abstract ByteBuf resetReaderIndex();

Source Link

Document

Repositions the current readerIndex to the marked readerIndex in this buffer.

Usage

From source file:me.bigteddy98.slimeportal.protocol.NetworkManager.java

License:Open Source License

public synchronized List<Packet> handleClientBoundPackets(ByteBuf bufferClone)
        throws InstantiationException, IllegalAccessException {
    List<Packet> list = new ArrayList<>();
    if (bufferClone.readableBytes() == 0) {
        return list;
    }//from  w  w  w  .ja  v  a2s .  c o m
    PacketDataWrapper wrapper = new PacketDataWrapper(bufferClone);
    while (bufferClone.readableBytes() > 0) {
        bufferClone.markReaderIndex();
        int readBytes = bufferClone.readableBytes();
        int length = 0;
        {
            int bytes = 0;
            byte in;
            while (true) {
                if (readBytes < 1) {
                    bufferClone.resetReaderIndex();
                    return list;
                }
                in = bufferClone.readByte();
                length |= (in & 0x7F) << (bytes++ * 7);
                if (bytes > 5) {
                    throw new RuntimeException("VarInt too big");
                }
                if ((in & 0x80) != 0x80) {
                    break;
                }
            }
        }
        if (bufferClone.readableBytes() < length) {
            bufferClone.resetReaderIndex();
            return list;
        }
        int id = wrapper.readVarInt();
        Class<? extends Packet> clazz = PacketRegistry.getClientBoundPacket(id, this.currentState);
        if (clazz == null) {
            return list;
        }
        Packet packet = clazz.newInstance();
        packet.read(wrapper);
        if (packet instanceof PacketInHandShake) {
            packet.onReceive(this, new PacketReceiveEvent());
        }
        list.add(packet);
        bufferClone.discardSomeReadBytes();
    }
    return list;
}

From source file:net.hasor.rsf.protocol.rsf.RsfDecoder.java

License:Apache License

protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }//from w ww  .  j av  a  2  s .com
    //
    byte rsfHead = frame.getByte(0);//??
    short status = this.doDecode(rsfHead, ctx, frame);//???
    if (status != ProtocolStatus.OK) {
        frame = frame.resetReaderIndex().skipBytes(1);
        long requestID = frame.readLong();
        ResponseInfo info = ProtocolUtils.buildResponseStatus(this.rsfEnvironment, requestID, status, null);
        ctx.pipeline().writeAndFlush(info);
    }
    return null;
}

From source file:net.hasor.rsf.remoting.transport.netty.RSFProtocolDecoder.java

License:Apache License

protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }//from   w w  w .  j a va 2  s . c om
    //
    //* byte[1]  version                              RSF(0xC1)
    byte version = frame.getByte(0);
    short status = 0;
    //decode
    try {
        status = this.doDecode(version, ctx, frame);//???
    } catch (Throwable e) {
        status = ProtocolStatus.ProtocolError;
    } finally {
        if (status == ProtocolStatus.OK)
            return null;
        /*                    */
        frame = frame.resetReaderIndex().skipBytes(1);
        this.fireProtocolError(ctx, version, frame.readLong(), ProtocolStatus.ProtocolError);
    }
    return null;
}

From source file:net.jselby.pc.network.PacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> objects) throws Exception {
    try {/*from   w w  w. java  2s  .c o m*/
        byteBuf.markReaderIndex();

        StandardInput in = new StandardInput(new DataInputStream(new ByteBufInputStream(byteBuf)));
        int length = in.readVarInt();

        if (byteBuf.readableBytes() < length) {
            // Not enough data yet! Wait for a while
            byteBuf.resetReaderIndex();
            return;
        }

        byte[] packet = in.readBytes(length);

        // Create a "unread" packet, for the connection handler to process
        StandardInput packetIn = new StandardInput(new DataInputStream(new ByteArrayInputStream(packet)));

        UnreadPacket packetContainer = new UnreadPacket();
        packetContainer.in = packetIn;
        packetContainer.length = length;

        objects.add(packetContainer);
    } catch (EOFException e) {
        System.out.println("Client " + ctx.channel().remoteAddress() + " disconnected: End of stream");
        UnreadPacket packetContainer = new UnreadPacket();
        packetContainer.in = null;
        packetContainer.length = -1;
        objects.add(packetContainer);
        throw e;
    } catch (Exception e) {
        throw e;
    }
}

From source file:netty.common.proto.code.DisconnectDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    //Common decoding part
    in.resetReaderIndex();
    DisconnectMessage message = new DisconnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();//from  w  w w .j a v a  2 s  . co m
        return;
    }
    LOG.debug("Decoding disconnect");
    out.add(message);
}

From source file:org.apache.activemq.artemis.tests.util.SimpleStringTest.java

License:Apache License

@Test
public void testByteBufSimpleStringPool() {
    final int capacity = 8;
    final int chars = Integer.toString(capacity).length();
    final SimpleString.ByteBufSimpleStringPool pool = new SimpleString.ByteBufSimpleStringPool(capacity, chars);
    final int bytes = new SimpleString(Integer.toString(capacity)).sizeof();
    final ByteBuf bb = Unpooled.buffer(bytes, bytes);
    for (int i = 0; i < capacity; i++) {
        final SimpleString s = new SimpleString(Integer.toString(i));
        bb.resetWriterIndex();//from w  w  w  .  j  a v a 2 s  . c om
        SimpleString.writeSimpleString(bb, s);
        bb.resetReaderIndex();
        final SimpleString expectedPooled = pool.getOrCreate(bb);
        bb.resetReaderIndex();
        Assert.assertSame(expectedPooled, pool.getOrCreate(bb));
        bb.resetReaderIndex();
    }
}

From source file:org.apache.activemq.artemis.tests.util.SimpleStringTest.java

License:Apache License

@Test
public void testByteBufSimpleStringPoolTooLong() {
    final SimpleString tooLong = new SimpleString("aa");
    final ByteBuf bb = Unpooled.buffer(tooLong.sizeof(), tooLong.sizeof());
    SimpleString.writeSimpleString(bb, tooLong);
    final SimpleString.ByteBufSimpleStringPool pool = new SimpleString.ByteBufSimpleStringPool(1,
            tooLong.length() - 1);// w w  w  .j  a va2 s  . c  o m
    Assert.assertNotSame(pool.getOrCreate(bb), pool.getOrCreate(bb.resetReaderIndex()));
}

From source file:org.apache.activemq.artemis.utils.TypedPropertiesTest.java

License:Apache License

@Test
public void testByteBufStringValuePool() {
    final int capacity = 8;
    final int chars = Integer.toString(capacity).length();
    final TypedProperties.StringValue.ByteBufStringValuePool pool = new TypedProperties.StringValue.ByteBufStringValuePool(
            capacity, chars);/*from w  w  w . j  a v a 2s  . c  o m*/
    final int bytes = new SimpleString(Integer.toString(capacity)).sizeof();
    final ByteBuf bb = Unpooled.buffer(bytes, bytes);
    for (int i = 0; i < capacity; i++) {
        final SimpleString s = new SimpleString(Integer.toString(i));
        bb.resetWriterIndex();
        SimpleString.writeSimpleString(bb, s);
        bb.resetReaderIndex();
        final TypedProperties.StringValue expectedPooled = pool.getOrCreate(bb);
        bb.resetReaderIndex();
        Assert.assertSame(expectedPooled, pool.getOrCreate(bb));
        bb.resetReaderIndex();
    }
}

From source file:org.apache.activemq.artemis.utils.TypedPropertiesTest.java

License:Apache License

@Test
public void testByteBufStringValuePoolTooLong() {
    final SimpleString tooLong = new SimpleString("aa");
    final ByteBuf bb = Unpooled.buffer(tooLong.sizeof(), tooLong.sizeof());
    SimpleString.writeSimpleString(bb, tooLong);
    final TypedProperties.StringValue.ByteBufStringValuePool pool = new TypedProperties.StringValue.ByteBufStringValuePool(
            1, tooLong.length() - 1);/* w w w  .  j av  a2s.  c om*/
    Assert.assertNotSame(pool.getOrCreate(bb), pool.getOrCreate(bb.resetReaderIndex()));
}

From source file:org.apache.bookkeeper.benchmark.BenchBookie.java

License:Apache License

/**
 * @param args//from ww  w.j a v  a  2 s.c  o m
 * @throws InterruptedException
 */
public static void main(String[] args)
        throws InterruptedException, ParseException, IOException, BKException, KeeperException {
    Options options = new Options();
    options.addOption("host", true, "Hostname or IP of bookie to benchmark");
    options.addOption("port", true, "Port of bookie to benchmark (default 3181)");
    options.addOption("zookeeper", true, "Zookeeper ensemble, (default \"localhost:2181\")");
    options.addOption("size", true, "Size of message to send, in bytes (default 1024)");
    options.addOption("warmupCount", true, "Number of messages in warmup phase (default 999)");
    options.addOption("latencyCount", true, "Number of messages in latency phase (default 5000)");
    options.addOption("throughputCount", true, "Number of messages in throughput phase (default 50000)");
    options.addOption("help", false, "This message");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help") || !cmd.hasOption("host")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("BenchBookie <options>", options);
        System.exit(-1);
    }

    String addr = cmd.getOptionValue("host");
    int port = Integer.parseInt(cmd.getOptionValue("port", "3181"));
    int size = Integer.parseInt(cmd.getOptionValue("size", "1024"));
    String servers = cmd.getOptionValue("zookeeper", "localhost:2181");
    int warmUpCount = Integer.parseInt(cmd.getOptionValue("warmupCount", "999"));
    int latencyCount = Integer.parseInt(cmd.getOptionValue("latencyCount", "5000"));
    int throughputCount = Integer.parseInt(cmd.getOptionValue("throughputCount", "50000"));

    EventLoopGroup eventLoop;
    if (SystemUtils.IS_OS_LINUX) {
        try {
            eventLoop = new EpollEventLoopGroup();
        } catch (Throwable t) {
            LOG.warn("Could not use Netty Epoll event loop for benchmark {}", t.getMessage());
            eventLoop = new NioEventLoopGroup();
        }
    } else {
        eventLoop = new NioEventLoopGroup();
    }

    OrderedExecutor executor = OrderedExecutor.newBuilder().name("BenchBookieClientScheduler").numThreads(1)
            .build();
    ScheduledExecutorService scheduler = Executors
            .newSingleThreadScheduledExecutor(new DefaultThreadFactory("BookKeeperClientScheduler"));

    ClientConfiguration conf = new ClientConfiguration();
    BookieClient bc = new BookieClientImpl(conf, eventLoop, PooledByteBufAllocator.DEFAULT, executor, scheduler,
            NullStatsLogger.INSTANCE);
    LatencyCallback lc = new LatencyCallback();

    ThroughputCallback tc = new ThroughputCallback();

    long ledger = getValidLedgerId(servers);
    for (long entry = 0; entry < warmUpCount; entry++) {
        ByteBuf toSend = Unpooled.buffer(size);
        toSend.resetReaderIndex();
        toSend.resetWriterIndex();
        toSend.writeLong(ledger);
        toSend.writeLong(entry);
        toSend.writerIndex(toSend.capacity());
        bc.addEntry(new BookieSocketAddress(addr, port), ledger, new byte[20], entry, ByteBufList.get(toSend),
                tc, null, BookieProtocol.FLAG_NONE, false, WriteFlag.NONE);
    }
    LOG.info("Waiting for warmup");
    tc.waitFor(warmUpCount);

    ledger = getValidLedgerId(servers);
    LOG.info("Benchmarking latency");
    long startTime = System.nanoTime();
    for (long entry = 0; entry < latencyCount; entry++) {
        ByteBuf toSend = Unpooled.buffer(size);
        toSend.resetReaderIndex();
        toSend.resetWriterIndex();
        toSend.writeLong(ledger);
        toSend.writeLong(entry);
        toSend.writerIndex(toSend.capacity());
        lc.resetComplete();
        bc.addEntry(new BookieSocketAddress(addr, port), ledger, new byte[20], entry, ByteBufList.get(toSend),
                lc, null, BookieProtocol.FLAG_NONE, false, WriteFlag.NONE);
        lc.waitForComplete();
    }
    long endTime = System.nanoTime();
    LOG.info("Latency: " + (((double) (endTime - startTime)) / ((double) latencyCount)) / 1000000.0);

    ledger = getValidLedgerId(servers);
    LOG.info("Benchmarking throughput");
    startTime = System.currentTimeMillis();
    tc = new ThroughputCallback();
    for (long entry = 0; entry < throughputCount; entry++) {
        ByteBuf toSend = Unpooled.buffer(size);
        toSend.resetReaderIndex();
        toSend.resetWriterIndex();
        toSend.writeLong(ledger);
        toSend.writeLong(entry);
        toSend.writerIndex(toSend.capacity());
        bc.addEntry(new BookieSocketAddress(addr, port), ledger, new byte[20], entry, ByteBufList.get(toSend),
                tc, null, BookieProtocol.FLAG_NONE, false, WriteFlag.NONE);
    }
    tc.waitFor(throughputCount);
    endTime = System.currentTimeMillis();
    LOG.info("Throughput: " + ((long) throughputCount) * 1000 / (endTime - startTime));

    bc.close();
    scheduler.shutdown();
    eventLoop.shutdownGracefully();
    executor.shutdown();
}