Example usage for io.netty.buffer ByteBuf refCnt

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

Introduction

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

Prototype

int refCnt();

Source Link

Document

Returns the reference count of this object.

Usage

From source file:net.epsilony.utils.codec.modbus.handler.ModbusMasterResponseDecoderTest.java

License:Open Source License

@Test
public void testDecodingWithCheckSome() {
    ModbusMasterResponseDecoder decoder = new ModbusMasterResponseDecoder(requests::remove);
    decoder.setWithCheckSum(true);/*from w  w  w . j  a  va2s .  c o m*/
    EmbeddedChannel channel = new EmbeddedChannel(decoder);
    TestData[] datas = initTestData();

    ByteBuf buf = createBuf();

    for (TestData data : datas) {
        data.writeBufferWithCrc(buf);
    }

    channel.writeInbound(buf);

    for (TestData data : datas) {
        Object decoded = channel.readInbound();
        assertEquals(data.response, decoded);
    }
    assertEquals(null, channel.readInbound());
    assertTrue(buf.refCnt() <= 0);
    assertTrue(requests.isEmpty());
}

From source file:net.epsilony.utils.codec.modbus.handler.ModbusSlaveRequestDecoderTest.java

License:Open Source License

@Test
public void testDecode() {

    EmbeddedChannel channel = new EmbeddedChannel(new ModbusSlaveRequestDecoder());

    TestData[] datas = createTestData();
    for (TestData data : datas) {
        ByteBuf buf = createBuf();
        data.writeBuffer(buf);/*from w  ww  .  jav a2 s .co m*/
        channel.writeInbound(buf);
        Object decoded = channel.readInbound();

        assertTrue(buf.refCnt() <= 0);
        ModbusRequest exp = data.createRequest();
        assertEquals(exp, decoded);
    }

    assertEquals(null, channel.readInbound());

    ByteBuf totalBuf = createBuf();
    for (TestData data : datas) {
        data.writeBuffer(totalBuf);
    }

    channel.writeInbound(totalBuf);
    for (TestData data : datas) {
        Object decoded = channel.readInbound();

        ModbusRequest exp = data.createRequest();
        assertEquals(exp, decoded);
    }
    assertTrue(totalBuf.refCnt() <= 0);
    assertEquals(null, channel.readInbound());
}

From source file:net.epsilony.utils.codec.modbus.handler.ModbusSlaveRequestDecoderTest.java

License:Open Source License

@Test
public void testDecodeWithCrc() {

    ModbusSlaveRequestDecoder decoder = new ModbusSlaveRequestDecoder();
    decoder.setWithCheckSum(true);//from  ww w .j a  v  a 2s  .  c  o m
    EmbeddedChannel channel = new EmbeddedChannel(decoder);

    TestData[] datas = createTestData();
    for (TestData data : datas) {
        ByteBuf buf = createBuf();
        data.writeBufferWithCrc(buf);
        channel.writeInbound(buf);
        Object decoded = channel.readInbound();

        assertTrue(buf.refCnt() <= 0);
        ModbusRequest exp = data.createRequest();
        assertEquals(exp, decoded);
    }

    assertEquals(null, channel.readInbound());

    ByteBuf totalBuf = createBuf();
    for (TestData data : datas) {
        data.writeBufferWithCrc(totalBuf);
    }

    channel.writeInbound(totalBuf);
    for (TestData data : datas) {
        Object decoded = channel.readInbound();

        ModbusRequest exp = data.createRequest();
        assertEquals(exp, decoded);
    }
    assertTrue(totalBuf.refCnt() <= 0);
    assertEquals(null, channel.readInbound());
}

From source file:org.apache.bookkeeper.bookie.storage.ldb.ReadCacheTest.java

License:Apache License

@Test
public void multipleSegments() {
    // Test with multiple smaller segments
    ReadCache cache = new ReadCache(UnpooledByteBufAllocator.DEFAULT, 10 * 1024, 2 * 1024);

    assertEquals(0, cache.count());//from w  ww . j a  v  a 2 s . com
    assertEquals(0, cache.size());

    for (int i = 0; i < 10; i++) {
        ByteBuf entry = Unpooled.wrappedBuffer(new byte[1024]);
        entry.setInt(0, i);
        cache.put(1, i, entry);
    }

    for (int i = 0; i < 10; i++) {
        ByteBuf res = cache.get(1, i);
        assertEquals(1, res.refCnt());

        assertEquals(1024, res.readableBytes());
        assertEquals(i, res.getInt(0));
    }

    assertEquals(10, cache.count());
    assertEquals(10 * 1024, cache.size());

    // Putting one more entry, should trigger the 1st segment rollover
    ByteBuf entry = Unpooled.wrappedBuffer(new byte[1024]);
    cache.put(2, 0, entry);

    assertEquals(9, cache.count());
    assertEquals(9 * 1024, cache.size());

    cache.close();
}

From source file:org.apache.bookkeeper.client.BookieWriteLedgerTest.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void testLedgerCreateAdvByteBufRefCnt() throws Exception {
    long ledgerId = rng.nextLong();
    ledgerId &= Long.MAX_VALUE;
    if (!baseConf.getLedgerManagerFactoryClass().equals(LongHierarchicalLedgerManagerFactory.class)) {
        // since LongHierarchicalLedgerManager supports ledgerIds of
        // decimal length upto 19 digits but other
        // LedgerManagers only upto 10 decimals
        ledgerId %= 9999999999L;//ww w . j a  v  a2 s.  c o  m
    }

    final LedgerHandle lh = bkc.createLedgerAdv(ledgerId, 5, 3, 2, digestType, ledgerPassword, null);

    final List<AbstractByteBufAllocator> allocs = Lists.newArrayList(new PooledByteBufAllocator(true),
            new PooledByteBufAllocator(false), new UnpooledByteBufAllocator(true),
            new UnpooledByteBufAllocator(false));

    long entryId = 0;
    for (AbstractByteBufAllocator alloc : allocs) {
        final ByteBuf data = alloc.buffer(10);
        data.writeBytes(("fragment0" + entryId).getBytes());
        assertEquals("ref count on ByteBuf should be 1", 1, data.refCnt());

        CompletableFuture<Integer> cf = new CompletableFuture<>();
        lh.asyncAddEntry(entryId, data, (rc, handle, eId, qwcLatency, ctx) -> {
            CompletableFuture<Integer> future = (CompletableFuture<Integer>) ctx;
            future.complete(rc);
        }, cf);

        int rc = cf.get();
        assertEquals("rc code is OK", BKException.Code.OK, rc);

        for (int i = 0; i < 10; i++) {
            if (data.refCnt() == 0) {
                break;
            }
            TimeUnit.MILLISECONDS.sleep(250); // recycler runs asynchronously
        }
        assertEquals("writing entry with id " + entryId + ", ref count on ByteBuf should be 0 ", 0,
                data.refCnt());

        org.apache.bookkeeper.client.api.LedgerEntry e = lh.read(entryId, entryId).getEntry(entryId);
        assertEquals("entry data is correct", "fragment0" + entryId, new String(e.getEntryBytes()));
        entryId++;
    }

    bkc.deleteLedger(lh.ledgerId);
}

From source file:org.apache.bookkeeper.client.BookieWriteLedgerTest.java

License:Apache License

@Test
@SuppressWarnings("unchecked")
public void testLedgerCreateByteBufRefCnt() throws Exception {
    final LedgerHandle lh = bkc.createLedger(5, 3, 2, digestType, ledgerPassword, null);

    final List<AbstractByteBufAllocator> allocs = Lists.newArrayList(new PooledByteBufAllocator(true),
            new PooledByteBufAllocator(false), new UnpooledByteBufAllocator(true),
            new UnpooledByteBufAllocator(false));

    int entryId = 0;
    for (AbstractByteBufAllocator alloc : allocs) {
        final ByteBuf data = alloc.buffer(10);
        data.writeBytes(("fragment0" + entryId).getBytes());
        assertEquals("ref count on ByteBuf should be 1", 1, data.refCnt());

        CompletableFuture<Integer> cf = new CompletableFuture<>();
        lh.asyncAddEntry(data, (rc, handle, eId, ctx) -> {
            CompletableFuture<Integer> future = (CompletableFuture<Integer>) ctx;
            future.complete(rc);//  w  ww  . j  a v  a 2  s  .  co  m
        }, cf);

        int rc = cf.get();
        assertEquals("rc code is OK", BKException.Code.OK, rc);

        for (int i = 0; i < 10; i++) {
            if (data.refCnt() == 0) {
                break;
            }
            TimeUnit.MILLISECONDS.sleep(250); // recycler runs asynchronously
        }
        assertEquals("writing entry with id " + entryId + ", ref count on ByteBuf should be 0 ", 0,
                data.refCnt());

        org.apache.bookkeeper.client.api.LedgerEntry e = lh.read(entryId, entryId).getEntry(entryId);
        assertEquals("entry data is correct", "fragment0" + entryId, new String(e.getEntryBytes()));
        entryId++;
    }

    bkc.deleteLedger(lh.ledgerId);
}

From source file:org.apache.bookkeeper.proto.ReadEntryProcessor.java

License:Apache License

@Override
protected void processPacket() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Received new read request: {}", request);
    }//from ww  w  .j  a v a2 s  . c om
    int errorCode = BookieProtocol.EOK;
    long startTimeNanos = MathUtils.nowInNano();
    ByteBuf data = null;
    try {
        SettableFuture<Boolean> fenceResult = null;
        if (request.isFencing()) {
            LOG.warn("Ledger: {}  fenced by: {}", request.getLedgerId(), channel.remoteAddress());

            if (request.hasMasterKey()) {
                fenceResult = requestProcessor.getBookie().fenceLedger(request.getLedgerId(),
                        request.getMasterKey());
            } else {
                LOG.error("Password not provided, Not safe to fence {}", request.getLedgerId());
                throw BookieException.create(BookieException.Code.UnauthorizedAccessException);
            }
        }
        data = requestProcessor.getBookie().readEntry(request.getLedgerId(), request.getEntryId());
        if (LOG.isDebugEnabled()) {
            LOG.debug("##### Read entry ##### {} -- ref-count: {}", data.readableBytes(), data.refCnt());
        }
        if (fenceResult != null) {
            handleReadResultForFenceRead(fenceResult, data, startTimeNanos);
            return;
        }
    } catch (Bookie.NoLedgerException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error reading {}", request, e);
        }
        errorCode = BookieProtocol.ENOLEDGER;
    } catch (Bookie.NoEntryException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error reading {}", request, e);
        }
        errorCode = BookieProtocol.ENOENTRY;
    } catch (IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error reading {}", request, e);
        }
        errorCode = BookieProtocol.EIO;
    } catch (BookieException e) {
        LOG.error("Unauthorized access to ledger {}", request.getLedgerId(), e);
        errorCode = BookieProtocol.EUA;
    } catch (Throwable t) {
        LOG.error("Unexpected exception reading at {}:{} : {}", request.getLedgerId(), request.getEntryId(),
                t.getMessage(), t);
        errorCode = BookieProtocol.EBADREQ;
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Read entry rc = {} for {}", errorCode, request);
    }
    sendResponse(data, errorCode, startTimeNanos);
}

From source file:org.apache.bookkeeper.util.ByteBufListTest.java

License:Apache License

@Test
public void testSingle() throws Exception {
    ByteBuf b1 = PooledByteBufAllocator.DEFAULT.heapBuffer(128, 128);
    b1.writerIndex(b1.capacity());//from   ww w  .  j  a  va  2s  .  c o  m
    ByteBufList buf = ByteBufList.get(b1);

    assertEquals(1, buf.size());
    assertEquals(128, buf.readableBytes());
    assertEquals(b1, buf.getBuffer(0));

    assertEquals(buf.refCnt(), 1);
    assertEquals(b1.refCnt(), 1);

    buf.release();

    assertEquals(buf.refCnt(), 0);
    assertEquals(b1.refCnt(), 0);
}

From source file:org.apache.bookkeeper.util.ByteBufListTest.java

License:Apache License

@Test
public void testDouble() throws Exception {
    ByteBuf b1 = PooledByteBufAllocator.DEFAULT.heapBuffer(128, 128);
    b1.writerIndex(b1.capacity());//from   w w w  . jav  a2  s  .  c o m
    ByteBuf b2 = PooledByteBufAllocator.DEFAULT.heapBuffer(128, 128);
    b2.writerIndex(b2.capacity());
    ByteBufList buf = ByteBufList.get(b1, b2);

    assertEquals(2, buf.size());
    assertEquals(256, buf.readableBytes());
    assertEquals(b1, buf.getBuffer(0));
    assertEquals(b2, buf.getBuffer(1));

    assertEquals(buf.refCnt(), 1);
    assertEquals(b1.refCnt(), 1);
    assertEquals(b2.refCnt(), 1);

    buf.release();

    assertEquals(buf.refCnt(), 0);
    assertEquals(b1.refCnt(), 0);
    assertEquals(b2.refCnt(), 0);
}

From source file:org.apache.bookkeeper.util.ByteBufListTest.java

License:Apache License

@Test
public void testClone() throws Exception {
    ByteBuf b1 = PooledByteBufAllocator.DEFAULT.heapBuffer(128, 128);
    b1.writerIndex(b1.capacity());/*from w ww.j  a  va 2 s.  c  om*/
    ByteBuf b2 = PooledByteBufAllocator.DEFAULT.heapBuffer(128, 128);
    b2.writerIndex(b2.capacity());
    ByteBufList buf = ByteBufList.get(b1, b2);

    ByteBufList clone = ByteBufList.clone(buf);

    assertEquals(2, buf.size());
    assertEquals(256, buf.readableBytes());
    assertEquals(b1, buf.getBuffer(0));
    assertEquals(b2, buf.getBuffer(1));

    assertEquals(2, clone.size());
    assertEquals(256, clone.readableBytes());
    assertEquals(b1, clone.getBuffer(0));
    assertEquals(b2, clone.getBuffer(1));

    assertEquals(buf.refCnt(), 1);
    assertEquals(clone.refCnt(), 1);
    assertEquals(b1.refCnt(), 2);
    assertEquals(b2.refCnt(), 2);

    buf.release();

    assertEquals(buf.refCnt(), 0);
    assertEquals(clone.refCnt(), 1);
    assertEquals(b1.refCnt(), 1);
    assertEquals(b2.refCnt(), 1);

    clone.release();

    assertEquals(buf.refCnt(), 0);
    assertEquals(clone.refCnt(), 0);
    assertEquals(b1.refCnt(), 0);
    assertEquals(b2.refCnt(), 0);
}