List of usage examples for io.netty.buffer ByteBuf writeBytes
public abstract int writeBytes(ScatteringByteChannel in, int length) throws IOException;
From source file:alluxio.worker.block.io.LocalFileBlockReader.java
License:Apache License
@Override public int transferTo(ByteBuf buf) throws IOException { return buf.writeBytes(mLocalFileChannel, buf.writableBytes()); }
From source file:alluxio.worker.block.RemoteBlockReader.java
License:Apache License
@Override public int transferTo(ByteBuf buf) throws IOException { Preconditions.checkState(!mClosed);/*from ww w . j av a 2 s . co m*/ init(); if (mInputStream == null || mInputStream.remaining() <= 0) { return -1; } int bytesToRead = (int) Math.min(buf.writableBytes(), mInputStream.remaining()); return buf.writeBytes(mInputStream, bytesToRead); }
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 w w w . j a va 2s .c o m*/ * @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:alluxio.worker.netty.DataServerBlockReadHandler.java
License:Apache License
@Override protected DataBuffer getDataBuffer(Channel channel, long offset, int len) throws IOException { BlockReader blockReader = ((BlockReadRequestInternal) mRequest).mBlockReader; Preconditions.checkArgument(blockReader.getChannel() instanceof FileChannel, "Only FileChannel is supported!"); switch (mTransferType) { case MAPPED:/*from ww w. j ava 2 s .c o m*/ ByteBuf buf = channel.alloc().buffer(len, len); try { FileChannel fileChannel = (FileChannel) blockReader.getChannel(); Preconditions.checkState(fileChannel.position() == offset); while (buf.writableBytes() > 0 && buf.writeBytes(fileChannel, buf.writableBytes()) != -1) { } return new DataNettyBufferV2(buf); } catch (Throwable e) { buf.release(); throw e; } case TRANSFER: // intend to fall through as TRANSFER is the default type. default: return new DataFileChannel((FileChannel) blockReader.getChannel(), offset, len); } }
From source file:alluxio.worker.netty.DataServerUFSFileReadHandler.java
License:Apache License
@Override protected DataBuffer getDataBuffer(Channel channel, long offset, int len) throws IOException { ByteBuf buf = channel.alloc().buffer(len, len); try {//w w w . ja v a 2s . c om InputStream in = ((FileReadRequestInternal) mRequest).mInputStream; if (in != null) { // if we have not reached the end of the file while (buf.writableBytes() > 0 && buf.writeBytes(in, buf.writableBytes()) != -1) { } } if (buf.readableBytes() == 0) { buf.release(); return null; } return new DataNettyBufferV2(buf); } catch (Throwable e) { buf.release(); throw e; } }
From source file:com.addthis.meshy.ChannelState.java
License:Apache License
public ByteBuf allocateSendBuffer(int type, int session, ByteBuf from, int length) { ByteBuf sendBuffer = channel.alloc().buffer(MESHY_BYTE_OVERHEAD + length); sendBuffer.writeInt(type);//from w w w . ja va2s. c o m sendBuffer.writeInt(session); sendBuffer.writeInt(length); sendBuffer.writeBytes(from, length); return sendBuffer; }
From source file:com.comphenix.protocol.events.PacketContainer.java
License:Open Source License
private void readObject(ObjectInputStream input) throws ClassNotFoundException, IOException { // Default deserialization input.defaultReadObject();/*from w ww. j av a 2 s . co m*/ // Get structure modifier structureModifier = StructureCache.getStructure(type); // Don't read NULL packets if (input.readBoolean()) { // Create a default instance of the packet handle = StructureCache.newPacket(type); // Call the read method try { if (MinecraftReflection.isUsingNetty()) { ByteBuf buffer = createPacketBuffer(); buffer.writeBytes(input, input.readInt()); MinecraftMethods.getPacketReadByteBufMethod().invoke(handle, buffer); } else { if (input.readInt() != -1) throw new IllegalArgumentException("Cannot load a packet from 1.7.2 in 1.6.4."); getMethodLazily(readMethods, handle.getClass(), "read", DataInput.class).invoke(handle, new DataInputStream(input)); } } catch (IllegalArgumentException e) { throw new IOException("Minecraft packet doesn't support DataInputStream", e); } catch (IllegalAccessException e) { throw new RuntimeException("Insufficient security privileges.", e); } catch (InvocationTargetException e) { throw new IOException("Could not deserialize Minecraft packet.", e); } // And we're done structureModifier = structureModifier.withTarget(handle); } }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all multi lookup response messages. * * @param request the current request./*from w w w .j ava 2s.co m*/ * @param msg the current response message. * @param ctx the handler context. * @param status the response status code. * @return the decoded response or null if it wasn't a subdocument multi lookup. */ private static CouchbaseResponse handleSubdocumentMultiLookupResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status) { if (!(request instanceof BinarySubdocMultiLookupRequest)) return null; BinarySubdocMultiLookupRequest subdocRequest = (BinarySubdocMultiLookupRequest) request; short statusCode = msg.getStatus(); long cas = msg.getCAS(); String bucket = request.bucket(); ByteBuf body = msg.content(); List<MultiResult<Lookup>> responses; if (status.isSuccess() || ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) { long bodyLength = body.readableBytes(); List<LookupCommand> commands = subdocRequest.commands(); responses = new ArrayList<MultiResult<Lookup>>(commands.size()); for (LookupCommand cmd : commands) { if (msg.content().readableBytes() < 6) { body.release(); throw new IllegalStateException("Expected " + commands.size() + " lookup responses, only got " + responses.size() + ", total of " + bodyLength + " bytes"); } short cmdStatus = body.readShort(); int valueLength = body.readInt(); ByteBuf value = ctx.alloc().buffer(valueLength, valueLength); value.writeBytes(body, valueLength); responses.add(MultiResult.create(cmdStatus, ResponseStatusConverter.fromBinary(cmdStatus), cmd.path(), cmd.lookup(), value)); } } else { responses = Collections.emptyList(); } body.release(); return new MultiLookupResponse(status, statusCode, bucket, responses, subdocRequest, cas); }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java
License:Apache License
/** * Helper method to decode all multi mutation response messages. * * @param request the current request./*from w ww . j a va 2 s.c o m*/ * @param msg the current response message. * @param ctx the handler context. * @param status the response status code. * @return the decoded response or null if it wasn't a subdocument multi lookup. */ private static CouchbaseResponse handleSubdocumentMultiMutationResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status, boolean seqOnMutation) { if (!(request instanceof BinarySubdocMultiMutationRequest)) return null; BinarySubdocMultiMutationRequest subdocRequest = (BinarySubdocMultiMutationRequest) request; long cas = msg.getCAS(); short statusCode = msg.getStatus(); String bucket = request.bucket(); MutationToken mutationToken = null; if (msg.getExtrasLength() > 0) { mutationToken = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); } MultiMutationResponse response; ByteBuf body = msg.content(); List<MultiResult<Mutation>> responses; if (status.isSuccess()) { List<MutationCommand> commands = subdocRequest.commands(); responses = new ArrayList<MultiResult<Mutation>>(commands.size()); //MB-17842: Mutations can have a value, so there could be individual results //but only mutation commands that provide a value will have an explicit result in the binary response. //However, we still want MutationResult for all of the commands ListIterator<MutationCommand> it = commands.listIterator(); int explicitResultSize = 0; //as long as there is an explicit response to read... while (msg.content().readableBytes() >= 7) { explicitResultSize++; //...read the data byte responseIndex = body.readByte(); short responseStatus = body.readShort(); //will this always be SUCCESS? int responseLength = body.readInt(); ByteBuf responseValue; if (responseLength > 0) { responseValue = ctx.alloc().buffer(responseLength, responseLength); responseValue.writeBytes(body, responseLength); } else { responseValue = Unpooled.EMPTY_BUFFER; //can an explicit response be 0-length (empty)? } //...sanity check response so subsequent loop don't run forever if (it.nextIndex() > responseIndex) { body.release(); throw new IllegalStateException("Unable to interpret multi mutation response, responseIndex = " + responseIndex + " while next available command was #" + it.nextIndex()); } ///...catch up on all commands before current one that didn't get an explicit response while (it.nextIndex() < responseIndex) { MutationCommand noResultCommand = it.next(); responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS, noResultCommand.path(), noResultCommand.mutation(), Unpooled.EMPTY_BUFFER)); } //...then process the one that did get an explicit response MutationCommand cmd = it.next(); responses.add(MultiResult.create(responseStatus, ResponseStatusConverter.fromBinary(responseStatus), cmd.path(), cmd.mutation(), responseValue)); } //...and finally the remainder of commands after the last one that got an explicit response: while (it.hasNext()) { MutationCommand noResultCommand = it.next(); responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS, noResultCommand.path(), noResultCommand.mutation(), Unpooled.EMPTY_BUFFER)); } if (responses.size() != commands.size()) { body.release(); throw new IllegalStateException( "Multi mutation spec size and result size differ: " + commands.size() + " vs " + responses.size() + ", including " + explicitResultSize + " explicit results"); } response = new MultiMutationResponse(bucket, subdocRequest, cas, mutationToken, responses); } else if (ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) { //MB-17842: order of index and status has been swapped byte firstErrorIndex = body.readByte(); short firstErrorCode = body.readShort(); response = new MultiMutationResponse(status, statusCode, bucket, firstErrorIndex, firstErrorCode, subdocRequest, cas, mutationToken); } else { response = new MultiMutationResponse(status, statusCode, bucket, subdocRequest, cas, mutationToken); } body.release(); return response; }
From source file:com.digitalpetri.modbus.codec.ModbusRequestEncoder.java
License:Apache License
public ByteBuf encodeWriteMultipleCoils(WriteMultipleCoilsRequest request, ByteBuf buffer) { buffer.writeByte(request.getFunctionCode().getCode()); buffer.writeShort(request.getAddress()); buffer.writeShort(request.getQuantity()); int byteCount = (request.getQuantity() + 7) / 8; buffer.writeByte(byteCount);//from w w w . ja va2 s. c o m buffer.writeBytes(request.getValues(), byteCount); return buffer; }