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

The following are Jave code examples for showing how to use slice() 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: angel   File: ServerArbitraryIntRow.java   Source Code and License Vote up 6 votes
private void densePlusSparse(ByteBuf buf, int size) {
  ByteBuf valueBuf = buf.slice(buf.readerIndex() + size * 4, size * 4);

  int ov, value, key, delta;
  for (int i = 0; i < size; i++) {
    key = buf.readInt();
    ov = denseRep.get(key);
    delta = valueBuf.readInt();
    value = ov + delta;

    if (ov != 0 && value == 0)
      nnz--;
    denseRep.put(key, value);
  }

  buf.readerIndex(buf.readerIndex() + size * 4);

  LOG.info("#######nnz=" + nnz);
  if (nnz < threshold * (endCol - startCol))
    denseToSparse();
}
 
Example 2
Project: Quavo   File: UpdateListener.java   Source Code and License Vote up 6 votes
@Override
public void handleMessage(ChannelHandlerContext ctx, UpdateRequest msg) {
	int type = msg.getType();
	int id = msg.getId();
	ByteBuf container = null;

	try {
		if (type == 0xff && id == 0xff) {
			container = Unpooled.wrappedBuffer(CacheManager.getChecksumBuffer());
		} else {
			container = Unpooled.wrappedBuffer(CacheManager.getCache().getStore().read(type, id));
			if (type != 0xff) {
				container = container.slice(0, container.readableBytes() - 2);
			}
		}
	} catch (IOException e) {
		e.printStackTrace();
	}

	ctx.write(new UpdateResponse(type, id, msg.isPriority(), container));
}
 
Example 3
Project: angel   File: ServerArbitraryIntRow.java   Source Code and License Vote up 5 votes
private void sparsePlusSparse(ByteBuf buf, int size) {
  ByteBuf valueBuf = buf.slice(buf.readerIndex() + size * 4, size * 4);

  for (int i = 0; i < size; i++) {
    sparseRep.addTo(buf.readInt(), valueBuf.readInt());
  }

  nnz = sparseRep.size();
  if (nnz > threshold * (endCol - startCol))
    sparseToDense();

  buf.readerIndex(buf.readerIndex() + size * 4);
}
 
Example 4
Project: angel   File: ServerArbitraryIntRow.java   Source Code and License Vote up 5 votes
private void initSparseRep(ByteBuf buf, int size) {
  ByteBuf valueBuf = buf.slice(buf.readerIndex() + size * 4, size * 4);
  initSparseRep(nnz);
  for (int i = 0; i < size; i++) {
    sparseRep.put(buf.readInt(), valueBuf.readInt());
  }
  nnz = sparseRep.size();

  buf.readerIndex(buf.readerIndex() + size * 4);
}
 
Example 5
Project: proteus-java   File: ProteusMetadata.java   Source Code and License Vote up 5 votes
public static ByteBuf metadata(ByteBuf byteBuf) {
  int offset = VERSION_SIZE + NAMESPACE_ID_SIZE + SERVICE_ID_SIZE + METHOD_ID_SIZE;
  int length = byteBuf.getInt(offset);
  offset += METADATA_LENGTH_SIZE;

  return byteBuf.slice(offset, length);
}
 
Example 6
Project: QDrill   File: DirectCodecFactory.java   Source Code and License Vote up 5 votes
public ByteBufBytesInput(ByteBuf buf, int offset, int length) {
  super();
  if(buf.capacity() == length && offset == 0){
    this.buf = buf;
  }else{
    this.buf = buf.slice(offset, length);
  }

  this.length = length;
}
 
Example 7
Project: ss-java   File: AbstractBouncycastleCrypto.java   Source Code and License Vote up 5 votes
@Override
protected ByteBuf process(final StreamCipher cipher, ByteBuf data) {
    final ByteBuf slice = data.slice();
    slice.writerIndex(0);
    data.forEachByte(data.readerIndex(), data.readableBytes(), new ByteBufProcessor() {
        @Override
        public boolean process(byte b) throws Exception {
            slice.writeByte(cipher.returnByte(b));
            return true;
        }
    });
    return data;
}
 
Example 8
Project: dremio-oss   File: MessageDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
  if (!ctx.channel().isOpen()) {
    if (in.readableBytes() > 0) {
      logger.info("Channel is closed, discarding remaining {} byte(s) in buffer.", in.readableBytes());
    }
    in.skipBytes(in.readableBytes());
    return;
  }

  in.markReaderIndex();

  /**
   *  a variable-width message length can be up to five bytes in length. read bytes until we have a length.
   */
  final byte[] buf = new byte[5];
  int length = 0;
  for (int i = 0; i < buf.length; i++) {
    if (!in.isReadable()) {
      in.resetReaderIndex();
      return;
    }

    buf[i] = in.readByte();
    if (buf[i] >= 0) {

      length = CodedInputStream.newInstance(buf, 0, i + 1).readRawVarint32();

      if (length < 0) {
        throw new CorruptedFrameException("negative length: " + length);
      }
      if (length == 0) {
        throw new CorruptedFrameException("Received a message of length 0.");
      }

      if (in.readableBytes() < length) {
        in.resetReaderIndex();
        return;
      } else {
        // complete message in buffer.
        break;
      }
    }
  }

  final ByteBuf frame = in.slice(in.readerIndex(), length);
  try {
    final InboundRpcMessage message = decodeMessage(ctx, frame, length);
    if (message != null) {
      out.add(message);
    }
  } finally {
    in.skipBytes(length);
  }
}
 
Example 9
Project: simulacron   File: FrameDecoder.java   Source Code and License Vote up 4 votes
@Override
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
  // use slice instead of retainedSlice (what super does) so don't need to release later.
  return buffer.slice(index, length);
}
 
Example 10
Project: simulacron   File: TestFrameDecoder.java   Source Code and License Vote up 4 votes
@Override
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
  // use slice instead of retainedSlice (what super does) so don't need to release later.
  return buffer.slice(index, length);
}
 
Example 11
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 12
Project: fresco_floodlight   File: ThriftFrameDecoder.java   Source Code and License Vote up 4 votes
@Override
protected final ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index,
        int length) {
    return buffer.slice(index, length);
}
 
Example 13
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);
    }