Java Code Examples for io.netty.buffer.ByteBuf#getInt()

The following examples show how to use io.netty.buffer.ByteBuf#getInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RntbdRequestDecoder.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
/**
 * Prepare for decoding an @{link RntbdRequest} or fire a channel readTree event to pass the input message along.
 *
 * @param context the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param message the message to be decoded
 * @throws Exception thrown if an error occurs
 */
@Override
public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception {

    if (message instanceof ByteBuf) {

        final ByteBuf in = (ByteBuf) message;
        final int resourceOperationType = in.getInt(in.readerIndex() + Integer.BYTES);

        if (resourceOperationType != 0) {
            super.channelRead(context, message);
            return;
        }
    }

    context.fireChannelRead(message);
}
 
Example 2
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
private static <T> T[] binaryDecodeArray(IntFunction<T[]> supplier, DataType type, int index, int len, ByteBuf buff) {
  if (len == 12) {
    return supplier.apply(0);
  }
  int dim = buff.getInt(index);    // read ndim
  index += 4;
  index += 4;                      // skip dataoffset
  index += 4;                      // skip elemtype
  int length = buff.getInt(index); // read dimensions
  index += 4;
  index += 4;                      // skip lower bnds
  if (dim != 1) {
    logger.warn("Only arrays of dimension 1 are supported");
    return null;
  }
  T[] array = supplier.apply(length);
  for (int i = 0; i < array.length; i++) {
    int l = buff.getInt(index);
    index += 4;
    if (l != -1) {
      array[i] = (T) decodeBinary(type, index, l, buff);
      index += l;
    }
  }
  return array;
}
 
Example 3
Source File: HttpServerPipelineConfigurator.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (keepAliveHandler != null) {
        keepAliveHandler.onReadOrWrite();
    }

    if (in.readableBytes() < 4) {
        return;
    }

    if (in.getInt(in.readerIndex()) == 0x50524920) { // If starts with 'PRI '
        // Probably HTTP/2; received the HTTP/2 preface string.
        configureHttp2(ctx);
    } else {
        // Probably HTTP/1; the client can still upgrade using the traditional HTTP/1 upgrade request.
        configureHttp1WithUpgrade(ctx);
    }

    ctx.pipeline().remove(this);
}
 
Example 4
Source File: Netty4MessageChannelHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Transports.assertTransportThread();
    if (!(msg instanceof ByteBuf)) {
        ctx.fireChannelRead(msg);
        return;
    }
    final ByteBuf buffer = (ByteBuf) msg;
    final int remainingMessageSize = buffer.getInt(buffer.readerIndex() - TcpHeader.MESSAGE_LENGTH_SIZE);
    final int expectedReaderIndex = buffer.readerIndex() + remainingMessageSize;
    try {
        Channel channel = ctx.channel();
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        // netty always copies a buffer, either in NioWorker in its read handler, where it copies to a fresh
        // buffer, or in the cumulative buffer, which is cleaned each time so it could be bigger than the actual size
        BytesReference reference = Netty4Utils.toBytesReference(buffer, remainingMessageSize);
        Attribute<NettyTcpChannel> channelAttribute = channel.attr(Netty4Transport.CHANNEL_KEY);
        transport.messageReceived(reference, channelAttribute.get(), profileName, remoteAddress, remainingMessageSize);
    } finally {
        // Set the expected position of the buffer, no matter what happened
        buffer.readerIndex(expectedReaderIndex);
    }
}
 
Example 5
Source File: KcpTestClient.java    From dfactor with MIT License 6 votes vote down vote up
@Override
		protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket pack) throws Exception {
			final ByteBuf buf = pack.content();
			final int size = buf.readableBytes();
			if(size > 0){
				int connId = 0;
				if(buf.readByte()==Kcp.FLAG && size > 1 + 4){ //valid kcp head
					connId = buf.getInt(buf.readerIndex());
				}
				if(connId > 0){ //valid kcp pack
					pack.retain();
					queueRecv.offer(pack);
//					log.I("Recv kcp pack, sender="+pack.sender().toString());
				}else{  //normal udp pack
					log.I("Recv udp pack, sender="+pack.sender().toString());
				}
			}else{
				log.E("Invalid pack, len=0, sender="+pack.sender().toString());
			}
		}
 
Example 6
Source File: KcpTestServer.java    From dfactor with MIT License 6 votes vote down vote up
@Override
		protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket pack) throws Exception {
			final ByteBuf buf = pack.content();
			final int size = buf.readableBytes();
			if(size > 0){
				int connId = 0;
				if(buf.readByte()==Kcp.FLAG && size > 1 + 4){ //valid kcp head
					connId = buf.getInt(buf.readerIndex());
				}
				if(connId > 0){ //valid kcp pack
					pack.retain();
					kcpSys.onReceive(pack, connId);
//					log.I("Recv kcp pack, sender="+pack.sender().toString());
				}else{  //normal udp pack
					log.I("Recv udp pack, sender="+pack.sender().toString());
				}
			}else{
				log.E("Invalid pack, len=0, sender="+pack.sender().toString());
			}
		}
 
Example 7
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static Interval binaryDecodeINTERVAL(int index, int len, ByteBuf buff) {
  Duration duration = Duration.of(buff.getLong(index), ChronoUnit.MICROS);
  final long hours = duration.toHours();
  duration = duration.minusHours(hours);
  final long minutes = duration.toMinutes();
  duration = duration.minusMinutes(minutes);
  final long seconds = NANOSECONDS.toSeconds(duration.toNanos());
  duration = duration.minusSeconds(seconds);
  final long microseconds = NANOSECONDS.toMicros(duration.toNanos());
  int days = buff.getInt(index + 8);
  int months = buff.getInt(index + 12);
  Period monthYear = Period.of(0, months, days).normalized();
  return new Interval(monthYear.getYears(), monthYear.getMonths(), monthYear.getDays(),
    (int) hours, (int) minutes, (int) seconds, (int) microseconds);
}
 
Example 8
Source File: KcpPingPongExampleClient.java    From java-Kcp with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReceive(ByteBuf byteBuf, Ukcp ukcp,int protocolType) {
    ukcp.writeOrderedReliableMessage(byteBuf);
    int id = byteBuf.getInt(0);
    //if(j-id%10!=0){
    //    System.out.println("id"+id +"  j" +j);
    //}

    j++;
    if(j%100000==0){
        System.out.println(Snmp.snmp.toString());
        System.out.println("收到了 返回回去"+j);
    }
}
 
Example 9
Source File: ThriftMessageDecoder.java    From nettythrift with Apache License 2.0 5 votes vote down vote up
protected ByteBuf tryDecodeFramedMessage(ChannelHandlerContext ctx, Channel channel, ByteBuf buffer) {
	// Framed messages are prefixed by the size of the frame (which doesn't
	// include the
	// framing itself).

	int messageStartReaderIndex = buffer.readerIndex();
	int messageContentsOffset;

	// if (stripFraming) {
	messageContentsOffset = messageStartReaderIndex + MESSAGE_FRAME_SIZE;
	// } else {
	// messageContentsOffset = messageStartReaderIndex;
	// }

	// The full message is larger by the size of the frame size prefix
	int messageLength = buffer.getInt(messageStartReaderIndex) + MESSAGE_FRAME_SIZE;
	int messageContentsLength = messageStartReaderIndex + messageLength - messageContentsOffset;
	logger.debug("messageLength={}, rIndex={}, offset={}, readableBytes={}", messageLength, messageStartReaderIndex,
			messageContentsOffset, buffer.readableBytes());
	if (messageContentsLength > maxFrameSize) {
		throw new TooLongFrameException(
				String.format("Frame size exceeded on encode: frame was %d bytes, maximum allowed is %d bytes",
						messageLength, maxFrameSize));
	}

	if (messageLength == 0) {
		// Zero-sized frame: just ignore it and return nothing
		buffer.readerIndex(messageContentsOffset);
		return null;
	} else if (buffer.readableBytes() < messageLength) {
		// Full message isn't available yet, return nothing for now
		return null;
	} else {
		// Full message is available, return it
		ByteBuf messageBuffer = extractFrame(buffer, messageContentsOffset, messageContentsLength);
		buffer.readerIndex(messageStartReaderIndex + messageLength);
		return messageBuffer;
	}
}
 
Example 10
Source File: MysqlHeaderFactory.java    From Mycat-Balance with Apache License 2.0 5 votes vote down vote up
public void decode(ByteBuf byteBuf)
{
	byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);

	ByteBuf lengthBuf = Unpooled.buffer(4);
	lengthBuf = lengthBuf.order(ByteOrder.LITTLE_ENDIAN);

	byteBuf.getBytes(byteBuf.readerIndex(), lengthBuf, 3);
	bodyLength = lengthBuf.getInt(0);
	serialNum = byteBuf.getByte(byteBuf.readerIndex() + 3);
	byteBuf.writerIndex(byteBuf.capacity());
	byteBuf.readerIndex(byteBuf.readerIndex() + 3);
}
 
Example 11
Source File: OutboundEnvelopeEncoder.java    From stratosphere with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Envelope env, ByteBuf out) throws Exception {
	// --------------------------------------------------------------------
	// (1) header (48 bytes)
	// --------------------------------------------------------------------
	out.writeInt(MAGIC_NUMBER); // 4 bytes

	if (out.getInt(out.writerIndex()-4) != MAGIC_NUMBER) {
		throw new RuntimeException();
	}

	out.writeInt(env.getSequenceNumber()); // 4 bytes
	env.getJobID().writeTo(out); // 16 bytes
	env.getSource().writeTo(out); // 16 bytes
	out.writeInt(env.getEventsSerialized() != null ? env.getEventsSerialized().remaining() : 0); // 4 bytes
	out.writeInt(env.getBuffer() != null ? env.getBuffer().size() : 0); // 4 bytes
	// --------------------------------------------------------------------
	// (2) events (var length)
	// --------------------------------------------------------------------
	if (env.getEventsSerialized() != null) {
		out.writeBytes(env.getEventsSerialized());
	}

	// --------------------------------------------------------------------
	// (3) buffer (var length)
	// --------------------------------------------------------------------
	if (env.getBuffer() != null) {
		Buffer buffer = env.getBuffer();
		out.writeBytes(buffer.getMemorySegment().wrap(0, buffer.size()));

		// Recycle the buffer from OUR buffer pool after everything has been
		// copied to Nettys buffer space.
		buffer.recycleBuffer();
	}
}
 
Example 12
Source File: Spliter.java    From netty-learning-example with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    if (in.getInt(in.readerIndex()) != PacketCodec.MAGIC_NUMBER) {
        ctx.channel().close();
        return null;
    }

    return super.decode(ctx, in);
}
 
Example 13
Source File: PduCodec.java    From herddb with Apache License 2.0 5 votes vote down vote up
public static int readFetchSize(Pdu pdu) {
    ByteBuf buffer = pdu.buffer;
    return buffer.getInt(VERSION_SIZE
            + FLAGS_SIZE
            + TYPE_SIZE
            + MSGID_SIZE
            + ONE_LONG);
}
 
Example 14
Source File: RSocketCompositeMetadataTest.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceIdRoutingMetadata() {
    Integer remoteServiceId = 114;
    BinaryRoutingMetadata serviceIdRoutingMetadata = new BinaryRoutingMetadata(remoteServiceId, 112);
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(serviceIdRoutingMetadata);
    ByteBuf compositeByteBuf = compositeMetadata.getContent();
    compositeByteBuf.resetReaderIndex();
    byte metadataTypeId = compositeByteBuf.getByte(0);
    System.out.println(metadataTypeId);
    Assertions.assertEquals(metadataTypeId, (byte) (WellKnownMimeType.MESSAGE_RSOCKET_BINARY_ROUTING.getIdentifier() | 0x80));
    int length = compositeByteBuf.getInt(0) & 0xFF;
    Assertions.assertEquals(length, 8);
    int serviceId = compositeByteBuf.getInt(4);
    Assertions.assertEquals(serviceId, remoteServiceId);
}
 
Example 15
Source File: MessageDecoder.java    From ethereumj with MIT License 5 votes vote down vote up
private boolean isValidEthereumPacket(ByteBuf in) {
	// Ethereum message is at least 8 bytes
	if (in.readableBytes() < 8)
		return false;

	long syncToken = in.readUnsignedInt();

       if (!((syncToken >> 24   &  0xFF) == 0x22  &&
             (syncToken >> 16   &  0xFF) == 0x40  &&
             (syncToken >>  8   &  0xFF) == 0x08  &&
             (syncToken         &  0xFF) == 0x91 )) {

		// TODO: Drop frame and continue.
		// A collision can happen (although rare)
		// If this happens too often, it's an attack.
		// In that case, drop the peer.
		loggerWire.error("Abandon garbage, wrong sync token: [{}]", syncToken);
	}

	// Don't have the full message yet
       long msgSize = in.getInt(in.readerIndex());
	if (msgSize > in.readableBytes()) {
		loggerWire.trace("msg decode: magicBytes: [{}], readBytes: [{}] / msgSize: [{}] ",
                   syncToken, in.readableBytes(), msgSize);
		in.resetReaderIndex();
		return false;
	}

	loggerWire.trace("Message fully constructed: readBytes: [{}] / msgSize: [{}]", in.readableBytes(), msgSize);
	return true;
}
 
Example 16
Source File: HandshakePacket.java    From Mycat-Balance with Apache License 2.0 4 votes vote down vote up
@Override
	public HandshakePacket decodeBody(ByteBuf byteBuf, MysqlHeader mysqlHeader) throws DecodeException
	{
		this.setMysqlHeader(mysqlHeader);
		int _index = byteBuf.readerIndex();
		int index = _index;

		protocolVersion = byteBuf.getByte(index++);

		int len = 0;
		while (byteBuf.getByte(index+len) != 0)
		{
			len++;
		}
		versionInfo = new byte[len];
		byteBuf.getBytes(index, versionInfo, 0, len);
		index += len;
		index++;

		threadId = byteBuf.getInt(index);
		index+=4;

		encrypt1 = new byte[8];
		byteBuf.getBytes(index, encrypt1, 0, 8);
		index += 8;

		fix1 = byteBuf.getByte(index++);

		serverProp1 = new byte[2];
		byteBuf.getBytes(index, serverProp1, 0, 2);
		index += 2;

		charset = byteBuf.getByte(index++);

		serverStatus = new byte[2];
		byteBuf.getBytes(index, serverStatus, 0, 2);
		index += 2;

		serverProp2 = new byte[2];
		byteBuf.getBytes(index, serverProp2, 0, 2);
		index += 2;

		fix2 = byteBuf.getByte(index++);

//		byte10 = new byte[10];
//		byteBuf.getBytes(index, byte10, 0, 10);
		index += 10;

		len = 0;
		while (byteBuf.getByte(index + len) != 0)
		{
			len++;
		}
		encrypt2 = new byte[len];
		byteBuf.getBytes(index, encrypt2, 0, len);
		index += len;
		index++;
		
		
		len = 0;
		while (byteBuf.getByte(index + len) != 0)
		{
			len++;
		}
		authPluginName = new byte[len];
		byteBuf.getBytes(index, authPluginName, 0, len);
		index += len;
		index++;
		
		byteBuf.readerIndex(index);
		return this;
	}
 
Example 17
Source File: HttpClientPipelineConfigurator.java    From armeria with Apache License 2.0 4 votes vote down vote up
private boolean isSettingsFrame(ByteBuf in) {
    final int start = in.readerIndex();
    return in.getByte(start + 3) == 4 &&             // type == SETTINGS
           (in.getInt(start + 5) & 0x7FFFFFFF) == 0; // streamId == 0
}
 
Example 18
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private static Integer binaryDecodeINT4(int index, int len, ByteBuf buff) {
  return buff.getInt(index);
}
 
Example 19
Source File: CursorParamTest.java    From lmdbjava with Apache License 2.0 4 votes vote down vote up
@Override
public int get(final ByteBuf buff) {
  return buff.getInt(0);
}
 
Example 20
Source File: Snappy.java    From netty-4.1.22 with Apache License 2.0 2 votes vote down vote up
/**
 * Hashes the 4 bytes located at index, shifting the resulting hash into
 * the appropriate range for our hash table.
 *
 * @param in The input buffer to read 4 bytes from
 * @param index The index to read at
 * @param shift The shift value, for ensuring that the resulting value is
 *     withing the range of our hash table size
 * @return A 32-bit hash of 4 bytes located at index
 * 将位于索引处的4个字节散列,将结果散列转换为我们的哈希表的适当范围。
 */
private static int hash(ByteBuf in, int index, int shift) {
    return in.getInt(index) * 0x1e35a7bd >>> shift;
}