Java Code Examples for io.netty.buffer.ByteBuf.retain()

The following are Jave code examples for showing how to use retain() of the io.netty.buffer.ByteBuf class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: kcp-netty   File: UkcpServerChannel.java   Source Code and License Vote up 6 votes
@Override
protected Object filterOutboundMessage(Object msg) {
    if (msg instanceof UkcpPacket) {
        UkcpPacket p = (UkcpPacket) msg;
        ByteBuf content = p.content();
        if (isSingleDirectBuffer(content)) {
            return p;
        }
        content.retain(); // newDirectBuffer method call release method of content
        UkcpPacket np = UkcpPacket.newInstance(newDirectBuffer(content), p.remoteAddress());
        p.release();
        return np;
    }

    throw new UnsupportedOperationException(
            "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
}
 
Example 2
Project: hekate   File: NetworkProtocolCodec.java   Source Code and License Vote up 5 votes
private Object decodeUser(ByteBuf in, int offset, int length) throws IOException {
    // Make sure that buffer will not be recycled until message is processed.
    in.retain();

    try {
        return message(in, offset, length);
    } catch (RuntimeException | Error | IOException e) {
        in.release();

        throw e;
    }
}
 
Example 3
Project: util4j   File: WebSocketTextFrameByteBufAdapter.java   Source Code and License Vote up 5 votes
/**
 * 将webSocket消息转换为bytebuf类型,以适配后面的解码器
 */
@Override
protected void decode(ChannelHandlerContext paramChannelHandlerContext,
		WebSocketFrame paramINBOUND_IN, List<Object> paramList)
		throws Exception {
	if(paramINBOUND_IN instanceof TextWebSocketFrame)
	{
		TextWebSocketFrame msg=(TextWebSocketFrame)paramINBOUND_IN;
		ByteBuf data = msg.content();
		paramList.add(data);
		data.retain();
		log.debug("TextWebSocketFrame to ByteBuf,size="+data.readableBytes());
	}
}
 
Example 4
Project: util4j   File: WebSocketTextFrameByteBufAdapter.java   Source Code and License Vote up 5 votes
/**
 * 对于业务层直接发送的bytebuf实例将其转换为websocket消息
 */
@Override
protected void encode(ChannelHandlerContext paramChannelHandlerContext,
		ByteBuf paramOUTBOUND_IN, List<Object> paramList) throws Exception {
	paramList.add(new TextWebSocketFrame(paramOUTBOUND_IN));
	paramOUTBOUND_IN.retain();
	log.debug("ByteBuf to TextWebSocketFrame,size="+paramOUTBOUND_IN.readableBytes());
}
 
Example 5
Project: util4j   File: WebSocketBinaryFrameByteBufAdapter.java   Source Code and License Vote up 5 votes
/**
 * 将webSocket消息转换为bytebuf类型,以适配后面的解码器
 */
@Override
protected void decode(ChannelHandlerContext paramChannelHandlerContext,
		WebSocketFrame paramINBOUND_IN, List<Object> paramList)
		throws Exception {
	if(paramINBOUND_IN instanceof BinaryWebSocketFrame)
	{
		BinaryWebSocketFrame msg=(BinaryWebSocketFrame)paramINBOUND_IN;
		ByteBuf data = msg.content();
		paramList.add(data);
		data.retain();
	}
}
 
Example 6
Project: util4j   File: WebSocketBinaryFrameByteBufAdapter.java   Source Code and License Vote up 5 votes
/**
 * 对于业务层直接发送的bytebuf实例将其转换为websocket消息
 */
@Override
protected void encode(ChannelHandlerContext paramChannelHandlerContext,
		ByteBuf paramOUTBOUND_IN, List<Object> paramList) throws Exception {
	paramList.add(new BinaryWebSocketFrame(paramOUTBOUND_IN));
	paramOUTBOUND_IN.retain();
}
 
Example 7
Project: spark_deep   File: SaslMessage.java   Source Code and License Vote up 5 votes
public static org.apache.spark.network.sasl.SaslMessage decode(ByteBuf buf) {
  if (buf.readByte() != TAG_BYTE) {
    throw new IllegalStateException("Expected SaslMessage, received something else"
      + " (maybe your client does not have SASL enabled?)");
  }

  String appId = Encoders.Strings.decode(buf);
  // See comment in encodedLength().
  buf.readInt();
  return new org.apache.spark.network.sasl.SaslMessage(appId, buf.retain());
}
 
Example 8
Project: spark_deep   File: ChunkFetchSuccess.java   Source Code and License Vote up 5 votes
/** Decoding uses the given ByteBuf as our data, and will retain() it. */
public static org.apache.spark.network.protocol.ChunkFetchSuccess decode(ByteBuf buf) {
  StreamChunkId streamChunkId = StreamChunkId.decode(buf);
  buf.retain();
  NettyManagedBuffer managedBuf = new NettyManagedBuffer(buf.duplicate());
  return new org.apache.spark.network.protocol.ChunkFetchSuccess(streamChunkId, managedBuf);
}
 
Example 9
Project: dremio-oss   File: AttemptManager.java   Source Code and License Vote up 5 votes
public void dataFromScreenArrived(QueryData header, ByteBuf data, ResponseSender sender) throws RpcException {
  if(data != null){
    // we're going to send this some place, we need increment to ensure this is around long enough to send.
    data.retain();
    observers.execDataArrived(new ScreenShuttle(sender), new QueryWritableBatch(header, data));
  } else {
    observers.execDataArrived(new ScreenShuttle(sender), new QueryWritableBatch(header));
  }

}
 
Example 10
Project: dremio-oss   File: RpcBus.java   Source Code and License Vote up 5 votes
RequestEvent(int coordinationId, C connection, int rpcType, byte[] pBody, ByteBuf dBody) {
  sender = new ResponseSenderImpl();
  this.connection = connection;
  this.rpcType = rpcType;
  this.pBody = pBody;
  this.dBody = dBody;
  sender.set(connection, coordinationId);

  if(dBody != null){
    dBody.retain();
  }
}
 
Example 11
Project: dremio-oss   File: RpcBus.java   Source Code and License Vote up 5 votes
public ResponseEvent(C connection, int rpcType, int coordinationId, byte[] pBody, ByteBuf dBody) {
  this.rpcType = rpcType;
  this.coordinationId = coordinationId;
  this.pBody = pBody;
  this.dBody = dBody;
  this.connection = connection;

  if(dBody != null){
    dBody.retain();
  }
}
 
Example 12
Project: QDrill   File: RpcDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
  if (!ctx.channel().isOpen()) {
    return;
  }

  if (RpcConstants.EXTRA_DEBUGGING) {
    logger.debug("Inbound rpc message received.");
  }

  // now, we know the entire message is in the buffer and the buffer is constrained to this message. Additionally,
  // this process should avoid reading beyond the end of this buffer so we inform the ByteBufInputStream to throw an
  // exception if be go beyond readable bytes (as opposed to blocking).
  final ByteBufInputStream is = new ByteBufInputStream(buffer, buffer.readableBytes());

  // read the rpc header, saved in delimited format.
  checkTag(is, RpcEncoder.HEADER_TAG);
  final RpcHeader header = RpcHeader.parseDelimitedFrom(is);

  if (RpcConstants.EXTRA_DEBUGGING) {
    logger.debug(" post header read index {}", buffer.readerIndex());
  }

  // read the protobuf body into a buffer.
  checkTag(is, RpcEncoder.PROTOBUF_BODY_TAG);
  final int pBodyLength = readRawVarint32(is);
  final ByteBuf pBody = buffer.slice(buffer.readerIndex(), pBodyLength);
  buffer.skipBytes(pBodyLength);
  pBody.retain(1);
  if (RpcConstants.EXTRA_DEBUGGING) {
    logger.debug("Read protobuf body of length {} into buffer {}.", pBodyLength, pBody);
  }

  if (RpcConstants.EXTRA_DEBUGGING) {
    logger.debug("post protobufbody read index {}", buffer.readerIndex());
  }

  ByteBuf dBody = null;
  int dBodyLength = 0;

  // read the data body.
  if (buffer.readableBytes() > 0) {

    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug("Reading raw body, buffer has {} bytes available, is available {}.", buffer.readableBytes(), is.available());
    }
    checkTag(is, RpcEncoder.RAW_BODY_TAG);
    dBodyLength = readRawVarint32(is);
    if (buffer.readableBytes() != dBodyLength) {
      throw new CorruptedFrameException(String.format("Expected to receive a raw body of %d bytes but received a buffer with %d bytes.", dBodyLength, buffer.readableBytes()));
    }
    dBody = buffer.slice();
    dBody.retain(1);
    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug("Read raw body of {}", dBody);
    }

  }else{
    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug("No need to read raw body, no readable bytes left.");
    }
  }


  // return the rpc message.
  InboundRpcMessage m = new InboundRpcMessage(header.getMode(), header.getRpcType(), header.getCoordinationId(),
      pBody, dBody);

  // move the reader index forward so the next rpc call won't try to work with it.
  buffer.skipBytes(dBodyLength);
  messageCounter.incrementAndGet();
  if (RpcConstants.SOME_DEBUGGING) {
    logger.debug("Inbound Rpc Message Decoded {}.", m);
  }
  out.add(m);

}
 
Example 13
Project: spark_deep   File: RpcResponse.java   Source Code and License Vote up 4 votes
public static org.apache.spark.network.protocol.RpcResponse decode(ByteBuf buf) {
  long requestId = buf.readLong();
  // See comment in encodedLength().
  buf.readInt();
  return new org.apache.spark.network.protocol.RpcResponse(requestId, new NettyManagedBuffer(buf.retain()));
}
 
Example 14
Project: spark_deep   File: OneWayMessage.java   Source Code and License Vote up 4 votes
public static org.apache.spark.network.protocol.OneWayMessage decode(ByteBuf buf) {
  // See comment in encodedLength().
  buf.readInt();
  return new org.apache.spark.network.protocol.OneWayMessage(new NettyManagedBuffer(buf.retain()));
}
 
Example 15
Project: spark_deep   File: RpcRequest.java   Source Code and License Vote up 4 votes
public static org.apache.spark.network.protocol.RpcRequest decode(ByteBuf buf) {
  long requestId = buf.readLong();
  // See comment in encodedLength().
  buf.readInt();
  return new org.apache.spark.network.protocol.RpcRequest(requestId, new NettyManagedBuffer(buf.retain()));
}
 
Example 16
Project: dremio-oss   File: RpcCheckedFuture.java   Source Code and License Vote up 4 votes
public void setBuffer(ByteBuf buffer) {
  if (buffer != null) {
    buffer.retain();
    this.buffer = buffer;
  }
}
 
Example 17
Project: dremio-oss   File: LocalStatefulOutputStream.java   Source Code and License Vote up 4 votes
protected WriteDataCommand(WriteDataRequest request, ByteBuf buf) {
  buf.retain();
  this.buf = buf;
  this.request = request;
}
 
Example 18
Project: jsf-sdk   File: LengthFieldBasedFrameDecoder.java   Source Code and License Vote up 3 votes
/**
     * Extract the sub-region of the specified buffer.
     * <p/>
     * If you are sure that the frame and its content are not accessed after
     * the current {@link #decode(ChannelHandlerContext, ByteBuf)}
     * call returns, you can even avoid memory copy by returning the sliced
     * sub-region (i.e. <tt>return buffer.slice(index, length)</tt>).
     * It's often useful when you convert the extracted frame into an object.
     * Refer to the source code of {@link io.netty.handler.codec.serialization.ObjectDecoder} to see how this method
     * is overridden to avoid memory copy.
     */
    protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
//        ByteBuf frame = ctx.alloc().buffer(length);
//        frame.writeBytes(buffer, index, length);
//        return frame;
        buffer.retain();
        return buffer.slice(index, length);
    }