List of usage examples for io.netty.buffer ByteBuf retain
@Override public abstract ByteBuf retain();
From source file:me.ferrybig.p2pnetwork.LocalConnection.java
public ChannelFuture sendPacket(Address destination, Packet packet) { if (!destination.equals(directNode)) { RelayPacket r;/*from w w w. j a v a 2 s.c o m*/ ByteBuf buf = this.channel.alloc().buffer(); try { buf.writeInt(PacketMap.getPacketId(packet)); packet.write(buf); r = new RelayPacket(buf.retain(), ourAddress, ourAddress, 255); } finally { packet.release(); buf.release(); } packet = r; } return sendPacket(packet); }
From source file:me.ferrybig.p2pnetwork.Peer.java
public boolean routePacket(Address to, Packet packet, byte ttl) { MultiConnection router = routingTable.tryRoute(to, this::getByAddress); if (router != null) { if (!(packet instanceof RelayPacket) && !router.getDirectNode().equals(to)) { Packet unwrapped = packet;//from ww w . j ava2s .c om ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(); try { buf.writeInt(PacketMap.getPacketId(unwrapped)); unwrapped.write(buf); packet = new RelayPacket(buf.retain(), address, to, ttl); } finally { unwrapped.release(); buf.release(); } } router.sendPacket(packet).addListener(ErrorLoggingFuture.SINGLETON); return true; } return false; }
From source file:net.tomp2p.storage.AlternativeCompositeByteBuf.java
License:Apache License
public AlternativeCompositeByteBuf addComponent(boolean fillBuffer, ByteBuf... buffers) { if (buffers == null) { throw new NullPointerException("buffers"); }//from w ww . j av a2s . c o m for (ByteBuf b : buffers) { if (b == null) { break; } //We want to use this buffer, so mark is as used b.retain(); addComponentElement(fillBuffer, b); } return this; }
From source file:org.apache.activemq.artemis.tests.integration.stomp.util.AbstractStompClientConnection.java
License:Apache License
private ClientStompFrame sendFrameInternal(ClientStompFrame frame, boolean wicked) throws IOException, InterruptedException { ClientStompFrame response = null;//from w w w .ja v a2 s .co m IntegrationTestLogger.LOGGER.trace("Sending " + (wicked ? "*wicked* " : "") + "frame:\n" + frame); ByteBuffer buffer; if (wicked) { buffer = frame.toByteBufferWithExtra("\n"); } else { buffer = frame.toByteBuffer(); } ByteBuf buf = Unpooled.copiedBuffer(buffer); try { buf.retain(); ChannelFuture future = transport.send(buf); if (future != null) { future.awaitUninterruptibly(); } } finally { buf.release(); } //now response if (frame.needsReply()) { response = receiveFrame(); //filter out server ping while (response != null) { if (response.getCommand().equals(Stomp.Commands.STOMP)) { response = receiveFrame(); } else { break; } } } IntegrationTestLogger.LOGGER.trace("Received:\n" + response); return response; }
From source file:org.apache.arrow.flight.grpc.AddWritableBuffer.java
License:Apache License
/** * Add the provided ByteBuf to the output stream if it is possible. * @param buf The buffer to add./*ww w. j a v a 2s . c o m*/ * @param stream The Candidate OutputStream to add to. * @return True if added. False if not possible. * @throws IOException on error */ public static boolean add(ByteBuf buf, OutputStream stream) throws IOException { buf.readBytes(stream, buf.readableBytes()); if (bufChainOut == null) { return false; } if (!stream.getClass().equals(bufChainOut)) { return false; } try { if (current.get(stream) != null) { return false; } buf.retain(); Object obj = bufConstruct.newInstance(buf); Object list = bufferList.get(stream); listAdd.invoke(list, obj); current.set(stream, obj); return true; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) { e.printStackTrace(); return false; } }
From source file:org.apache.bookkeeper.bookie.Journal.java
License:Apache License
@VisibleForTesting void logAddEntry(long ledgerId, long entryId, ByteBuf entry, boolean ackBeforeSync, WriteCallback cb, Object ctx) throws InterruptedException { //Retain entry until it gets written to journal entry.retain(); journalStats.getJournalQueueSize().inc(); queue.put(QueueEntry.create(entry, ackBeforeSync, ledgerId, entryId, cb, ctx, MathUtils.nowInNano(), journalStats.getJournalAddEntryStats(), journalStats.getJournalQueueSize())); }
From source file:org.apache.bookkeeper.client.BookieWriteLedgerTest.java
License:Apache License
/** * In a loop create/write/delete the ledger with same ledgerId through * the functionality of Advanced Ledger which accepts ledgerId as input. * * @throws Exception// ww w . j av a 2 s . c o m */ @Test public void testLedgerCreateAdvWithLedgerIdInLoop() throws Exception { int ledgerCount = 40; long maxId = 9999999999L; if (baseConf.getLedgerManagerFactoryClass().equals(LongHierarchicalLedgerManagerFactory.class)) { // since LongHierarchicalLedgerManager supports ledgerIds of decimal length upto 19 digits but other // LedgerManagers only upto 10 decimals maxId = Long.MAX_VALUE; } rng.longs(ledgerCount, 0, maxId) // generate a stream of ledger ids .mapToObj(ledgerId -> { // create a ledger for each ledger id LOG.info("Creating adv ledger with id {}", ledgerId); return bkc.newCreateLedgerOp().withEnsembleSize(1).withWriteQuorumSize(1).withAckQuorumSize(1) .withDigestType(org.apache.bookkeeper.client.api.DigestType.CRC32) .withPassword(ledgerPassword).makeAdv().withLedgerId(ledgerId).execute() .thenApply(writer -> { // Add entries to ledger when created LOG.info("Writing stream of {} entries to {}", numEntriesToWrite, ledgerId); List<ByteBuf> entries = rng.ints(numEntriesToWrite, 0, maxInt).mapToObj(i -> { ByteBuf entry = Unpooled.buffer(4); entry.retain(); entry.writeInt(i); return entry; }).collect(Collectors.toList()); CompletableFuture<?> lastRequest = null; int i = 0; for (ByteBuf entry : entries) { long entryId = i++; LOG.info("Writing {}:{} as {}", ledgerId, entryId, entry.slice().readInt()); lastRequest = writer.writeAsync(entryId, entry); } lastRequest.join(); return Pair.of(writer, entries); }); }).parallel().map(CompletableFuture::join) // wait for all creations and adds in parallel .forEach(e -> { // check that each set of adds succeeded try { WriteAdvHandle handle = e.getLeft(); List<ByteBuf> entries = e.getRight(); // Read and verify LOG.info("Read entries for ledger: {}", handle.getId()); readEntries(handle, entries); entries.forEach(ByteBuf::release); handle.close(); bkc.deleteLedger(handle.getId()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); Assert.fail("Test interrupted"); } catch (Exception ex) { LOG.info("Readback failed with exception", ex); Assert.fail("Readback failed " + ex.getMessage()); } }); }
From source file:org.apache.bookkeeper.client.MockLedgerHandle.java
License:Apache License
@Override public void asyncAddEntry(final ByteBuf data, final AddCallback cb, final Object ctx) { if (bk.isStopped()) { cb.addComplete(-1, MockLedgerHandle.this, INVALID_ENTRY_ID, ctx); return;/*from w w w. ja v a 2s. co m*/ } data.retain(); bk.executor.execute(new Runnable() { public void run() { if (bk.getProgrammedFailStatus()) { fenced = true; data.release(); cb.addComplete(bk.failReturnCode, MockLedgerHandle.this, INVALID_ENTRY_ID, ctx); return; } if (bk.isStopped()) { data.release(); cb.addComplete(-1, MockLedgerHandle.this, INVALID_ENTRY_ID, ctx); return; } try { Thread.sleep(1); } catch (InterruptedException e) { } if (fenced) { data.release(); cb.addComplete(BKException.Code.LedgerFencedException, MockLedgerHandle.this, LedgerHandle.INVALID_ENTRY_ID, ctx); } else { lastEntry = entries.size(); byte[] storedData = new byte[data.readableBytes()]; data.readBytes(storedData); LedgerEntry entry = new MockLedgerEntry(ledgerId, lastEntry, storedData); entries.add(entry); data.release(); cb.addComplete(0, MockLedgerHandle.this, lastEntry, ctx); } } }); }
From source file:org.apache.bookkeeper.client.PendingReadOp.java
License:Apache License
@Override public void readEntryComplete(int rc, long ledgerId, final long entryId, final ByteBuf buffer, Object ctx) { final ReadContext rctx = (ReadContext) ctx; final LedgerEntryRequest entry = rctx.entry; if (rc != BKException.Code.OK) { entry.logErrorAndReattemptRead(rctx.bookieIndex, rctx.to, "Error: " + BKException.getMessage(rc), rc); return;// www .j av a 2 s. co m } heardFromHosts.add(rctx.to); heardFromHostsBitSet.set(rctx.bookieIndex, true); buffer.retain(); if (entry.complete(rctx.bookieIndex, rctx.to, buffer)) { if (!isRecoveryRead) { // do not advance LastAddConfirmed for recovery reads lh.updateLastConfirmed(rctx.getLastAddConfirmed(), 0L); } submitCallback(BKException.Code.OK); } else { buffer.release(); } if (numPendingEntries < 0) { LOG.error("Read too many values for ledger {} : [{}, {}].", ledgerId, startEntryId, endEntryId); } }
From source file:org.apache.bookkeeper.client.PulsarMockLedgerHandle.java
License:Apache License
@Override public void asyncAddEntry(final ByteBuf data, final AddCallback cb, final Object ctx) { data.retain(); bk.getProgrammedFailure().thenComposeAsync((res) -> { try {/*from w ww .j ava 2 s .c o m*/ Thread.sleep(1); } catch (InterruptedException e) { } if (fenced) { return FutureUtils.exception(new BKException.BKLedgerFencedException()); } else { lastEntry = entries.size(); byte[] storedData = new byte[data.readableBytes()]; data.readBytes(storedData); entries.add(LedgerEntryImpl.create(ledgerId, lastEntry, storedData.length, Unpooled.wrappedBuffer(storedData))); return FutureUtils.value(lastEntry); } }, bk.executor).whenCompleteAsync((entryId, exception) -> { data.release(); if (exception != null) { fenced = true; cb.addComplete(PulsarMockBookKeeper.getExceptionCode(exception), PulsarMockLedgerHandle.this, INVALID_ENTRY_ID, ctx); } else { cb.addComplete(BKException.Code.OK, PulsarMockLedgerHandle.this, entryId, ctx); } }, bk.executor); }