List of usage examples for io.netty.buffer ByteBuf duplicate
public abstract ByteBuf duplicate();
From source file:alluxio.worker.block.UnderFileSystemBlockReader.java
License:Apache License
/** * This interface is supposed to be used for sequence block reads. * * @param buf the byte buffer//from ww w .j a va 2s.c om * @return the number of bytes read, -1 if it reaches EOF and none was read * @throws IOException if any I/O errors occur when reading the block */ @Override public int transferTo(ByteBuf buf) throws IOException { Preconditions.checkState(!mClosed); if (mUnderFileSystemInputStream == null) { return -1; } if (mBlockMeta.getBlockSize() <= mInStreamPos) { return -1; } // Make a copy of the state to keep track of what we have read in this transferTo call. ByteBuf bufCopy = null; if (mBlockWriter != null) { bufCopy = buf.duplicate(); bufCopy.readerIndex(bufCopy.writerIndex()); } int bytesToRead = (int) Math.min((long) buf.writableBytes(), mBlockMeta.getBlockSize() - mInStreamPos); int bytesRead = buf.writeBytes(mUnderFileSystemInputStream, bytesToRead); if (bytesRead <= 0) { return bytesRead; } mInStreamPos += bytesRead; if (mBlockWriter != null) { bufCopy.writerIndex(buf.writerIndex()); while (bufCopy.readableBytes() > 0) { mBlockWriter.transferFrom(bufCopy); } } return bytesRead; }
From source file:com.addthis.meshy.SourceHandler.java
License:Apache License
@Override public final boolean send(byte[] data, final SendWatcher watcher) { synchronized (channels) { if (channels.isEmpty()) { return false; }/*from w ww. jav a 2 s . c o m*/ int sendType = MeshyConstants.KEY_EXISTING; if (sent.compareAndSet(false, true) || DISABLE_CREATION_FRAMES) { sendType = targetHandler; } final ByteBufAllocator alloc = channels.iterator().next().alloc(); final ByteBuf buffer = allocateSendBuffer(alloc, sendType, session, data); final int reportBytes = data.length; final int peerCount = channels.size(); log.trace("{} send {} to {}", this, buffer.capacity(), peerCount); List<ChannelFuture> futures = new ArrayList<>(peerCount); for (Channel c : channels) { futures.add(c.writeAndFlush(buffer.duplicate().retain())); } AggregateChannelFuture aggregateFuture = new AggregateChannelFuture(futures); aggregateFuture.addListener(ignored -> { master.sentBytes(reportBytes * peerCount); if (watcher != null) { watcher.sendFinished(reportBytes); } }); buffer.release(); return true; } }
From source file:com.addthis.meshy.SourceHandler.java
License:Apache License
protected boolean sendToSingleTarget(Channel channel, byte[] data) { int sendType = MeshyConstants.KEY_EXISTING; final ByteBufAllocator alloc = channel.alloc(); final ByteBuf buffer = allocateSendBuffer(alloc, sendType, session, data); final int reportBytes = data.length; log.trace("{} send {} to {}", this, buffer.capacity(), channel); channel.writeAndFlush(buffer.duplicate().retain()).addListener(ignored -> { master.sentBytes(reportBytes);//from w ww. j av a2s . c o m }); buffer.release(); return true; }
From source file:com.flysoloing.learning.network.netty.http2.tiles.Http2RequestHandler.java
License:Apache License
private void handleImage(String x, String y, ChannelHandlerContext ctx, String streamId, int latency, FullHttpRequest request) {/*w ww .j av a 2 s . co m*/ ByteBuf image = ImageCache.INSTANCE.image(parseInt(x), parseInt(y)); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, image.duplicate()); response.headers().set(CONTENT_TYPE, "image/jpeg"); sendResponse(ctx, streamId, latency, response, request); }
From source file:com.github.sparkfy.network.protocol.ChunkFetchSuccess.java
License:Apache License
/** Decoding uses the given ByteBuf as our data, and will retain() it. */ public static ChunkFetchSuccess decode(ByteBuf buf) { StreamChunkId streamChunkId = StreamChunkId.decode(buf); buf.retain();//from w w w.j av a2 s. co m NettyManagedBuffer managedBuf = new NettyManagedBuffer(buf.duplicate()); return new ChunkFetchSuccess(streamChunkId, managedBuf); }
From source file:com.hazelcast.simulator.protocol.handler.SimulatorProtocolDecoder.java
License:Open Source License
private void decodeSimulatorMessage(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) { long messageId = SimulatorMessageCodec.getMessageId(buffer); AddressLevel dstAddressLevel = AddressLevel .fromInt(SimulatorMessageCodec.getDestinationAddressLevel(buffer)); if (LOGGER.isTraceEnabled()) { LOGGER.trace(format("[%d] %s %s received a message for addressLevel %s", messageId, addressLevel, localAddress, dstAddressLevel)); }// www . j a v a 2 s. c o m if (dstAddressLevel == addressLevel) { SimulatorMessage message = SimulatorMessageCodec.decodeSimulatorMessage(buffer); if (LOGGER.isTraceEnabled()) { LOGGER.trace(format("[%d] %s %s will consume %s", messageId, addressLevel, localAddress, message)); } out.add(message); } else { int addressIndex = SimulatorMessageCodec.getChildAddressIndex(buffer, addressLevelValue); ctx.attr(forwardAddressIndex).set(addressIndex); out.add(buffer.duplicate()); buffer.readerIndex(buffer.readableBytes()); buffer.retain(); } }
From source file:com.hazelcast.simulator.protocol.handler.SimulatorProtocolDecoder.java
License:Open Source License
private void decodeResponse(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) { long messageId = ResponseCodec.getMessageId(buffer); AddressLevel dstAddressLevel = AddressLevel.fromInt(ResponseCodec.getDestinationAddressLevel(buffer)); if (LOGGER.isTraceEnabled()) { LOGGER.trace(format("[%d] %s %s received a response for addressLevel %s", messageId, addressLevel, localAddress, dstAddressLevel)); }/*from ww w . j a va 2 s. com*/ if (dstAddressLevel == addressLevel || dstAddressLevel.isParentAddressLevel(addressLevel)) { Response response = ResponseCodec.decodeResponse(buffer); if (LOGGER.isTraceEnabled()) { LOGGER.trace(format("[%d] %s %s received %s", response.getMessageId(), addressLevel, localAddress, response)); } if (workerJvmManager != null) { workerJvmManager.updateLastSeenTimestamp(response); } out.add(response); } else { int addressIndex = ResponseCodec.getChildAddressIndex(buffer, addressLevelValue); ctx.attr(forwardAddressIndex).set(addressIndex); out.add(buffer.duplicate()); buffer.readerIndex(buffer.readableBytes()); buffer.retain(); } }
From source file:com.ibm.crail.datanode.netty.server.IncomingRequestHandler.java
License:Apache License
private void handleWrite(ChannelHandlerContext ctx, RdmaMsgRx incomingWrite, ByteBuf targetBuf) { /* we make the right offset */ int offset = (int) (incomingWrite.address() - ((DirectBuffer) targetBuf.nioBuffer()).address()); incomingWrite.copyAndReleaseRxPayload(targetBuf.duplicate(), offset); final RdmaMsgTx writeResponse = incomingWrite.makeTxMsg(0, MessageTypes.WRITE_RESP); //FIXME:/* w w w . ja va 2 s . com*/ assert ctx.channel() == this.channel; synchronized (this.channel) { /* write the header only, there is no payload */ this.channel.writeAndFlush(writeResponse.getHeaderPayload()) .addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { writeResponse.releaseHeaderPayload(); } }); } }
From source file:com.mastfrog.tinymavenproxy.FileFinder.java
License:Open Source License
public synchronized void put(final Path path, final ByteBuf content, final DateTime lastModified) { // This method is currently unused, but if we enhance the server to accept // uploads, we will likely need code a lot like this if (content.readableBytes() == 0) { return;//from ww w . ja v a 2s . c om } final ByteBuf buf = content.duplicate(); threadPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { final File target = new File(config.dir, path.toString().replace('/', File.separatorChar)); buf.retain(); if (!target.exists()) { if (!target.getParentFile().exists()) { if (!target.getParentFile().mkdirs()) { throw new IOException("Could not create " + target.getParentFile()); } } if (!target.createNewFile()) { throw new IOException("Could not create " + target); } } try (ByteBufInputStream in = new ByteBufInputStream(buf)) { try (OutputStream out = new BufferedOutputStream(new FileOutputStream(target))) { Streams.copy(in, out, 1024); } } catch (IOException ioe) { if (target.exists()) { target.delete(); } throw ioe; } finally { buf.release(); } threadPool.submit(new Runnable() { @Override public void run() { if (lastModified != null) { target.setLastModified(lastModified.getMillis()); } } }); return null; } }); }
From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPWriterTest.java
License:Apache License
@Test public void testOneFrame() throws Exception { final ZMTPWriter writer = ZMTPWriter.create(ZMTP10); final ByteBuf buf = Unpooled.buffer(); writer.reset(buf);/*w w w .j a v a2 s . com*/ ByteBuf frame = writer.frame(11, false); assertThat(frame, is(sameInstance(buf))); final ByteBuf content = copiedBuffer("hello world", UTF_8); frame.writeBytes(content.duplicate()); final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat(ZMTP10), new RawDecoder()); decoder.decode(null, buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) singletonList(content))); }