Example usage for io.netty.buffer ByteBuf readUnsignedShort

List of usage examples for io.netty.buffer ByteBuf readUnsignedShort

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readUnsignedShort.

Prototype

public abstract int readUnsignedShort();

Source Link

Document

Gets an unsigned 16-bit short integer at the current readerIndex and increases the readerIndex by 2 in this buffer.

Usage

From source file:org.lanternpowered.server.network.query.QueryHandler.java

License:MIT License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    final ByteBuf buf = msg.content();
    if (buf.readableBytes() < 7) {
        return;/*from  w w w .  ja  v a 2 s.  co  m*/
    }

    final int magic = buf.readUnsignedShort();
    final byte type = buf.readByte();
    final int sessionId = buf.readInt();

    if (magic != 0xFEFD) {
        return;
    }

    if (type == ACTION_HANDSHAKE) {
        handleHandshake(ctx, msg, sessionId);
    } else if (type == ACTION_STATS) {
        if (buf.readableBytes() < 4) {
            return;
        }
        final int token = buf.readInt();
        if (this.queryServer.verifyChallengeToken(msg.sender(), token)) {
            if (buf.readableBytes() == 4) {
                this.handleFullStats(ctx, msg, sessionId);
            } else {
                this.handleBasicStats(ctx, msg, sessionId);
            }
        }
    }
}

From source file:org.neo4j.bolt.v1.transport.BoltV1Dechunker.java

License:Open Source License

public void handle(ByteBuf data) throws IOException {
    while (data.readableBytes() > 0) {
        switch (state) {
        case AWAITING_CHUNK: {
            if (data.readableBytes() >= 2) {
                // Whole header available, read that
                chunkSize = data.readUnsignedShort();
                handleHeader();/*from   w w w .  j  a v a  2  s  .  c o  m*/
            } else {
                // Only one byte available, read that and wait for the second byte
                chunkSize = data.readUnsignedByte() << 8;
                state = State.IN_HEADER;
            }
            break;
        }
        case IN_HEADER: {
            // First header byte read, now we read the next one
            chunkSize = chunkSize | data.readUnsignedByte();
            handleHeader();
            break;
        }
        case IN_CHUNK: {
            if (chunkSize < data.readableBytes()) {
                // Current packet is larger than current chunk, slice of the chunk
                input.append(data.readSlice(chunkSize));
                state = State.AWAITING_CHUNK;
            } else if (chunkSize == data.readableBytes()) {
                // Current packet perfectly maps to current chunk
                input.append(data);
                state = State.AWAITING_CHUNK;
                return;
            } else {
                // Current packet is smaller than the chunk we're reading, split the current chunk itself up
                chunkSize -= data.readableBytes();
                input.append(data);
                return;
            }
            break;
        }
        case CLOSED: {
            // No-op
            return;
        }
        }
    }
}

From source file:org.neo4j.ndp.transport.socket.SocketProtocolV1.java

License:Open Source License

/**
 * Handle an incoming network packet. We currently deal with the chunked input by building up full messages in
 * RAM before we deserialize them. This is fine with most messages, but will become a problem with very large
 * parameters and so on. The next step will be to write a new protocol V1 deserializer that can do incremental
 * deserialization, see the Netty HTTP parser for an example.
 *//*from   w  w  w. ja  va  2 s . c om*/
@Override
public void handle(ChannelHandlerContext channelContext, ByteBuf data) {
    onBatchOfMessagesStarted();
    while (data.readableBytes() > 0) {
        int chunkSize = data.readUnsignedShort();
        if (chunkSize > 0) {
            if (chunkSize <= data.readableBytes()) {
                // Incoming buffer contains the whole chunk, forward it to our chunked input handling
                input.addChunk(data.readSlice(chunkSize));
            } else {
                throw new UnsupportedOperationException("Chunks split across packets not yet supported"); // TODO
            }
        } else {
            processChunkedMessage(channelContext);
        }
    }
    onBatchOfMessagesDone();
}

From source file:org.onosproject.lisp.msg.types.lcaf.LispLcafAddress.java

License:Apache License

/**
 * Deserializes common fields from byte buffer.
 *
 * @param byteBuf byte buffer/* w  w w. j ava2 s  .  c om*/
 * @return LispLcafAddress with filled common data fields
 */
public static LispLcafAddress deserializeCommon(ByteBuf byteBuf) {

    // let's skip first and second two bytes,
    // because it represents LCAF AFI code
    byteBuf.skipBytes(LCAF_AFI_CODE_BYTE_LENGTH);

    // reserved1 -> 8 bits
    byte reserved1 = (byte) byteBuf.readUnsignedByte();

    // flags -> 8 bits
    byte flag = (byte) byteBuf.readUnsignedByte();

    // LCAF type -> 8 bits
    byte lcafType = (byte) byteBuf.readUnsignedByte();

    // reserved2 -> 8bits
    byte reserved2 = (byte) byteBuf.readUnsignedByte();

    // length -> 16 bits
    short length = (short) byteBuf.readUnsignedShort();

    return new LispLcafAddress(LispCanonicalAddressFormatEnum.valueOf(lcafType), reserved1, reserved2, flag,
            length);
}

From source file:org.onosproject.lisp.msg.types.LispLcafAddress.java

License:Apache License

/**
 * Deserializes common fields from byte buffer.
 *
 * @param byteBuf byte buffer/*  w  w w  .j  a va  2 s . c  om*/
 * @return LispLcafAddress with filled common data fields
 */
public static LispLcafAddress deserializeCommon(ByteBuf byteBuf) {

    // reserved1 -> 8 bits
    byte reserved1 = (byte) byteBuf.readUnsignedByte();

    // flags -> 8 bits
    byte flag = (byte) byteBuf.readUnsignedByte();

    // LCAF type -> 8 bits
    byte lcafType = (byte) byteBuf.readUnsignedByte();

    // reserved2 -> 8bits
    byte reserved2 = (byte) byteBuf.readUnsignedByte();

    // length -> 16 bits
    short length = (short) byteBuf.readUnsignedShort();

    return new LispLcafAddress(LispCanonicalAddressFormatEnum.valueOf(lcafType), reserved1, reserved2, flag,
            length);
}

From source file:org.opendaylight.bgp.concepts.RouteDistinguisherUtil.java

License:Open Source License

/**
 * Parses three types of route distinguisher from given ByteBuf.
 *
 * @param buffer//from   w  w w.j  av a  2 s .c om
 * @return RouteDistinguisher
 */
public static RouteDistinguisher parseRouteDistinguisher(final ByteBuf buffer) {
    Preconditions.checkState(buffer != null && buffer.isReadable(RD_LENGTH),
            "Cannot read Route Distinguisher from provided buffer.");
    final int type = buffer.readUnsignedShort();
    final RD_TYPE rdType = RD_TYPE.valueOf(type);
    final StringBuilder routeDistiguisher = new StringBuilder();
    switch (rdType) {
    case AS_2BYTE:
        routeDistiguisher.append(type);
        routeDistiguisher.append(SEPARATOR);
        routeDistiguisher.append(buffer.readUnsignedShort());
        routeDistiguisher.append(SEPARATOR);
        routeDistiguisher.append(buffer.readUnsignedInt());
        return new RouteDistinguisher(new RdTwoOctetAs(routeDistiguisher.toString()));
    case IPV4:
        routeDistiguisher.append(Ipv4Util.addressForByteBuf(buffer).getValue());
        routeDistiguisher.append(SEPARATOR);
        routeDistiguisher.append(buffer.readUnsignedShort());
        return new RouteDistinguisher(new RdIpv4(routeDistiguisher.toString()));
    case AS_4BYTE:
        routeDistiguisher.append(buffer.readUnsignedInt());
        routeDistiguisher.append(SEPARATOR);
        routeDistiguisher.append(buffer.readUnsignedShort());
        return new RouteDistinguisher(new RdAs(routeDistiguisher.toString()));
    default:
        // now that this RD type is not supported, we want to read the remain 6 bytes
        // in order to get the byte index correct
        for (int i = 0; i < 6; i++) {
            routeDistiguisher.append("0x").append(Integer.toHexString(buffer.readByte() & 0xFF)).append(" ");
        }
        LOG.debug("Invalid Route Distinguisher: type={}, rawRouteDistinguisherValue={}", type,
                routeDistiguisher.toString());
        throw new IllegalArgumentException("Invalid Route Distinguisher type " + type);
    }
}

From source file:org.opendaylight.capwap.ODLCapwapControlMessage.java

License:Open Source License

int decode(ByteBuf buf) {
    //ByteBuf bbuf = Unpooled.wrappedBuffer(buf);
    //ByteBuf tmpbuf = bbuf.readerIndex(pos);

    this.msgType = buf.readUnsignedInt();
    this.seqNo = buf.readUnsignedByte();
    this.msgLen = buf.readUnsignedShort();
    this.flags = buf.readUnsignedByte();

    return 0;/* w  ww  . j  a v  a  2s  . c o  m*/
}

From source file:org.opendaylight.ext.impl.FooActionDeserializer.java

License:Open Source License

@Override
public Action deserialize(ByteBuf input) {

    input.skipBytes(EncodeConstants.SIZE_OF_SHORT_IN_BYTES); // we know the type of action
    input.skipBytes(EncodeConstants.SIZE_OF_SHORT_IN_BYTES); // we don't need length

    ActionBuilder actionBuilder = new ActionBuilder();
    actionBuilder.setExperimenterId(new ExperimenterId(input.readUnsignedInt()));
    ActionFooBuilder actionFooBuilder = new ActionFooBuilder();
    ExtActionFooBuilder extActionFooBuilder = new ExtActionFooBuilder();
    extActionFooBuilder.setFirst(input.readUnsignedShort());
    extActionFooBuilder.setSecond(input.readUnsignedShort());
    input.skipBytes(4); // padding
    actionFooBuilder.setExtActionFoo(extActionFooBuilder.build());
    actionBuilder.setActionChoice(actionFooBuilder.build());
    return actionBuilder.build();
}

From source file:org.opendaylight.netide.openflowjava.protocol.impl.deserialization.factories.FlowModInputMessageFactory.java

License:Open Source License

@Override
public FlowModInput deserialize(ByteBuf rawMessage) {
    FlowModInputBuilder builder = new FlowModInputBuilder();
    builder.setVersion((short) EncodeConstants.OF13_VERSION_ID);
    builder.setXid(rawMessage.readUnsignedInt());
    byte[] cookie = new byte[EncodeConstants.SIZE_OF_LONG_IN_BYTES];
    rawMessage.readBytes(cookie);/*from   w  w w  .  j  a  va  2 s  . co  m*/
    builder.setCookie(new BigInteger(1, cookie));
    byte[] cookie_mask = new byte[EncodeConstants.SIZE_OF_LONG_IN_BYTES];
    rawMessage.readBytes(cookie_mask);
    builder.setCookieMask(new BigInteger(1, cookie_mask));
    builder.setTableId(new TableId((long) rawMessage.readUnsignedByte()));
    builder.setCommand(FlowModCommand.forValue(rawMessage.readUnsignedByte()));
    builder.setIdleTimeout(rawMessage.readUnsignedShort());
    builder.setHardTimeout(rawMessage.readUnsignedShort());
    builder.setPriority(rawMessage.readUnsignedShort());
    builder.setBufferId(rawMessage.readUnsignedInt());
    builder.setOutPort(new PortNumber(rawMessage.readUnsignedInt()));
    builder.setOutGroup(rawMessage.readUnsignedInt());
    builder.setFlags(createFlowModFlagsFromBitmap(rawMessage.readUnsignedShort()));
    rawMessage.skipBytes(PADDING);
    OFDeserializer<Match> matchDeserializer = registry.getDeserializer(
            new MessageCodeKey(EncodeConstants.OF13_VERSION_ID, EncodeConstants.EMPTY_VALUE, Match.class));
    builder.setMatch(matchDeserializer.deserialize(rawMessage));
    CodeKeyMaker keyMaker = CodeKeyMakerFactory.createInstructionsKeyMaker(EncodeConstants.OF13_VERSION_ID);
    List<Instruction> instructions = ListDeserializer.deserializeList(EncodeConstants.OF13_VERSION_ID,
            rawMessage.readableBytes(), rawMessage, keyMaker, registry);
    builder.setInstruction(instructions);
    return builder.build();
}

From source file:org.opendaylight.netide.openflowjava.protocol.impl.deserialization.factories.GroupModInputMessageFactory.java

License:Open Source License

@Override
public GroupModInput deserialize(ByteBuf rawMessage) {
    GroupModInputBuilder builder = new GroupModInputBuilder();
    builder.setVersion((short) EncodeConstants.OF13_VERSION_ID);
    builder.setXid(rawMessage.readUnsignedInt());
    builder.setCommand(GroupModCommand.forValue(rawMessage.readUnsignedShort()));
    builder.setType(GroupType.forValue(rawMessage.readUnsignedByte()));
    rawMessage.skipBytes(PADDING);//w w  w .ja  v  a2 s.  c om
    builder.setGroupId(new GroupId(rawMessage.readUnsignedInt()));
    List<BucketsList> bucketsList = new ArrayList<>();
    while (rawMessage.readableBytes() > 0) {
        BucketsListBuilder bucketsBuilder = new BucketsListBuilder();
        int bucketsLength = rawMessage.readUnsignedShort();
        bucketsBuilder.setWeight(rawMessage.readUnsignedShort());
        bucketsBuilder.setWatchPort(new PortNumber(rawMessage.readUnsignedInt()));
        bucketsBuilder.setWatchGroup(rawMessage.readUnsignedInt());
        rawMessage.skipBytes(PADDING_IN_BUCKETS_HEADER);
        CodeKeyMaker keyMaker = CodeKeyMakerFactory.createActionsKeyMaker(EncodeConstants.OF13_VERSION_ID);
        List<Action> actions = ListDeserializer.deserializeList(EncodeConstants.OF13_VERSION_ID,
                bucketsLength - BUCKETS_HEADER_LENGTH, rawMessage, keyMaker, registry);
        bucketsBuilder.setAction(actions);
        bucketsList.add(bucketsBuilder.build());
    }
    builder.setBucketsList(bucketsList);
    return builder.build();
}