List of usage examples for io.netty.buffer ByteBuf nioBuffer
public abstract ByteBuffer nioBuffer(int index, int length);
From source file:com.baidu.jprotobuf.pbrpc.transport.handler.RpcDataPackageDecoder.java
License:Apache License
protected Object decode(ChannelHandlerContext ctx, ByteBuf buf) throws Exception { // Make sure if the length field was received. if (buf.readableBytes() < RpcHeadMeta.SIZE) { // The length field was not received yet - return null. // This method will be invoked again when more packets are // received and appended to the buffer. return null; }/*from w w w . j ava 2 s . c om*/ // The length field is in the buffer. // Mark the current buffer position before reading the length field // because the whole frame might not be in the buffer yet. // We will reset the buffer position to the marked position if // there's not enough bytes in the buffer. buf.markReaderIndex(); // Read the RPC head long rpcMessageDecoderStart = System.nanoTime(); ByteBuffer buffer = buf.nioBuffer(buf.readerIndex(), RpcHeadMeta.SIZE); buffer.order(ByteOrder.LITTLE_ENDIAN); byte[] bytes = new byte[RpcHeadMeta.SIZE]; buffer.get(bytes); RpcHeadMeta headMeta = new RpcHeadMeta(); headMeta.read(bytes); // get total message size int messageSize = headMeta.getMessageSize() + RpcHeadMeta.SIZE; // Make sure if there's enough bytes in the buffer. if (buf.readableBytes() < messageSize) { // The whole bytes were not received yet - return null. // This method will be invoked again when more packets are // received and appended to the buffer. // Reset to the marked position to read the length field again // next time. buf.resetReaderIndex(); return null; } // check magic code String magicCode = headMeta.getMagicCodeAsString(); if (!ProtocolConstant.MAGIC_CODE.equals(magicCode)) { throw new Exception("Error magic code:" + magicCode); } // There's enough bytes in the buffer. Read it. byte[] totalBytes = new byte[messageSize]; buf.readBytes(totalBytes, 0, messageSize); RpcDataPackage rpcDataPackage = new RpcDataPackage(); rpcDataPackage.setTimeStamp(System.currentTimeMillis()); rpcDataPackage.read(totalBytes); // check if a chunk package if (rpcDataPackage.isChunkPackage()) { Long chunkStreamId = rpcDataPackage.getChunkStreamId(); RpcDataPackage chunkDataPackage = tempTrunkPackages.get(chunkStreamId); if (chunkDataPackage == null) { chunkDataPackage = rpcDataPackage; tempTrunkPackages.put(chunkStreamId, rpcDataPackage); } else { chunkDataPackage.mergeData(rpcDataPackage.getData()); } if (rpcDataPackage.isFinalPackage()) { chunkDataPackage.chunkInfo(chunkStreamId, -1); tempTrunkPackages.remove(chunkStreamId); return chunkDataPackage; } return null; } long rpcMessageDecoderEnd = System.nanoTime(); LOG.log(Level.FINE, "[profiling] nshead decode cost : " + (rpcMessageDecoderEnd - rpcMessageDecoderStart) / 1000); return rpcDataPackage; }
From source file:com.cloudera.livy.client.local.rpc.KryoMessageCodec.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 4) { return;//www. java2 s .c om } in.markReaderIndex(); int msgSize = in.readInt(); checkSize(msgSize); if (in.readableBytes() < msgSize) { // Incomplete message in buffer. in.resetReaderIndex(); return; } try { ByteBuffer nioBuffer = maybeDecrypt(in.nioBuffer(in.readerIndex(), msgSize)); Object msg = serializer.deserialize(nioBuffer); LOG.debug("Decoded message of type {} ({} bytes)", msg != null ? msg.getClass().getName() : msg, msgSize); out.add(msg); } finally { in.skipBytes(msgSize); } }
From source file:com.datastax.driver.core.FrameCompressor.java
License:Apache License
protected static ByteBuffer inputNioBuffer(ByteBuf buf) { // Using internalNioBuffer(...) as we only hold the reference in this method and so can // reduce Object allocations. int index = buf.readerIndex(); int len = buf.readableBytes(); return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len); }
From source file:com.datastax.driver.core.FrameCompressor.java
License:Apache License
protected static ByteBuffer outputNioBuffer(ByteBuf buf) { int index = buf.writerIndex(); int len = buf.writableBytes(); return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len); }
From source file:com.digitalpetri.opcua.stack.core.channel.ChunkEncoder.java
License:Apache License
private List<ByteBuf> encode(Delegate delegate, SecureChannel channel, MessageType messageType, ByteBuf messageBuffer, long requestId) throws UaException { List<ByteBuf> chunks = new ArrayList<>(); boolean encrypted = delegate.isEncryptionEnabled(channel); int securityHeaderSize = delegate.getSecurityHeaderSize(channel); int cipherTextBlockSize = delegate.getCipherTextBlockSize(channel); int plainTextBlockSize = delegate.getPlainTextBlockSize(channel); int signatureSize = delegate.getSignatureSize(channel); int maxChunkSize = parameters.getLocalSendBufferSize(); int headerSizes = SecureMessageHeader.SECURE_MESSAGE_HEADER_SIZE + securityHeaderSize; int paddingOverhead = encrypted ? (cipherTextBlockSize > 256 ? 2 : 1) : 0; int maxBlockCount = (maxChunkSize - headerSizes - signatureSize - paddingOverhead) / cipherTextBlockSize; int maxBodySize = (plainTextBlockSize * maxBlockCount - SequenceHeader.SEQUENCE_HEADER_SIZE); while (messageBuffer.readableBytes() > 0) { int bodySize = Math.min(messageBuffer.readableBytes(), maxBodySize); int paddingSize = encrypted ? plainTextBlockSize// w ww . j av a2 s . co m - (SequenceHeader.SEQUENCE_HEADER_SIZE + bodySize + signatureSize + paddingOverhead) % plainTextBlockSize : 0; int plainTextContentSize = SequenceHeader.SEQUENCE_HEADER_SIZE + bodySize + signatureSize + paddingSize + paddingOverhead; assert (plainTextContentSize % plainTextBlockSize == 0); int chunkSize = SecureMessageHeader.SECURE_MESSAGE_HEADER_SIZE + securityHeaderSize + (plainTextContentSize / plainTextBlockSize) * cipherTextBlockSize; ByteBuf chunkBuffer = BufferUtil.buffer(chunkSize); /* Message Header */ SecureMessageHeader messageHeader = new SecureMessageHeader(messageType, messageBuffer.readableBytes() > bodySize ? 'C' : 'F', chunkSize, channel.getChannelId()); SecureMessageHeader.encode(messageHeader, chunkBuffer); /* Security Header */ delegate.encodeSecurityHeader(channel, chunkBuffer); /* Sequence Header */ SequenceHeader sequenceHeader = new SequenceHeader(sequenceNumber.getAndIncrement(), requestId); SequenceHeader.encode(sequenceHeader, chunkBuffer); /* Message Body */ chunkBuffer.writeBytes(messageBuffer, bodySize); /* Padding and Signature */ if (encrypted) { writePadding(cipherTextBlockSize, paddingSize, chunkBuffer); } if (delegate.isSigningEnabled(channel)) { ByteBuffer chunkNioBuffer = chunkBuffer.nioBuffer(0, chunkBuffer.writerIndex()); byte[] signature = delegate.signChunk(channel, chunkNioBuffer); chunkBuffer.writeBytes(signature); } /* Encryption */ if (encrypted) { chunkBuffer.readerIndex(SecureMessageHeader.SECURE_MESSAGE_HEADER_SIZE + securityHeaderSize); assert (chunkBuffer.readableBytes() % plainTextBlockSize == 0); try { int blockCount = chunkBuffer.readableBytes() / plainTextBlockSize; ByteBuffer chunkNioBuffer = chunkBuffer.nioBuffer(chunkBuffer.readerIndex(), blockCount * cipherTextBlockSize); ByteBuf copyBuffer = chunkBuffer.copy(); ByteBuffer plainTextNioBuffer = copyBuffer.nioBuffer(); Cipher cipher = delegate.getAndInitializeCipher(channel); if (delegate instanceof AsymmetricDelegate) { for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) { int position = blockNumber * plainTextBlockSize; int limit = (blockNumber + 1) * plainTextBlockSize; plainTextNioBuffer.position(position).limit(limit); int bytesWritten = cipher.doFinal(plainTextNioBuffer, chunkNioBuffer); assert (bytesWritten == cipherTextBlockSize); } } else { cipher.doFinal(plainTextNioBuffer, chunkNioBuffer); } copyBuffer.release(); } catch (GeneralSecurityException e) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, e); } } chunkBuffer.readerIndex(0).writerIndex(chunkSize); chunks.add(chunkBuffer); } lastRequestId = requestId; return chunks; }
From source file:com.lambdaworks.redis.codec.StringCodec.java
License:Apache License
public void encode(String str, ByteBuf target) { if (str == null) { return;// ww w . j a v a 2 s . c o m } if (utf8) { ByteBufUtil.writeUtf8(target, str); return; } if (ascii) { ByteBufUtil.writeAscii(target, str); return; } CharsetEncoder encoder = CharsetUtil.encoder(charset); int length = (int) ((double) str.length() * encoder.maxBytesPerChar()); target.ensureWritable(length); try { final ByteBuffer dstBuf = target.nioBuffer(0, length); final int pos = dstBuf.position(); CoderResult cr = encoder.encode(CharBuffer.wrap(str), dstBuf, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = encoder.flush(dstBuf); if (!cr.isUnderflow()) { cr.throwException(); } target.writerIndex(target.writerIndex() + dstBuf.position() - pos); } catch (CharacterCodingException x) { throw new IllegalStateException(x); } }
From source file:com.linecorp.armeria.internal.grpc.GrpcMessageMarshaller.java
License:Apache License
private ByteBuf serializeProto(Message message) throws IOException { if (GrpcSerializationFormats.isProto(serializationFormat)) { final ByteBuf buf = alloc.buffer(message.getSerializedSize()); boolean success = false; try {/* w w w . j a va2 s. c om*/ message.writeTo(CodedOutputStream.newInstance(buf.nioBuffer(0, buf.writableBytes()))); buf.writerIndex(buf.capacity()); success = true; } finally { if (!success) { buf.release(); } } return buf; } if (GrpcSerializationFormats.isJson(serializationFormat)) { final ByteBuf buf = alloc.buffer(); boolean success = false; try (ByteBufOutputStream os = new ByteBufOutputStream(buf)) { jsonMarshaller.writeValue(message, os); success = true; } finally { if (!success) { buf.release(); } } return buf; } throw new IllegalStateException("Unknown serialization format: " + serializationFormat); }
From source file:com.vethrfolnir.game.network.login.LoginServerClientHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buff = (ByteBuf) msg; int opcode = buff.readUnsignedByte(); switch (opcode) { case 0xBB:/*from w ww .j a v a2s . c o m*/ ServerKill.read(serverClient, buff); break; case 0xA1: int newId = buff.readInt(); RecievedAlternativeId.read(serverClient, buff, newId); break; default: log.warn("Unknown packet 0x" + PrintData.fillHex(opcode, 2) + ". Dump: " + PrintData.printData(buff.nioBuffer(0, buff.writerIndex()))); break; } buff.release(); }
From source file:com.vethrfolnir.game.network.mu.MuChannelHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buff = (msg instanceof ByteBuffer) ? ctx.alloc().buffer().writeBytes((ByteBuffer) msg) : (ByteBuf) msg;//from w w w. ja v a 2 s. c om buff.readerIndex(2); int opcode = buff.readUnsignedByte(); switch (opcode) { // double opcode case 0xf1: case 0xf3: case 0x0e: case 0x03: buff.readerIndex(buff.readerIndex() - 1); opcode = buff.readUnsignedShort(); // ex 0xF1_03 break; default: break; } if (opcode == 0xe00) { // Time packet? buff.clear(); buff.release(); return; } ReadPacket packet = clientpackets.get(opcode); if (packet != null) { MuClient client = ctx.channel().attr(MuClient.ClientKey).get(); //System.out.println("Got opcode: 0x"+PrintData.fillHex(opcode, 2)+ " packet = \n"+packet.getClass().getSimpleName()); packet.read(client, buff); } else { log.warn("Unknown packet[opcode = 0x" + PrintData.fillHex(opcode, 2) + "]. Dump: "); log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex()))); } //log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex()))); if (buff.refCnt() > 0) { //System.out.println("Handler Release when packet[opcode = 0x"+PrintData.fillHex(opcode, 2)+"]"); buff.release(); } }
From source file:com.vethrfolnir.login.network.mu.ClientChannelHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buff = (ByteBuf) msg; switch (buff.getUnsignedByte(0)) { case 0xC1://from w w w . j av a 2 s. c o m case 0xC2: case 0xC3: case 0xC4: break; default: ctx.close(); buff.release(); //TODO: maybe add a flood protector? log.warn("Client[" + ctx.channel() + "] is not a mu online client! Disconnecting!"); return; } // we are not interested in the header and size; buff.readerIndex(2); int opcode = buff.readUnsignedShort(); switch (opcode) { case 0xf4_03: { // Request Server information int serverId = buff.readUnsignedByte(); ByteBuf buf = ctx.alloc().heapBuffer().order(ByteOrder.LITTLE_ENDIAN); WritePacket packet = SendServerInfo.StaticPacket; packet.write(null, buf, nameService, serverId); packet.markLength(buf); ; ctx.writeAndFlush(buf); break; } case 0xf4_06: { // Request Server list ByteBuf buf = ctx.alloc().heapBuffer().order(ByteOrder.LITTLE_ENDIAN); WritePacket packet = SendServerLists.StaticPacket; packet.write(null, buf, nameService); packet.markLength(buf); ctx.writeAndFlush(buf); break; } default: log.warn("Unkown packet[OPCODE = " + Integer.toHexString(opcode) + "] Dump: " + PrintData.printData(buff.nioBuffer(0, buff.writerIndex()))); ctx.close(); break; } buff.release(); }