Java Code Examples for org.jboss.netty.buffer.ChannelBuffer#readableBytes()

The following examples show how to use org.jboss.netty.buffer.ChannelBuffer#readableBytes() . 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: BgpPrefixAttrMetric.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the Prefix Metric.
 *
 * @param cb ChannelBuffer
 * @return object of BgpPrefixAttrMetric
 * @throws BgpParseException while parsing BgpPrefixAttrMetric
 */
public static BgpPrefixAttrMetric read(ChannelBuffer cb)
        throws BgpParseException {
    int linkPfxMetric;

    short lsAttrLength = cb.readShort(); // 4 Bytes

    if ((lsAttrLength != ATTR_PREFIX_LEN)
            || (cb.readableBytes() < lsAttrLength)) {
        Validation.validateLen(BgpErrorType.UPDATE_MESSAGE_ERROR,
                               BgpErrorType.ATTRIBUTE_LENGTH_ERROR,
                               lsAttrLength);
    }

    linkPfxMetric = cb.readInt();

    return BgpPrefixAttrMetric.of(linkPfxMetric);
}
 
Example 2
Source File: ThriftFrameDecoder.java    From ikasoa with MIT License 6 votes vote down vote up
protected ChannelBuffer tryDecodeFramedMessage(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer,
		boolean stripFraming) {

	int messageStartReaderIndex = buffer.readerIndex();
	int messageContentsOffset = stripFraming ? messageStartReaderIndex + MESSAGE_FRAME_SIZE
			: messageStartReaderIndex;
	int messageLength = buffer.getInt(messageStartReaderIndex) + MESSAGE_FRAME_SIZE;
	int messageContentsLength = messageStartReaderIndex + messageLength - messageContentsOffset;

	if (messageContentsLength > maxFrameSize)
		Channels.fireExceptionCaught(ctx,
				new TooLongFrameException(String.format("Maximum frame size of %d exceeded .", maxFrameSize)));

	if (messageLength == 0) {
		buffer.readerIndex(messageContentsOffset);
		return null;
	} else if (buffer.readableBytes() < messageLength)
		return null;
	else {
		ChannelBuffer messageBuffer = extractFrame(buffer, messageContentsOffset, messageContentsLength);
		buffer.readerIndex(messageStartReaderIndex + messageLength);
		return messageBuffer;
	}
}
 
Example 3
Source File: BgpPrefixAttrRouteTag.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the Route Tag.
 *
 * @param cb ChannelBuffer
 * @return object of BgpPrefixAttrRouteTag
 * @throws BgpParseException while parsing BgpPrefixAttrRouteTag
 */
public static BgpPrefixAttrRouteTag read(ChannelBuffer cb)
        throws BgpParseException {
    int tmp;
    ArrayList<Integer> pfxRouteTag = new ArrayList<Integer>();

    short lsAttrLength = cb.readShort();
    int len = lsAttrLength / SIZE;

    if (cb.readableBytes() < lsAttrLength) {
        Validation.validateLen(BgpErrorType.UPDATE_MESSAGE_ERROR,
                               BgpErrorType.ATTRIBUTE_LENGTH_ERROR,
                               lsAttrLength);
    }

    for (int i = 0; i < len; i++) {
        tmp = cb.readInt();
        pfxRouteTag.add(new Integer(tmp));
    }

    return BgpPrefixAttrRouteTag.of(pfxRouteTag);
}
 
Example 4
Source File: Origin.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Reads from ChannelBuffer and parses Origin.
 *
 * @param cb ChannelBuffer
 * @return object of Origin
 * @throws BgpParseException while parsing Origin path attribute
 */
public static Origin read(ChannelBuffer cb) throws BgpParseException {
    ChannelBuffer tempCb = cb.copy();
    Validation parseFlags = Validation.parseAttributeHeader(cb);

    int len = parseFlags.isShort() ? parseFlags.getLength() + Constants.TYPE_AND_LEN_AS_SHORT : parseFlags
            .getLength() + Constants.TYPE_AND_LEN_AS_BYTE;
    ChannelBuffer data = tempCb.readBytes(len);
    if ((parseFlags.getLength() > ORIGIN_VALUE_LEN) || (cb.readableBytes() < parseFlags.getLength())) {
        Validation.validateLen(BgpErrorType.UPDATE_MESSAGE_ERROR, BgpErrorType.ATTRIBUTE_LENGTH_ERROR,
                parseFlags.getLength());
    }
    if (parseFlags.getFirstBit() && !parseFlags.getSecondBit() && parseFlags.getThirdBit()) {
        throw new BgpParseException(BgpErrorType.UPDATE_MESSAGE_ERROR, BgpErrorType.ATTRIBUTE_FLAGS_ERROR, data);
    }

    byte originValue;
    originValue = cb.readByte();
    if ((originValue != OriginType.INCOMPLETE.value) && (originValue != OriginType.IGP.value) &&
          (originValue != OriginType.EGP.value)) {
        throw new BgpParseException(BgpErrorType.UPDATE_MESSAGE_ERROR, BgpErrorType.INVALID_ORIGIN_ATTRIBUTE, data);
    }
    return new Origin(originValue);
}
 
Example 5
Source File: LocalInterfaceIpAddress.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Reads bytes from channel buffer.
 *
 * @param channelBuffer channel buffer instance
 * @throws OspfParseException might throws exception while parsing buffer
 */
public void readFrom(ChannelBuffer channelBuffer) throws OspfParseException {
    while (channelBuffer.readableBytes() >= OspfUtil.FOUR_BYTES) {
        try {
            byte[] tempByteArray = new byte[OspfUtil.FOUR_BYTES];
            channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
            this.addLocalInterfaceIPAddress(InetAddress.getByAddress(tempByteArray).getHostName());
        } catch (UnknownHostException e) {
            log.debug("Error::readFrom:: {}", e.getMessage());
            throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR,
                                         OspfErrorType.BAD_MESSAGE);
        }
    }
}
 
Example 6
Source File: PcepErrorVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * parseErrObjList from the channel buffer.
 *
 * @param cb of type channel buffer
 * @throws PcepParseException if mandatory fields are missing
 */
public void parseErrObjList(ChannelBuffer cb) throws PcepParseException {
    byte yObjClass;
    byte yObjType;
    boolean bIsErrorObjFound = false;

    errObjList = new LinkedList<>();

    // caller should verify for RP object
    if (cb.readableBytes() < OBJECT_HEADER_LENGTH) {
        throw new PcepParseException("Unable to find PCEP-ERROR Object");
    }

    cb.markReaderIndex();
    PcepObjectHeader tempObjHeader = PcepObjectHeader.read(cb);
    cb.resetReaderIndex();
    yObjClass = tempObjHeader.getObjClass();
    yObjType = tempObjHeader.getObjType();
    PcepErrorObject errorObject;
    while ((yObjClass == PcepErrorObjectVer1.ERROR_OBJ_CLASS) && (yObjType == PcepErrorObjectVer1.ERROR_OBJ_TYPE)) {
        errorObject = PcepErrorObjectVer1.read(cb);
        errObjList.add(errorObject);
        bIsErrorObjFound = true;

        if (cb.readableBytes() > OBJECT_HEADER_LENGTH) {
            cb.markReaderIndex();
            tempObjHeader = PcepObjectHeader.read(cb);
            cb.resetReaderIndex();
            yObjClass = tempObjHeader.getObjClass();
            yObjType = tempObjHeader.getObjType();
        } else {
            break;
        }
    }

    if (!bIsErrorObjFound) {
        throw new PcepParseException("At least one PCEP-ERROR Object should be present.");
    }
}
 
Example 7
Source File: HelloPacket.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void readFrom(ChannelBuffer channelBuffer) throws OspfParseException {

    try {
        byte[] tempByteArray = new byte[OspfUtil.FOUR_BYTES];
        channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
        this.setNetworkMask(Ip4Address.valueOf(tempByteArray));
        this.setHelloInterval(channelBuffer.readShort());
        this.setOptions(channelBuffer.readByte());
        this.setRouterPriority(channelBuffer.readByte() & 0xff);
        this.setRouterDeadInterval(channelBuffer.readInt());
        tempByteArray = new byte[OspfUtil.FOUR_BYTES];
        channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
        this.setDr(Ip4Address.valueOf(tempByteArray));
        tempByteArray = new byte[OspfUtil.FOUR_BYTES];
        channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
        this.setBdr(Ip4Address.valueOf(tempByteArray));

        while (channelBuffer.readableBytes() > 0) {
            tempByteArray = new byte[OspfUtil.FOUR_BYTES];
            channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
            this.addNeighbor(Ip4Address.valueOf(tempByteArray));
        }

    } catch (Exception e) {
        log.debug("Error::HelloPacket:: {}", e.getMessage());
        throw new OspfParseException(OspfErrorType.MESSAGE_HEADER_ERROR, OspfErrorType.BAD_MESSAGE_LENGTH);
    }
}
 
Example 8
Source File: PcepLabelUpdateMsgVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public PcepLabelUpdateMsg readFrom(ChannelBuffer cb) throws PcepParseException {

    if (cb.readableBytes() < PACKET_MINIMUM_LENGTH) {
        throw new PcepParseException("Readable bytes are less than Packet minimum length.");
    }

    // fixed value property version == 1
    byte version = cb.readByte();
    version = (byte) (version >> PcepMessageVer1.SHIFT_FLAG);
    if (version != PACKET_VERSION) {
        throw new PcepParseException("Wrong version.Expected=PcepVersion.PCEP_1(1), got=" + version);
    }
    // fixed value property type == 13
    byte type = cb.readByte();
    if (type != MSG_TYPE.getType()) {
        throw new PcepParseException("Wrong type. Expected=PcepType.LABEL_UPDATE(13), got=" + type);
    }
    short length = cb.readShort();
    if (length < PACKET_MINIMUM_LENGTH) {
        throw new PcepParseException("Wrong length. Expected to be >= " + PACKET_MINIMUM_LENGTH + ", is: "
                + length);
    }
    // parse <pce-label-download> / <pce-label-map>
    LinkedList<PcepLabelUpdate> llPcLabelUpdateList = parsePcLabelUpdateList(cb);
    return new PcepLabelUpdateMsgVer1(llPcLabelUpdateList);
}
 
Example 9
Source File: WideCommunityAttrHeader.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the channel buffer and returns object of WideCommunityAttrHeader.
 *
 * @param c ChannelBuffer
 * @return object of WideCommunityAttrHeader
 * @throws BgpParseException if a parsing error occurs
 */
public static WideCommunityAttrHeader read(ChannelBuffer c) throws BgpParseException {

    if (c.readableBytes() < HEADER_LENGTH) {
        Validation.validateLen(BgpErrorType.UPDATE_MESSAGE_ERROR,
                               BgpErrorType.ATTRIBUTE_LENGTH_ERROR, c.readableBytes());
    }

    short type = c.readShort();
    byte flag = c.readByte();
    byte hopCount = c.readByte();
    short length = c.readShort();
    return WideCommunityAttrHeader.of(flag, hopCount, length);
}
 
Example 10
Source File: BgpPrefixAttrOspfFwdAddr.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the OSPF Forwarding Address.
 *
 * @param cb ChannelBuffer
 * @return object of BgpPrefixAttrOSPFFwdAddr
 * @throws BgpParseException while parsing BgpPrefixAttrOspfFwdAddr
 */
public static BgpPrefixAttrOspfFwdAddr read(ChannelBuffer cb)
        throws BgpParseException {
    short lsAttrLength;
    byte[] ipBytes;
    Ip4Address ip4RouterId = null;
    Ip6Address ip6RouterId = null;

    lsAttrLength = cb.readShort();
    ipBytes = new byte[lsAttrLength];

    if ((cb.readableBytes() < lsAttrLength)) {
        Validation.validateLen(BgpErrorType.UPDATE_MESSAGE_ERROR,
                               BgpErrorType.ATTRIBUTE_LENGTH_ERROR,
                               lsAttrLength);
    }

    cb.readBytes(ipBytes);

    if (IPV4_LEN == lsAttrLength) {
        ip4RouterId = Ip4Address.valueOf(ipBytes);
    } else if (IPV6_LEN == lsAttrLength) {
        ip6RouterId = Ip6Address.valueOf(ipBytes);
    }

    return BgpPrefixAttrOspfFwdAddr.of(lsAttrLength, ip4RouterId,
                                       ip6RouterId);
}
 
Example 11
Source File: IpInterfaceAddressTlv.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void readFrom(ChannelBuffer channelBuffer) {
    while (channelBuffer.readableBytes() >= 4) {
        byte[] addressbytes = new byte[IsisUtil.FOUR_BYTES];
        channelBuffer.readBytes(addressbytes, 0, IsisUtil.FOUR_BYTES);
        this.interfaceAddress.add(Ip4Address.valueOf(addressbytes));
    }
}
 
Example 12
Source File: RPCRecordDecoder.java    From nfs-client-java with Apache License 2.0 5 votes vote down vote up
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception {
    // Wait until the length prefix is available.
    if (channelBuffer.readableBytes() < 4) {
        // If null is returned, it means there is not enough data yet.
        // FrameDecoder will call again when there is a sufficient amount of data available.
        return null;
    }

    //marking the current reading position
    channelBuffer.markReaderIndex();

    //get the fragment size and wait until the entire fragment is available.
    long fragSize = channelBuffer.readUnsignedInt();
    boolean lastFragment = RecordMarkingUtil.isLastFragment(fragSize);
    fragSize = RecordMarkingUtil.maskFragmentSize(fragSize);
    if (channelBuffer.readableBytes() < fragSize) {
        channelBuffer.resetReaderIndex();
        return null;
    }

    //seek to the beginning of the next fragment
    channelBuffer.skipBytes((int) fragSize);

    _recordLength += 4 + (int) fragSize;

    //check the last fragment
    if (!lastFragment) {
        //not the last fragment, the data is put in an internally maintained cumulative buffer
        return null;
    }

    byte[] rpcResponse = new byte[_recordLength];
    channelBuffer.readerIndex(channelBuffer.readerIndex() - _recordLength);
    channelBuffer.readBytes(rpcResponse, 0, _recordLength);

    _recordLength = 0;
    return rpcResponse;
}
 
Example 13
Source File: AreaAddressTlv.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void readFrom(ChannelBuffer channelBuffer) {
    while (channelBuffer.readableBytes() > 0) {
        int addressLength = channelBuffer.readByte();
        byte[] addressbytes = new byte[addressLength];
        channelBuffer.readBytes(addressbytes, 0, addressLength);
        String areaAddress = IsisUtil.areaAddress(addressbytes);
        this.areaAddress.add(areaAddress);
    }
}
 
Example 14
Source File: PcepUpdateMsgVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Parse update request list.
 *
 * @param cb of type channel buffer
 * @return true after parsing Update Request List
 * @throws PcepParseException while parsing update request list from channel buffer
 */
public boolean parseUpdateRequestList(ChannelBuffer cb) throws PcepParseException {

    /*                     <update-request-list>
     * Where:
     *   <update-request-list>     ::= <update-request>[<update-request-list>]
     *   <update-request>          ::= <SRP>
     *                                 <LSP>
     *                                 <path>
     * Where:
     *   <path>                     ::= <ERO><attribute-list>
     * Where:
     * <attribute-list> is defined in [RFC5440] and extended by PCEP extensions.
     */

    while (0 < cb.readableBytes()) {

        PcepUpdateRequest pceUpdateReq = new PcepUpdateRequestVer1();

        //Read SRP Object and Store it.
        PcepSrpObject srpObj;
        srpObj = PcepSrpObjectVer1.read(cb);
        pceUpdateReq.setSrpObject(srpObj);

        //Read LSP object and Store it.
        PcepLspObject lspObj;
        lspObj = PcepLspObjectVer1.read(cb);
        pceUpdateReq.setLspObject(lspObj);

        // Read Msg Path and store it.
        PcepMsgPath msgPath = new PcepMsgPathVer1().read(cb);
        pceUpdateReq.setMsgPath(msgPath);

        llUpdateRequestList.add(pceUpdateReq);
    }
    return true;
}
 
Example 15
Source File: LinkType.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Reads from channel buffer.
 *
 * @param channelBuffer channel buffer instance
 * @throws OspfParseException might throws exception while parsing buffer
 */
public void readFrom(ChannelBuffer channelBuffer) throws OspfParseException {
    try {
        int len = channelBuffer.readableBytes();
        byte[] tempByteArray = new byte[len];
        channelBuffer.readBytes(tempByteArray, 0, len);
        this.setLinkType(OspfUtil.byteToInteger(tempByteArray));
    } catch (Exception e) {
        log.debug("Error::LinkType:: {}", e.getMessage());
        throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR,
                                     OspfErrorType.BAD_MESSAGE);
    }
}
 
Example 16
Source File: NettyCodecAdapter.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
    Object o = event.getMessage();
    if (!(o instanceof ChannelBuffer)) {
        ctx.sendUpstream(event);
        return;
    }

    ChannelBuffer input = (ChannelBuffer) o;
    int readable = input.readableBytes();
    if (readable <= 0) {
        return;
    }

    com.alibaba.dubbo.remoting.buffer.ChannelBuffer message;
    if (buffer.readable()) {
        if (buffer instanceof DynamicChannelBuffer) {
            buffer.writeBytes(input.toByteBuffer());
            message = buffer;
        } else {
            int size = buffer.readableBytes() + input.readableBytes();
            message = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(
                    size > bufferSize ? size : bufferSize);
            message.writeBytes(buffer, buffer.readableBytes());
            message.writeBytes(input.toByteBuffer());
        }
    } else {
        message = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer(
                input.toByteBuffer());
    }

    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
    Object msg;
    int saveReaderIndex;

    try {
        // decode object.
        do {
            saveReaderIndex = message.readerIndex();
            try {
                msg = codec.decode(channel, message);
            } catch (IOException e) {
                buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
                throw e;
            }
            if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) {
                message.readerIndex(saveReaderIndex);
                break;
            } else {
                if (saveReaderIndex == message.readerIndex()) {
                    buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
                    throw new IOException("Decode without read data.");
                }
                if (msg != null) {
                    Channels.fireMessageReceived(ctx, msg, event.getRemoteAddress());
                }
            }
        } while (message.readable());
    } finally {
        if (message.readable()) {
            message.discardReadBytes();
            buffer = message;
        } else {
            buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
        }
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}
 
Example 17
Source File: MemcachedBinaryCommandDecoder.java    From fqueue with Apache License 2.0 4 votes vote down vote up
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception {

        // need at least 24 bytes, to get header
        if (channelBuffer.readableBytes() < 24) return null;

        // get the header
        channelBuffer.markReaderIndex();
        ChannelBuffer headerBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24);
        channelBuffer.readBytes(headerBuffer);

        short magic = headerBuffer.readUnsignedByte();

        // magic should be 0x80
        if (magic != 0x80) {
            headerBuffer.resetReaderIndex();

            throw new MalformedCommandException("binary request payload is invalid, magic byte incorrect");
        }

        short opcode = headerBuffer.readUnsignedByte();
        short keyLength = headerBuffer.readShort();
        short extraLength = headerBuffer.readUnsignedByte();
        short dataType = headerBuffer.readUnsignedByte();   // unused
        short reserved = headerBuffer.readShort(); // unused
        int totalBodyLength = headerBuffer.readInt();
        int opaque = headerBuffer.readInt();
        long cas = headerBuffer.readLong();

        // we want the whole of totalBodyLength; otherwise, keep waiting.
        if (channelBuffer.readableBytes() < totalBodyLength) {
            channelBuffer.resetReaderIndex();
            return null;
        }

        // This assumes correct order in the enum. If that ever changes, we will have to scan for 'code' field.
        BinaryCommand bcmd = BinaryCommand.values()[opcode];

        Command cmdType = bcmd.correspondingCommand;
        CommandMessage cmdMessage = CommandMessage.command(cmdType);
        cmdMessage.noreply = bcmd.noreply;
        cmdMessage.cas_key = cas;
        cmdMessage.opaque = opaque;
        cmdMessage.addKeyToResponse = bcmd.addKeyToResponse;

        // get extras. could be empty.
        ChannelBuffer extrasBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, extraLength);
        channelBuffer.readBytes(extrasBuffer);

        // get the key if any
        if (keyLength != 0) {
            ChannelBuffer keyBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, keyLength);
            channelBuffer.readBytes(keyBuffer);

            ArrayList<String> keys = new ArrayList<String>();
            String key = keyBuffer.toString(USASCII);
            keys.add(key); // TODO this or UTF-8? ISO-8859-1?

            cmdMessage.keys = keys;


            if (cmdType == Command.ADD ||
                    cmdType == Command.SET ||
                    cmdType == Command.REPLACE ||
                    cmdType == Command.APPEND ||
                    cmdType == Command.PREPEND)
            {
                // TODO these are backwards from the spec, but seem to be what spymemcached demands -- which has the mistake?!
                short expire = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0);
                short flags = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0);

                // the remainder of the message -- that is, totalLength - (keyLength + extraLength) should be the payload
                int size = totalBodyLength - keyLength - extraLength;

                cmdMessage.element = new LocalCacheElement(key, flags, expire != 0 && expire < CacheElement.THIRTY_DAYS ? LocalCacheElement.Now() + expire : expire, 0L);
                cmdMessage.element.setData(new byte[size]);
                channelBuffer.readBytes(cmdMessage.element.getData(), 0, size);
            } else if (cmdType == Command.INCR || cmdType == Command.DECR) {
                long initialValue = extrasBuffer.readUnsignedInt();
                long amount = extrasBuffer.readUnsignedInt();
                long expiration = extrasBuffer.readUnsignedInt();

                cmdMessage.incrAmount = (int) amount;
                cmdMessage.incrDefault = (int) initialValue;
                cmdMessage.incrExpiry = (int) expiration;
            }
        }

        return cmdMessage;
    }
 
Example 18
Source File: NettyCodecAdapter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
    Object o = event.getMessage();
    if (! (o instanceof ChannelBuffer)) {
        ctx.sendUpstream(event);
        return;
    }

    ChannelBuffer input = (ChannelBuffer) o;
    int readable = input.readableBytes();
    if (readable <= 0) {
        return;
    }

    com.alibaba.dubbo.remoting.buffer.ChannelBuffer message;
    if (buffer.readable()) {
        if (buffer instanceof DynamicChannelBuffer) {
            buffer.writeBytes(input.toByteBuffer());
            message = buffer;
        } else {
            int size = buffer.readableBytes() + input.readableBytes();
            message = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(
                size > bufferSize ? size : bufferSize);
            message.writeBytes(buffer, buffer.readableBytes());
            message.writeBytes(input.toByteBuffer());
        }
    } else {
        message = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer(
            input.toByteBuffer());
    }

    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
    Object msg;
    int saveReaderIndex;

    try {
        // decode object.
        do {
            saveReaderIndex = message.readerIndex();
            try {
                msg = codec.decode(channel, message);
            } catch (IOException e) {
                buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
                throw e;
            }
            if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) {
                message.readerIndex(saveReaderIndex);
                break;
            } else {
                if (saveReaderIndex == message.readerIndex()) {
                    buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
                    throw new IOException("Decode without read data.");
                }
                if (msg != null) {
                    Channels.fireMessageReceived(ctx, msg, event.getRemoteAddress());
                }
            }
        } while (message.readable());
    } finally {
        if (message.readable()) {
            message.discardReadBytes();
            buffer = message;
        } else {
            buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
        }
        NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
    }
}
 
Example 19
Source File: LsUpdate.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public void readFrom(ChannelBuffer channelBuffer) throws OspfParseException {
    try {
        //From header 4 bytes is number of lsa's
        this.setNumberOfLsa(channelBuffer.readInt());
        //get the remaining bytes represents Number of LSA's present. Add all the LSA's
        while (channelBuffer.readableBytes() > OspfUtil.LSA_HEADER_LENGTH) {

            LsaHeader header = OspfUtil.readLsaHeader(channelBuffer.readBytes(OspfUtil.LSA_HEADER_LENGTH));
            int lsaLength = header.lsPacketLen();
            int lsType = header.lsType();

            switch (lsType) {
                case OspfParameters.LINK_LOCAL_OPAQUE_LSA:
                    OpaqueLsa9 opaqueLsa9 = new OpaqueLsa9((OpaqueLsaHeader) header);
                    opaqueLsa9.readFrom(channelBuffer.readBytes(lsaLength - OspfUtil.LSA_HEADER_LENGTH));
                    addLsa(opaqueLsa9);
                    break;
                case OspfParameters.AREA_LOCAL_OPAQUE_LSA:
                    OpaqueLsa10 opaqueLsa10 = new OpaqueLsa10((OpaqueLsaHeader) header);
                    opaqueLsa10.readFrom(channelBuffer.readBytes(lsaLength - OspfUtil.LSA_HEADER_LENGTH));
                    addLsa(opaqueLsa10);
                    break;
                case OspfParameters.AS_OPAQUE_LSA:
                    OpaqueLsa11 opaqueLsa11 = new OpaqueLsa11((OpaqueLsaHeader) header);
                    opaqueLsa11.readFrom(channelBuffer.readBytes(lsaLength - OspfUtil.LSA_HEADER_LENGTH));
                    addLsa(opaqueLsa11);
                    break;
                case OspfParameters.ROUTER:
                    RouterLsa routerLsa = new RouterLsa(header);
                    routerLsa.readFrom(channelBuffer.readBytes(lsaLength - OspfUtil.LSA_HEADER_LENGTH));
                    addLsa(routerLsa);
                    break;
                case OspfParameters.NETWORK:
                    NetworkLsa networkLsa = new NetworkLsa(header);
                    networkLsa.readFrom(channelBuffer.readBytes(lsaLength - OspfUtil.LSA_HEADER_LENGTH));
                    addLsa(networkLsa);
                    break;
                case OspfParameters.ASBR_SUMMARY:
                    AsbrSummaryLsa asbrSummaryLsa = new AsbrSummaryLsa(header);
                    asbrSummaryLsa.readFrom(channelBuffer.readBytes(lsaLength - OspfUtil.LSA_HEADER_LENGTH));
                    addLsa(asbrSummaryLsa);
                    break;
                case OspfParameters.SUMMARY:
                    SummaryLsa summaryLsa = new SummaryLsa(header);
                    summaryLsa.readFrom(channelBuffer.readBytes(lsaLength - OspfUtil.LSA_HEADER_LENGTH));
                    addLsa(summaryLsa);
                    break;
                case OspfParameters.EXTERNAL_LSA:
                    ExternalLsa externalLsa = new ExternalLsa(header);
                    externalLsa.readFrom(channelBuffer.readBytes(lsaLength - OspfUtil.LSA_HEADER_LENGTH));
                    addLsa(externalLsa);
                    break;
                default:
                    log.debug("LSUpdate::readLsUpdateBody::UnKnown LS Type: {}", lsType);
                    break;
            }
        }
    } catch (Exception e) {
        log.debug("Error::LsUpdate:: {}", e.getMessage());
        throw new OspfParseException(OspfErrorType.MESSAGE_HEADER_ERROR, OspfErrorType.BAD_MESSAGE_LENGTH);
    }
}
 
Example 20
Source File: PcepLspObjectVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns Linked list of optional tlvs.
 *
 * @param cb of channel buffer.
 * @return list of optional tlvs
 * @throws PcepParseException when unsupported tlv is received
 */
protected static LinkedList<PcepValueType> parseOptionalTlv(ChannelBuffer cb) throws PcepParseException {

    LinkedList<PcepValueType> llOutOptionalTlv;

    llOutOptionalTlv = new LinkedList<>();

    while (MINIMUM_COMMON_HEADER_LENGTH <= cb.readableBytes()) {

        PcepValueType tlv = null;
        short hType = cb.readShort();
        short hLength = cb.readShort();
        int iValue = 0;

        switch (hType) {

        case StatefulIPv4LspIdentifiersTlv.TYPE:
            tlv = StatefulIPv4LspIdentifiersTlv.read(cb);
            break;
        case StatefulLspErrorCodeTlv.TYPE:
            iValue = cb.readInt();
            tlv = new StatefulLspErrorCodeTlv(iValue);
            break;
        case StatefulRsvpErrorSpecTlv.TYPE:
            tlv = StatefulRsvpErrorSpecTlv.read(cb);
            break;
        case SymbolicPathNameTlv.TYPE:
            tlv = SymbolicPathNameTlv.read(cb, hLength);
            break;
        case StatefulLspDbVerTlv.TYPE:
            tlv = StatefulLspDbVerTlv.read(cb);
            break;
        default:
            // Skip the unknown TLV.
            cb.skipBytes(hLength);
            log.info("Received unsupported TLV type :" + hType + " in LSP object.");
        }
        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }

        if (tlv != null) {
            llOutOptionalTlv.add(tlv);
        }
    }

    if (0 < cb.readableBytes()) {

        throw new PcepParseException("Optional Tlv parsing error. Extra bytes received.");
    }
    return llOutOptionalTlv;
}