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

The following examples show how to use io.netty.buffer.ByteBuf#readUnsignedInt() . 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: DiscoveryServiceTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
        ByteBuf buffer = (ByteBuf) msg;
        buffer.readUnsignedInt(); // discard frame length
        int cmdSize = (int) buffer.readUnsignedInt();
        buffer.writerIndex(buffer.readerIndex() + cmdSize);
        ByteBufCodedInputStream cmdInputStream = ByteBufCodedInputStream.get(buffer);
        BaseCommand.Builder cmdBuilder = BaseCommand.newBuilder();
        BaseCommand cmd = cmdBuilder.mergeFrom(cmdInputStream, null).build();

        cmdInputStream.recycle();
        cmdBuilder.recycle();
        buffer.release();

        promise.complete(cmd);
    } catch (Exception e) {
        promise.completeExceptionally(e);
    }
    ctx.close();
}
 
Example 2
Source File: MuKeyFactory.java    From vethrfolnir-mu with GNU General Public License v3.0 5 votes vote down vote up
private static void readFile(String path, long[] out_dat) {

		AssetManager assetManager = Corax.fetch(AssetManager.class);

		ByteBuf buff = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);

		
		try (InputStream is = assetManager.loadAsset(FileKey.class, path)) {
			buff.writeBytes(is, is.available());
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		buff.readerIndex(6);
		int pointer = 0;
		for (int i = 0; i < 3; i++) {
			long[] buf = new long[4];

			for (int j = 0; j < 4; j++) {
				buf[j] = buff.readUnsignedInt();
			}

			out_dat[pointer++] = buf[0] ^ (xor_tab_datfile[0]);
			out_dat[pointer++] = buf[1] ^ (xor_tab_datfile[1] & 0xFFFFFFFFL);
			out_dat[pointer++] = buf[2] ^ (xor_tab_datfile[2] & 0xFFFFFFFFL);
			out_dat[pointer++] = buf[3] ^ (xor_tab_datfile[3]);
		}
	}
 
Example 3
Source File: AbstractSrSubobjectParser.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
protected static SrSubobject parseSrSubobject(final ByteBuf buffer) throws PCEPDeserializerException {
    final int sidTypeByte = buffer.readByte() >> SID_TYPE_BITS_OFFSET;
    final SidType sidType = SidType.forValue(sidTypeByte);
    final BitArray bitSet = BitArray.valueOf(buffer.readByte());
    final boolean f = bitSet.get(F_FLAG_POSITION);
    final boolean s = bitSet.get(S_FLAG_POSITION);
    final boolean c = bitSet.get(C_FLAG_POSITION);
    final boolean m = bitSet.get(M_FLAG_POSITION);

    if (f && s) {
        throw new PCEPDeserializerException("Both SID and NAI are absent in SR subobject.");
    }

    final Uint32 sid;
    if (!s) {
        final long tmp = buffer.readUnsignedInt();
        sid = Uint32.valueOf(m ? tmp >> MPLS_LABEL_OFFSET : tmp);
    } else {
        sid = null;
    }
    final Nai nai;
    if (sidType != null && !f) {
        nai = parseNai(sidType, buffer);
    } else {
        nai = null;
    }
    return new SrSubobjectImpl(m, c, sidType, sid, nai);
}
 
Example 4
Source File: BeatsFrameDecoderTest.java    From graylog-plugin-beats with GNU General Public License v3.0 5 votes vote down vote up
private long extractSequenceNumber(ByteBuf buffer) {
    assertThat(buffer.readByte()).isEqualTo((byte) '2');
    assertThat(buffer.readByte()).isEqualTo((byte) 'A');
    final long seqNum = buffer.readUnsignedInt();
    assertThat(buffer.readableBytes()).isEqualTo(0);
    return seqNum;
}
 
Example 5
Source File: WSMessageDecoder.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    log.debug("In webappdecoder. {}", msg);
    if (msg instanceof BinaryWebSocketFrame) {
        try {
            ByteBuf in = ((BinaryWebSocketFrame) msg).content();

            short command = in.readUnsignedByte();
            int messageId = in.readUnsignedShort();

            if (limitChecker.quotaReached(ctx, messageId)) {
                return;
            }

            MessageBase message;
            if (command == Command.RESPONSE) {
                message = new ResponseMessage(messageId, (int) in.readUnsignedInt());
            } else {
                int codeOrLength = in.capacity() - 3;
                message = produce(messageId, command, (String) in.readCharSequence(codeOrLength, UTF_8));
            }

            log.trace("Incoming websocket msg {}", message);
            stats.markWithoutGlobal(Command.WEB_SOCKETS);
            ctx.fireChannelRead(message);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    } else {
        super.channelRead(ctx, msg);
    }
}
 
Example 6
Source File: AcknowledgeMessage.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
public static AcknowledgeMessage decode(ByteBuf buffer) {
    return new AcknowledgeMessage(
            buffer.readUnsignedInt(), /*    ProtocolVersion     */
            buffer.readUnsignedInt(), /*    ReceiveBufferSize   */
            buffer.readUnsignedInt(), /*    SendBufferSize      */
            buffer.readUnsignedInt(), /*    MaxMessageSize      */
            buffer.readUnsignedInt()  /*    MaxChunkCount       */
    );
}
 
Example 7
Source File: ScopeCreated.java    From java-dcp-client with Apache License 2.0 5 votes vote down vote up
public ScopeCreated(int vbucket, long seqno, int version, ByteBuf buffer) {
  super(Type.SCOPE_CREATED, vbucket, seqno, version);

  scopeName = MessageUtil.getKeyAsString(buffer);
  ByteBuf value = MessageUtil.getContent(buffer);

  newManifestId = value.readLong();
  scopeId = value.readUnsignedInt();
}
 
Example 8
Source File: TimeClientHandler.java    From netty-learning with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf byteBuf = (ByteBuf) msg ;
    try {
        long currentTimeMillis = (byteBuf.readUnsignedInt() - 2208988800L) * 1000L;
        System.out.println("=========="+new Date(currentTimeMillis));
        ctx.close();

    }finally {
        byteBuf.release() ;
    }

}
 
Example 9
Source File: ReadDataFiles.java    From vethrfolnir-mu with GNU General Public License v3.0 5 votes vote down vote up
public static long[] readFile(URL url) {
	
	ByteBuf buff = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);

	try (DataInputStream is = new DataInputStream(url.openStream())) {
		buff.writeBytes(is, is.available());
	}
	catch (Exception e) {
		throw new RuntimeException(e);
	}
	
	int bits2 = buff.readUnsignedShort();
	
	System.out.println("First two bits: "+bits2 + " hex: 0x"+PrintData.fillHex(bits2, 2));

	long[] out_dat = new long[12];

	buff.readerIndex(6);
	int pointer = 0;
	for (int i = 0; i < 3; i++) {
		long[] buf = new long[4];
		
		for (int j = 0; j < 4; j++) {
			buf[j] = buff.readUnsignedInt();
		}
		
		out_dat[pointer++] = buf[0] ^ (xor_tab_datfile[0]);
		out_dat[pointer++] = buf[1] ^ (xor_tab_datfile[1] & 0xFFFFFFFFL);
		out_dat[pointer++] = buf[2] ^ (xor_tab_datfile[2] & 0xFFFFFFFFL);
		out_dat[pointer++] = buf[3] ^ (xor_tab_datfile[3]);
	}
	
	for (int i = 0; i < out_dat.length; i++) {
		System.out.print(" "+(out_dat[i]));
	}
	
	System.out.println();
	return null;
}
 
Example 10
Source File: ZlibRectDecoder.java    From jfxvnc with Apache License 2.0 5 votes vote down vote up
@Override
public boolean decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
  if (!initialized) {
    if (!in.isReadable(4)) {
      return false;
    }
    capacity = (int) in.readUnsignedInt();
    initialized = true;
  }
  return super.decode(ctx, in, out);
}
 
Example 11
Source File: DefaultHttp2FrameReader.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void readGoAwayFrame(ChannelHandlerContext ctx, ByteBuf payload,
        Http2FrameListener listener) throws Http2Exception {
    int lastStreamId = readUnsignedInt(payload);
    long errorCode = payload.readUnsignedInt();
    ByteBuf debugData = payload.readSlice(payload.readableBytes());
    listener.onGoAwayRead(ctx, lastStreamId, errorCode, debugData);
}
 
Example 12
Source File: CollectionCreated.java    From java-dcp-client with Apache License 2.0 5 votes vote down vote up
public CollectionCreated(int vbucket, long seqno, int version, ByteBuf buffer) {
  super(Type.COLLECTION_CREATED, vbucket, seqno, version);

  collectionName = MessageUtil.getKeyAsString(buffer);
  ByteBuf value = MessageUtil.getContent(buffer);

  newManifestId = value.readLong();
  scopeId = value.readUnsignedInt();
  collectionId = value.readUnsignedInt();

  // absent in version 0
  maxTtl = value.isReadable() ? OptionalLong.of(value.readUnsignedInt()) : OptionalLong.empty();
}
 
Example 13
Source File: DefaultDnsRecordDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public final <T extends DnsRecord> T decodeRecord(ByteBuf in) throws Exception {
    final int startOffset = in.readerIndex();
    final String name = decodeName(in);

    final int endOffset = in.writerIndex();
    if (endOffset - startOffset < 10) {
        // Not enough data
        in.readerIndex(startOffset);
        return null;
    }

    final DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort());
    final int aClass = in.readUnsignedShort();
    final long ttl = in.readUnsignedInt();
    final int length = in.readUnsignedShort();
    final int offset = in.readerIndex();

    if (endOffset - offset < length) {
        // Not enough data
        in.readerIndex(startOffset);
        return null;
    }

    @SuppressWarnings("unchecked")
    T record = (T) decodeRecord(name, type, aClass, ttl, in, offset, length);
    in.readerIndex(offset + length);
    return record;
}
 
Example 14
Source File: Commands.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static void skipMessageMetadata(ByteBuf buffer) {
    // initially reader-index may point to start_of_checksum : increment reader-index to start_of_metadata to parse
    // metadata
    skipChecksumIfPresent(buffer);
    int metadataSize = (int) buffer.readUnsignedInt();
    buffer.skipBytes(metadataSize);
}
 
Example 15
Source File: HelloMessage.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
public static HelloMessage decode(ByteBuf buffer) {
    return new HelloMessage(
            buffer.readUnsignedInt(), /*    ProtocolVersion    */
            buffer.readUnsignedInt(), /*    ReceiveBufferSize  */
            buffer.readUnsignedInt(), /*    SendBufferSize     */
            buffer.readUnsignedInt(), /*    MaxMessageSize     */
            buffer.readUnsignedInt(), /*    MaxChunkCount      */
            decodeString(buffer)      /*    EndpointUrl        */
    );
}
 
Example 16
Source File: FrameDecoder.java    From incubator-nemo with Apache License 2.0 4 votes vote down vote up
/**
 * Try to decode a frame header.
 *
 * @param ctx the channel handler context
 * @param in  the {@link ByteBuf} from which to read data
 * @return {@code true} if a header was decoded, {@code false} otherwise
 */
private boolean onFrameStarted(final ChannelHandlerContext ctx, final ByteBuf in) {
  assert (controlBodyBytesToRead == 0);
  assert (dataBodyBytesToRead == 0);
  assert (inputContext == null);

  if (in.readableBytes() < HEADER_LENGTH) {
    // cannot read a frame header frame now
    return false;
  }
  final byte flags = in.readByte();
  final int transferIndex = in.readInt();
  final long length = in.readUnsignedInt();
  if (length < 0) {
    throw new IllegalStateException(String.format("Frame length is negative: %d", length));
  }
  if ((flags & ((byte) (1 << 3))) == 0) {
    // setup context for reading control frame body
    controlBodyBytesToRead = length;
  } else {
    // setup context for reading data frame body
    dataBodyBytesToRead = length;
    final ByteTransferDataDirection dataDirection = (flags & ((byte) (1 << 2))) == 0
      ? ByteTransferDataDirection.INITIATOR_SENDS_DATA : ByteTransferDataDirection.INITIATOR_RECEIVES_DATA;
    final boolean newSubStreamFlag = (flags & ((byte) (1 << 1))) != 0;
    isLastFrame = (flags & ((byte) (1 << 0))) != 0;
    inputContext = contextManager.getInputContext(dataDirection, transferIndex);
    if (inputContext == null) {
      throw new IllegalStateException(String.format("Transport context for %s:%d was not found between the local"
          + "address %s and the remote address %s", dataDirection, transferIndex,
        ctx.channel().localAddress(), ctx.channel().remoteAddress()));
    }
    if (newSubStreamFlag) {
      inputContext.onNewStream();
    }
    if (dataBodyBytesToRead == 0) {
      onDataFrameEnd();
    }
  }
  return true;
}
 
Example 17
Source File: TimeClientHandler.java    From learning-code with Apache License 2.0 4 votes vote down vote up
@Override
protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
    long currentTimeMillis = (byteBuf.readUnsignedInt() - 123456789L) * 1000L;
    System.out.println(new Date(currentTimeMillis));
    channelHandlerContext.close();
}
 
Example 18
Source File: NetFlowV5Parser.java    From graylog-plugin-netflow with Apache License 2.0 4 votes vote down vote up
/**
 * <pre>
 * | BYTES | CONTENTS  |                            DESCRIPTION                             |
 * |-------|-----------|--------------------------------------------------------------------|
 * | 0-3   | srcaddr   | Source IP address                                                  |
 * | 4-7   | dstaddr   | Destination IP address                                             |
 * | 8-11  | nexthop   | IP address of next hop router                                      |
 * | 12-13 | input     | SNMP index of input interface                                      |
 * | 14-15 | output    | SNMP index of output interface                                     |
 * | 16-19 | dPkts     | Packets in the flow                                                |
 * | 20-23 | dOctets   | Total number of Layer 3 bytes in the packets of the flow           |
 * | 24-27 | first     | SysUptime at start of flow                                         |
 * | 28-31 | last      | SysUptime at the time the last packet of the flow was received     |
 * | 32-33 | srcport   | TCP/UDP source port number or equivalent                           |
 * | 34-35 | dstport   | TCP/UDP destination port number or equivalent                      |
 * | 36    | pad1      | Unused (zero) bytes                                                |
 * | 37    | tcp_flags | Cumulative OR of TCP flags                                         |
 * | 38    | prot      | IP protocol type (for example, TCP = 6; UDP = 17)                  |
 * | 39    | tos       | IP type of service (ToS)                                           |
 * | 40-41 | src_as    | Autonomous system number of the source, either origin or peer      |
 * | 42-43 | dst_as    | Autonomous system number of the destination, either origin or peer |
 * | 44    | src_mask  | Source address prefix mask bits                                    |
 * | 45    | dst_mask  | Destination address prefix mask bits                               |
 * | 46-47 | pad2      | Unused (zero) bytes                                                |
 * </pre>
 */
private static NetFlowV5Record parseRecord(ByteBuf bb) {
    final InetAddress srcAddr = ByteBufUtils.readInetAddress(bb);
    final InetAddress dstAddr = ByteBufUtils.readInetAddress(bb);
    final InetAddress nextHop = ByteBufUtils.readInetAddress(bb);
    final int inputIface = bb.readUnsignedShort();
    final int outputIface = bb.readUnsignedShort();
    final long packetCount = bb.readUnsignedInt();
    final long octetCount = bb.readUnsignedInt();
    final long first = bb.readUnsignedInt();
    final long last = bb.readUnsignedInt();
    final int srcPort = bb.readUnsignedShort();
    final int dstPort = bb.readUnsignedShort();
    bb.readByte(); // unused pad1
    final short tcpFlags = bb.readUnsignedByte();
    final short protocol = bb.readUnsignedByte();
    final short tos = bb.readUnsignedByte();
    final int srcAs = bb.readUnsignedShort();
    final int dstAs = bb.readUnsignedShort();
    final short srcMask = bb.readUnsignedByte();
    final short dstMask = bb.readUnsignedByte();

    return NetFlowV5Record.create(srcAddr, dstAddr, nextHop, inputIface, outputIface, packetCount, octetCount, first, last, srcPort, dstPort, tcpFlags, protocol, tos, srcAs, dstAs, srcMask, dstMask);
}
 
Example 19
Source File: AppClientMessageDecoder.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if (in.readableBytes() < MobileMessageDecoder.PROTOCOL_APP_HEADER_SIZE) {
        return;
    }

    in.markReaderIndex();

    short command = in.readUnsignedByte();
    int messageId = in.readUnsignedShort();

    MessageBase message;
    if (command == Command.RESPONSE) {
        int responseCode = (int) in.readUnsignedInt();
        message = new ResponseMessage(messageId, responseCode);
    } else {
        int length = (int) in.readUnsignedInt();

        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }

        ByteBuf buf = in.readSlice(length);
        switch (command) {
            case GET_ENHANCED_GRAPH_DATA :
            case GET_PROJECT_BY_CLONE_CODE :
            case LOAD_PROFILE_GZIPPED :
            case GET_PROJECT_BY_TOKEN :
                byte[] bytes = new byte[buf.readableBytes()];
                buf.readBytes(bytes);
                message = new BinaryMessage(messageId, command, bytes);
                break;
            default:
                message = produce(messageId, command, buf.toString(StandardCharsets.UTF_8));
        }

    }

    log.trace("Incoming client {}", message);

    out.add(message);
}
 
Example 20
Source File: ErrorMessage.java    From opc-ua-stack with Apache License 2.0 4 votes vote down vote up
public static ErrorMessage decode(ByteBuf buffer) {
    return new ErrorMessage(
            buffer.readUnsignedInt(),
            decodeString(buffer));
}