Example usage for io.netty.buffer ByteBuf markReaderIndex

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

Introduction

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

Prototype

public abstract ByteBuf markReaderIndex();

Source Link

Document

Marks the current readerIndex in this buffer.

Usage

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

License:Open Source License

public synchronized List<Packet> handleServerBoundPackets(ByteBuf bufferClone)
        throws InstantiationException, IllegalAccessException {
    List<Packet> list = new ArrayList<>();
    if (bufferClone.readableBytes() == 0) {
        return list;
    }/* w ww. j  av  a 2 s  .c om*/
    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.getServerBoundPacket(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: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  www . j a  v a  2  s .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:nats.client.DefaultMessage.java

License:Open Source License

public DefaultMessage(String subject, ByteBuf body, String queueGroup, boolean request) {
    this.subject = subject;
    this.body = body;
    body.markReaderIndex();
    this.queueGroup = queueGroup;
    isRequest = request;/*from  ww  w.j  a v a 2 s  .  c  o m*/
}

From source file:nats.codec.ClientPublishFrame.java

License:Open Source License

public ClientPublishFrame(String subject, ByteBuf body, String replyTo) {
    // TODO Validate subject, replyTo What is valid?
    this.subject = subject;
    body.markReaderIndex();
    this.body = body;
    this.replyTo = replyTo;
}

From source file:nats.codec.ServerPublishFrame.java

License:Open Source License

public ServerPublishFrame(String id, String subject, String replyTo, ByteBuf body) {
    this.id = id;
    this.subject = subject;
    this.replyTo = replyTo;
    this.body = body;
    body.markReaderIndex();
}

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  ww  w .ja v  a  2 s. 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:org.apache.bookkeeper.bookie.Bookie.java

License:Apache License

public void setExplicitLac(ByteBuf entry, WriteCallback writeCallback, Object ctx, byte[] masterKey)
        throws IOException, InterruptedException, BookieException {
    try {//w w  w .  j av  a  2s  . c  o m
        long ledgerId = entry.getLong(entry.readerIndex());
        LedgerDescriptor handle = handles.getHandle(ledgerId, masterKey);
        synchronized (handle) {
            entry.markReaderIndex();
            handle.setExplicitLac(entry);
            entry.resetReaderIndex();
            ByteBuf explicitLACEntry = createExplicitLACEntry(ledgerId, entry);
            getJournal(ledgerId).logAddEntry(explicitLACEntry, false /* ackBeforeSync */, writeCallback, ctx);
        }
    } catch (NoWritableLedgerDirException e) {
        stateManager.transitionToReadOnlyMode();
        throw new IOException(e);
    }
}

From source file:org.apache.bookkeeper.bookie.BufferedChannelTest.java

License:Apache License

public void testBufferedChannel(int byteBufLength, int numOfWrites, int unpersistedBytesBound, boolean flush,
        boolean shouldForceWrite) throws Exception {
    File newLogFile = File.createTempFile("test", "log");
    newLogFile.deleteOnExit();/*w w  w  . j a  va  2  s.c o m*/
    FileChannel fileChannel = new RandomAccessFile(newLogFile, "rw").getChannel();

    BufferedChannel logChannel = new BufferedChannel(UnpooledByteBufAllocator.DEFAULT, fileChannel,
            INTERNAL_BUFFER_WRITE_CAPACITY, INTERNAL_BUFFER_READ_CAPACITY, unpersistedBytesBound);

    ByteBuf dataBuf = generateEntry(byteBufLength);
    dataBuf.markReaderIndex();
    dataBuf.markWriterIndex();

    for (int i = 0; i < numOfWrites; i++) {
        logChannel.write(dataBuf);
        dataBuf.resetReaderIndex();
        dataBuf.resetWriterIndex();
    }

    if (flush && shouldForceWrite) {
        logChannel.flushAndForceWrite(false);
    } else if (flush) {
        logChannel.flush();
    } else if (shouldForceWrite) {
        logChannel.forceWrite(false);
    }

    int expectedNumOfUnpersistedBytes = 0;

    if (flush && shouldForceWrite) {
        /*
         * if flush call is made with shouldForceWrite,
         * then expectedNumOfUnpersistedBytes should be zero.
         */
        expectedNumOfUnpersistedBytes = 0;
    } else if (!flush && shouldForceWrite) {
        /*
         * if flush is not called then internal write buffer is not flushed,
         * but while adding entries to BufferedChannel if writeBuffer has
         * reached its capacity then it will call flush method, and the data
         * gets added to the file buffer. So though explicitly we are not
         * calling flush method, implicitly flush gets called when
         * writeBuffer reaches its capacity.
         */
        expectedNumOfUnpersistedBytes = (byteBufLength * numOfWrites) % INTERNAL_BUFFER_WRITE_CAPACITY;
    } else {
        expectedNumOfUnpersistedBytes = (byteBufLength * numOfWrites) - unpersistedBytesBound;
    }

    Assert.assertEquals("Unpersisted bytes", expectedNumOfUnpersistedBytes, logChannel.getUnpersistedBytes());
    logChannel.close();
    fileChannel.close();
}

From source file:org.apache.bookkeeper.bookie.IndexPersistenceMgrTest.java

License:Apache License

void validateFileInfo(IndexPersistenceMgr indexPersistenceMgr, long ledgerId, int headerVersion)
        throws IOException, GeneralSecurityException {
    BookKeeper.DigestType digestType = BookKeeper.DigestType.CRC32;
    boolean getUseV2WireProtocol = true;

    preCreateFileInfoForLedger(ledgerId, headerVersion);
    DigestManager digestManager = DigestManager.instantiate(ledgerId, masterKey,
            BookKeeper.DigestType.toProtoDigestType(digestType), UnpooledByteBufAllocator.DEFAULT,
            getUseV2WireProtocol);/*from  w  ww . j  a  v a  2 s . co m*/

    CachedFileInfo fileInfo = indexPersistenceMgr.getFileInfo(ledgerId, masterKey);
    fileInfo.readHeader();
    assertEquals("ExplicitLac should be null", null, fileInfo.getExplicitLac());
    assertEquals("Header Version should match with precreated fileinfos headerversion", headerVersion,
            fileInfo.headerVersion);
    assertTrue("Masterkey should match with precreated fileinfos masterkey",
            Arrays.equals(masterKey, fileInfo.masterKey));
    long explicitLac = 22;
    ByteBuf explicitLacByteBuf = digestManager.computeDigestAndPackageForSendingLac(explicitLac).getBuffer(0);
    explicitLacByteBuf.markReaderIndex();
    indexPersistenceMgr.setExplicitLac(ledgerId, explicitLacByteBuf);
    explicitLacByteBuf.resetReaderIndex();
    assertEquals("explicitLac ByteBuf contents should match", 0,
            ByteBufUtil.compare(explicitLacByteBuf, indexPersistenceMgr.getExplicitLac(ledgerId)));
    /*
     * release fileInfo untill it is marked dead and closed, so that
     * contents of it are persisted.
     */
    while (fileInfo.refCount.get() != FileInfoBackingCache.DEAD_REF) {
        fileInfo.release();
    }
    /*
     * reopen the fileinfo and readHeader, so that whatever was persisted
     * would be read.
     */
    fileInfo = indexPersistenceMgr.getFileInfo(ledgerId, masterKey);
    fileInfo.readHeader();
    assertEquals("Header Version should match with precreated fileinfos headerversion even after reopening",
            headerVersion, fileInfo.headerVersion);
    assertTrue("Masterkey should match with precreated fileinfos masterkey",
            Arrays.equals(masterKey, fileInfo.masterKey));
    if (headerVersion == FileInfo.V0) {
        assertEquals(
                "Since it is V0 Header, explicitLac will not be persisted and should be null after reopening",
                null, indexPersistenceMgr.getExplicitLac(ledgerId));
    } else {
        explicitLacByteBuf.resetReaderIndex();
        assertEquals(
                "Since it is V1 Header, explicitLac will be persisted and should not be null after reopening",
                0, ByteBufUtil.compare(explicitLacByteBuf, indexPersistenceMgr.getExplicitLac(ledgerId)));
    }
}

From source file:org.apache.camel.component.netty4.http.NettyChannelBufferStreamCache.java

License:Apache License

public NettyChannelBufferStreamCache(ByteBuf buffer) {
    this.buffer = buffer;
    buffer.markReaderIndex();
}