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

The following are Jave code examples for showing how to use readableBytes() of the org.jboss.netty.buffer.ChannelBuffer 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: athena   File: BgpNodeLSIdentifier.java   Source Code and License Vote up 6 votes
/**
 * Parse local node descriptors.
 *
 * @param cb ChannelBuffer
 * @param protocolId protocol identifier
 * @return object of this BGPNodeLSIdentifier
 * @throws BgpParseException while parsing local node descriptors
 */
public static BgpNodeLSIdentifier parseLocalNodeDescriptors(ChannelBuffer cb, byte protocolId)
        throws BgpParseException {
    log.debug("parse Local node descriptor");
    ChannelBuffer tempBuf = cb.copy();
    short type = cb.readShort();
    short length = cb.readShort();
    if (cb.readableBytes() < length) {
        throw new BgpParseException(BgpErrorType.UPDATE_MESSAGE_ERROR, BgpErrorType.OPTIONAL_ATTRIBUTE_ERROR,
                                    tempBuf.readBytes(cb.readableBytes() + Constants.TYPE_AND_LEN));
    }
    NodeDescriptors nodeDescriptors = new NodeDescriptors();
    ChannelBuffer tempCb = cb.readBytes(length);

    if (type == NodeDescriptors.LOCAL_NODE_DES_TYPE) {
        nodeDescriptors = NodeDescriptors.read(tempCb, length, type, protocolId);
    } else {
        throw new BgpParseException(BgpErrorType.UPDATE_MESSAGE_ERROR, BgpErrorType.MALFORMED_ATTRIBUTE_LIST, null);
    }
    return new BgpNodeLSIdentifier(nodeDescriptors);
}
 
Example 2
Project: athena   File: BgpLinkAttrMaxLinkBandwidth.java   Source Code and License Vote up 6 votes
/**
 * Reads the BGP link attributes of Maximum link bandwidth.
 *
 * @param cb Channel buffer
 * @param type type of this tlv
 * @return object of type BgpLinkAttrMaxLinkBandwidth
 * @throws BgpParseException while parsing BgpLinkAttrMaxLinkBandwidth
 */
public static BgpLinkAttrMaxLinkBandwidth read(ChannelBuffer cb, short type)
        throws BgpParseException {
    float maxBandwidth;
    short lsAttrLength = cb.readShort();

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

    maxBandwidth = ieeeToFloatRead(cb.readInt()) * NO_OF_BITS;

    return BgpLinkAttrMaxLinkBandwidth.of(maxBandwidth, type);
}
 
Example 3
Project: traccar-service   File: IntellitracFrameDecoder.java   Source Code and License Vote up 6 votes
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {

    // Check minimum length
    if (buf.readableBytes() < MESSAGE_MINIMUM_LENGTH) {
        return null;
    }

    // Check for sync packet
    if (buf.getUnsignedShort(buf.readerIndex()) == 0xFAF8) {
        ChannelBuffer syncMessage = buf.readBytes(8);
        if (channel != null) {
            channel.write(syncMessage);
        }
    }

    return super.decode(ctx, channel, buf);
}
 
Example 4
Project: athena   File: NetworkLsa.java   Source Code and License Vote up 6 votes
/**
 * Reads from channel buffer and populate instance.
 *
 * @param channelBuffer channel buffer instance
 * @throws OspfParseException might throws exception while parsing buffer
 */
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));
        //add all the attached routers
        while (channelBuffer.readableBytes() > 0) {
            tempByteArray = new byte[OspfUtil.FOUR_BYTES];
            channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
            this.addAttachedRouter(Ip4Address.valueOf(tempByteArray));
        }
    } catch (Exception e) {
        log.debug("Error::NetworkLSA::readFrom:: {}", e.getMessage());
        throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR, OspfErrorType.BAD_MESSAGE);
    }
}
 
Example 5
Project: athena   File: LsRequest.java   Source Code and License Vote up 6 votes
@Override
public void readFrom(ChannelBuffer channelBuffer) throws OspfParseException {

    while (channelBuffer.readableBytes() >= OspfUtil.LSREQUEST_LENGTH) {
        LsRequestPacket lsRequestPacket = new LsRequestPacket();
        lsRequestPacket.setLsType(channelBuffer.readInt());
        byte[] tempByteArray = new byte[OspfUtil.FOUR_BYTES];
        channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
        lsRequestPacket.setLinkStateId(Ip4Address.valueOf(tempByteArray).toString());
        tempByteArray = new byte[OspfUtil.FOUR_BYTES];
        channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
        lsRequestPacket.setOwnRouterId(Ip4Address.valueOf(tempByteArray).toString());

        this.addLinkStateRequests(lsRequestPacket);
    }
}
 
Example 6
Project: traccar-service   File: AlematicsFrameDecoder.java   Source Code and License Vote up 6 votes
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {

    if (buf.readableBytes() < MESSAGE_MINIMUM_LENGTH) {
        return null;
    }

    if (buf.getUnsignedShort(buf.readerIndex()) == 0xFAF8) {
        ChannelBuffer heartbeat = buf.readBytes(12);
        if (channel != null) {
            channel.write(heartbeat);
        }
    }

    return super.decode(ctx, channel, buf);
}
 
Example 7
Project: athena   File: BgpPrefixAttrOpaqueData.java   Source Code and License Vote up 6 votes
/**
 * Reads the Opaque Prefix Attribute.
 *
 * @param cb ChannelBuffer
 * @return object of BgpPrefixAttrOpaqueData
 * @throws BgpParseException while parsing BgpPrefixAttrOpaqueData
 */
public static BgpPrefixAttrOpaqueData read(ChannelBuffer cb)
        throws BgpParseException {
    byte[] opaquePrefixAttribute;

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

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

    cb.readBytes(opaquePrefixAttribute);

    return BgpPrefixAttrOpaqueData.of(opaquePrefixAttribute);
}
 
Example 8
Project: Elasticsearch   File: RemoteDigestBlob.java   Source Code and License Vote up 6 votes
private Status start(ChannelBuffer buffer, boolean last) {
    logger.trace("start blob upload");
    assert (transferId == null);
    StartBlobRequest request = new StartBlobRequest(
            index,
            Hex.decodeHex(digest),
            new BytesArray(buffer.array()),
            last
    );
    transferId = request.transferId();
    size += buffer.readableBytes();

    startResponse = client.execute(StartBlobAction.INSTANCE, request).actionGet();
    status = startResponse.status();
    return status;
}
 
Example 9
Project: athena   File: FpmFrameDecoder.java   Source Code and License Vote up 5 votes
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer)
        throws Exception {

    if (!channel.isConnected()) {
        return null;
    }

    if (buffer.readableBytes() < FpmHeader.FPM_HEADER_LENGTH) {
        return null;
    }

    buffer.markReaderIndex();

    short version = buffer.readUnsignedByte();
    short type = buffer.readUnsignedByte();
    int length = buffer.readUnsignedShort();

    buffer.resetReaderIndex();

    if (buffer.readableBytes() < length) {
        // Not enough bytes to read a whole message
        return null;
    }

    byte[] fpmMessage = new byte[length];
    buffer.readBytes(fpmMessage);

    return FpmHeader.decode(fpmMessage, 0, fpmMessage.length);
}
 
Example 10
Project: athena   File: AdjacencyStateTlv.java   Source Code and License Vote up 5 votes
@Override
public void readFrom(ChannelBuffer channelBuffer) {
    this.setAdjacencyType(channelBuffer.readByte());
    this.setLocalCircuitId(channelBuffer.readInt());
    if (channelBuffer.readableBytes() > 0) {
        byte[] tempByteArray = new byte[IsisUtil.ID_SIX_BYTES];
        channelBuffer.readBytes(tempByteArray, 0, IsisUtil.ID_SIX_BYTES);
        this.setNeighborSystemId(IsisUtil.systemId(tempByteArray));
        this.setNeighborLocalCircuitId(channelBuffer.readInt());
    }
}
 
Example 11
Project: athena   File: PcepReportMsgVer1.java   Source Code and License Vote up 5 votes
@Override
public PcepReportMsg readFrom(ChannelBuffer cb) throws PcepParseException {

    if (cb.readableBytes() < PACKET_MINIMUM_LENGTH) {
        throw new PcepParseException("Received packet size " + cb.readableBytes()
                + " is less than the expected size: " + PACKET_MINIMUM_LENGTH);
    }
    llStateReportList = new LinkedList<>();
    byte version = cb.readByte();
    version = (byte) (version >> PcepMessageVer1.SHIFT_FLAG);

    if (version != PACKET_VERSION) {
        throw new PcepParseException(" Invalid version: " + version);
    }

    byte type = cb.readByte();

    if (type != MSG_TYPE.getType()) {
        throw new PcepParseException("Unexpected type: " + type);
    }

    short length = cb.readShort();

    if (length < PACKET_MINIMUM_LENGTH) {
        throw new PcepParseException("Wrong length. Expected to be >= " + PACKET_MINIMUM_LENGTH + ", was: "
                + length);
    }
    // parse state report list
    parseStateReportList(cb);
    return new PcepReportMsgVer1(llStateReportList);
}
 
Example 12
Project: traccar-service   File: AplicomFrameDecoder.java   Source Code and License Vote up 5 votes
@Override
protected Object decode(
        ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {

    // Skip Alive message
    while (buf.readable() && Character.isDigit(buf.getByte(buf.readerIndex()))) {
        buf.readByte();
    }

    // Check minimum length
    if (buf.readableBytes() < 11) {
        return null;
    }

    // Read flags
    int version = buf.getUnsignedByte(buf.readerIndex() + 1);
    int offset = 1 + 1 + 3;
    if ((version & 0x80) != 0) {
        offset += 4;
    }

    // Get data length
    int length = buf.getUnsignedShort(buf.readerIndex() + offset);
    offset += 2;
    if ((version & 0x40) != 0) {
        offset += 3;
    }
    length += offset; // add header

    // Return buffer
    if (buf.readableBytes() >= length) {
        return buf.readBytes(length);
    }

    return null;
}
 
Example 13
Project: athena   File: PcepErrorVer1.java   Source Code and License Vote up 5 votes
/**
 * Parse RP List from the channel buffer.
 *
 * @param cb of type channel buffer
 * @throws PcepParseException if mandatory fields are missing
 */
public void parseRPList(ChannelBuffer cb) throws PcepParseException {
    byte yObjClass;
    byte yObjType;

    rpObjList = new LinkedList<>();

    // caller should verify for RP object
    if (cb.readableBytes() < OBJECT_HEADER_LENGTH) {
        log.debug("Unable to find RP Object");
        return;
    }

    cb.markReaderIndex();
    PcepObjectHeader tempObjHeader = PcepObjectHeader.read(cb);
    cb.resetReaderIndex();
    yObjClass = tempObjHeader.getObjClass();
    yObjType = tempObjHeader.getObjType();
    PcepRPObject rpObj;
    while ((yObjClass == PcepRPObjectVer1.RP_OBJ_CLASS) && (yObjType == PcepRPObjectVer1.RP_OBJ_TYPE)) {
        rpObj = PcepRPObjectVer1.read(cb);
        rpObjList.add(rpObj);

        if (cb.readableBytes() > OBJECT_HEADER_LENGTH) {
            cb.markReaderIndex();
            tempObjHeader = PcepObjectHeader.read(cb);
            cb.resetReaderIndex();
            yObjClass = tempObjHeader.getObjClass();
            yObjType = tempObjHeader.getObjType();
        } else {
            break;
        }
    }
}
 
Example 14
Project: athena   File: TestBgpPeerFrameDecoder.java   Source Code and License Vote up 5 votes
/**
 * Processes BGP KEEPALIVE message.
 *
 * @param ctx the Channel Handler Context.
 * @param message the message to process.
 */
private void processBgpKeepalive(ChannelHandlerContext ctx,
                                 ChannelBuffer message) {
    if (message.readableBytes() + BgpConstants.BGP_HEADER_LENGTH !=
        BgpConstants.BGP_KEEPALIVE_EXPECTED_LENGTH) {
        // ERROR: Bad Message Length. Close the channel.
        ctx.getChannel().close();
        return;
    }
    // BGP KEEPALIVE message successfully received
    receivedKeepaliveMessageLatch.countDown();
}
 
Example 15
Project: athena   File: NeighborForExtendedIs.java   Source Code and License Vote up 5 votes
/**
 * Reads from the channel buffer and populate this instance.
 *
 * @param channelBuffer channel buffer instance
 */
public void readFrom(ChannelBuffer channelBuffer) {
    byte[] tempByteArray = new byte[IsisUtil.ID_PLUS_ONE_BYTE];
    channelBuffer.readBytes(tempByteArray, 0, IsisUtil.ID_PLUS_ONE_BYTE);
    this.setNeighborId(IsisUtil.systemIdPlus(tempByteArray));
    this.setMetric(channelBuffer.readUnsignedMedium());
    int nTlvPresent = channelBuffer.readByte();
    if (nTlvPresent > 0) {
        while (channelBuffer.readableBytes() > IsisUtil.TWO_BYTES) {
            TlvHeader tlvHeader = new TlvHeader();
            tlvHeader.setTlvType(channelBuffer.readByte());
            tlvHeader.setTlvLength(channelBuffer.readByte());
            SubTlvType tlvValue = SubTlvType.get(tlvHeader.tlvType());
            int tlvLength = tlvHeader.tlvLength();
            if (tlvValue != null) {
                if (channelBuffer.readableBytes() >= tlvLength) {
                    TrafficEngineeringSubTlv subTlv =
                            SubTlvFinder.findSubTlv(tlvHeader, channelBuffer.readBytes(tlvHeader.tlvLength()));
                    if (subTlv != null) {
                        this.addSubTlv(subTlv);
                    }
                }
            } else {
                if (channelBuffer.readableBytes() >= tlvLength) {
                    channelBuffer.readBytes(tlvLength);
                }
            }
        }
    }
}
 
Example 16
Project: athena   File: NodeAttributesTlv.java   Source Code and License Vote up 4 votes
/**
 * Reads the channel buffer and returns object of NodeAttributesTlv.
 *
 * @param c input channel buffer
 * @param hLength length
 * @return object of NodeAttributesTlv
 * @throws PcepParseException if mandatory fields are missing
 */
public static PcepValueType read(ChannelBuffer c, short hLength) throws PcepParseException {

    // Node Descriptor Sub-TLVs (variable)
    List<PcepValueType> llNodeAttributesSubTLVs = new LinkedList<>();

    ChannelBuffer tempCb = c.readBytes(hLength);

    while (TLV_HEADER_LENGTH <= tempCb.readableBytes()) {
        PcepValueType tlv;
        short hType = tempCb.readShort();
        int iValue = 0;
        short length = tempCb.readShort();
        switch (hType) {

        case NodeFlagBitsSubTlv.TYPE:
            byte cValue = tempCb.readByte();
            tlv = new NodeFlagBitsSubTlv(cValue);
            break;
        case OpaqueNodePropertiesSubTlv.TYPE:
            tlv = OpaqueNodePropertiesSubTlv.read(tempCb, length);
            break;
        case NodeNameSubTlv.TYPE:
            tlv = NodeNameSubTlv.read(tempCb, length);
            break;
        case IsisAreaIdentifierSubTlv.TYPE:
            tlv = IsisAreaIdentifierSubTlv.read(tempCb, length);
            break;
        case IPv4RouterIdOfLocalNodeSubTlv.TYPE:
            iValue = tempCb.readInt();
            tlv = new IPv4RouterIdOfLocalNodeSubTlv(iValue);
            break;
        case IPv6RouterIdofLocalNodeSubTlv.TYPE:
            byte[] ipv6Value = new byte[IPv6RouterIdofLocalNodeSubTlv.VALUE_LENGTH];
            tempCb.readBytes(ipv6Value, 0, IPv6RouterIdofLocalNodeSubTlv.VALUE_LENGTH);
            tlv = new IPv6RouterIdofLocalNodeSubTlv(ipv6Value);
            break;
        default:
            throw new PcepParseException("Unsupported Sub TLV type :" + hType);
        }

        // Check for the padding
        int pad = length % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= tempCb.readableBytes()) {
                tempCb.skipBytes(pad);
            }
        }

        llNodeAttributesSubTLVs.add(tlv);
    }

    if (0 < tempCb.readableBytes()) {

        throw new PcepParseException("Sub Tlv parsing error. Extra bytes received.");
    }
    return new NodeAttributesTlv(llNodeAttributesSubTLVs);
}
 
Example 17
Project: athena   File: WideCommunity.java   Source Code and License Vote up 4 votes
/**
 * Reads the wide community attribute.
 *
 * @param c ChannelBuffer
 * @return object of WideCommunityAttr
 * @throws BgpParseException while parsing BgpPrefixAttrRouteTag
 */
public static WideCommunity read(ChannelBuffer c) throws BgpParseException {

    WideCommunityAttrHeader wideCommunityHeader;
    int community;
    int localAsn;
    int contextAsn;
    WideCommunityTarget target = null;
    WideCommunityExcludeTarget excludeTarget = null;
    WideCommunityParameter parameter = null;

    short length = c.readShort();

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

    wideCommunityHeader = WideCommunityAttrHeader.read(c);
    if ((c.readableBytes() < 12) || (c.readableBytes() < wideCommunityHeader.length())) {
        Validation.validateLen(BgpErrorType.UPDATE_MESSAGE_ERROR, BgpErrorType.ATTRIBUTE_LENGTH_ERROR, length);
    }

    community = c.readInt();
    localAsn = c.readInt();
    contextAsn = c.readInt();

    while (c.readableBytes() > 0) {

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

        byte type = c.readByte();
        length = c.readShort();

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

        if (type == WideCommunityTarget.TYPE) {
            target = WideCommunityTarget.read(c);
        } else if (type == WideCommunityExcludeTarget.TYPE) {
            excludeTarget = WideCommunityExcludeTarget.read(c);
        } else if (type == WideCommunityParameter.TYPE) {
            parameter = WideCommunityParameter.read(c);
        }
    }
    return new WideCommunity(wideCommunityHeader, community, localAsn, contextAsn,
                                 target, excludeTarget, parameter);
}
 
Example 18
Project: athena   File: PcepErrorMsgVer1.java   Source Code and License Vote up 4 votes
/**
 * Parsing PCErr Message.
 *
 * @param cb channel buffer.
 * @throws PcepParseException if mandatory fields are missing
 * output: this.errObjListWithOpen, this.errInfo
 */
public void parsePCErrMsg(ChannelBuffer cb) throws PcepParseException {
    //If PCEP-ERROR list is followed by OPEN Object then store into ErrorObjListWithOpen.
    //     ( <error-obj-list> [<Open>]
    //If PCEP-ERROR list is followed by RP or LS Object then store into errInfo. <error> [<error-list>]
    //If only PCEP-ERROR list is present then store into ErrorObjListWithOpen.
    PcepObjectHeader tempObjHeader;
    List<PcepErrorObject> llErrObjList;

    if (0 >= cb.readableBytes()) {
        throw new PcepParseException("PCEP-ERROR message came with empty objects.");
    }

    //parse PCEP-ERROR list
    llErrObjList = new LinkedList<>();
    tempObjHeader = parseErrorObjectList(llErrObjList, cb);

    //check whether OPEN-OBJECT is present.
    if ((tempObjHeader != null)
            && (tempObjHeader.getObjClass() == PcepOpenObjectVer1.OPEN_OBJ_CLASS)) {

        if (llErrObjList.isEmpty()) {
            throw new PcepParseException("<error-obj-list> should be present if OPEN-OBJECT exists");
        }

        PcepOpenObject pcepOpenObj = PcepOpenObjectVer1.read(cb);
        this.errObjListWithOpen = new ErrorObjListWithOpen(llErrObjList, pcepOpenObj);

    } else if ((tempObjHeader != null) //check whether RP or LS Object is present.
            && ((tempObjHeader.getObjClass() == PcepRPObjectVer1.RP_OBJ_CLASS)
                    || (tempObjHeader.getObjClass() == PcepLSObjectVer1.LS_OBJ_CLASS))) {

        this.errInfo = new PcepErrorInfoVer1(null, null, llErrObjList);
        this.errInfo.read(cb);

    } else if (!llErrObjList.isEmpty()) {
        //If only PCEP-ERROR list is present then store it in errObjListWithOpen.
        this.errObjListWithOpen = new ErrorObjListWithOpen(llErrObjList);
    } else {
        throw new PcepParseException("Empty PCEP-ERROR message.");
    }
}
 
Example 19
Project: athena   File: RemoteNodeDescriptorsTlv.java   Source Code and License Vote up 4 votes
/**
 * Reads channel buffer and returns object of Remote TE Node Descriptors TLV.
 *
 * @param c input channel buffer
 * @param length length of buffer
 * @return object of RemoteNodeDescriptorsTlv
 * @throws PcepParseException if mandatory fields are missing
 */
public static PcepValueType read(ChannelBuffer c, short length) throws PcepParseException {

    // Node Descriptor Sub-TLVs (variable)
    List<PcepValueType> llRemoteTENodeDescriptorSubTLVs = new LinkedList<>();

    ChannelBuffer tempCb = c.readBytes(length);

    while (TLV_HEADER_LENGTH <= tempCb.readableBytes()) {

        PcepValueType tlv;
        short hType = tempCb.readShort();
        int iValue = 0;
        short hLength = tempCb.readShort();
        switch (hType) {

        case AutonomousSystemSubTlv.TYPE:
            iValue = tempCb.readInt();
            tlv = new AutonomousSystemSubTlv(iValue);
            break;
        case BgpLsIdentifierSubTlv.TYPE:
            iValue = tempCb.readInt();
            tlv = new BgpLsIdentifierSubTlv(iValue);
            break;
        case OspfAreaIdSubTlv.TYPE:
            iValue = tempCb.readInt();
            tlv = new OspfAreaIdSubTlv(iValue);
            break;
        case IgpRouterIdSubTlv.TYPE:
            tlv = IgpRouterIdSubTlv.read(tempCb, hLength);
            break;

        default:
            throw new PcepParseException("Unsupported Sub TLV type :" + hType);
        }

        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= tempCb.readableBytes()) {
                tempCb.skipBytes(pad);
            }
        }

        llRemoteTENodeDescriptorSubTLVs.add(tlv);
    }

    if (0 < tempCb.readableBytes()) {

        throw new PcepParseException("Sub Tlv parsing error. Extra bytes received.");
    }
    return new RemoteNodeDescriptorsTlv(llRemoteTENodeDescriptorSubTLVs);
}
 
Example 20
Project: traccar-service   File: TytanProtocolDecoder.java   Source Code and License Vote up 4 votes
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ChannelBuffer buf = (ChannelBuffer) msg;

    buf.readUnsignedByte(); // protocol
    buf.readUnsignedShort(); // length
    int index = buf.readUnsignedByte() >> 3;

    if (channel != null) {
        ChannelBuffer response = ChannelBuffers.copiedBuffer(
                "^" + index, StandardCharsets.US_ASCII);
        channel.write(response, remoteAddress);
    }

    String id = String.valueOf(buf.readUnsignedInt());
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id);
    if (deviceSession == null) {
        return null;
    }

    List<Position> positions = new LinkedList<>();

    while (buf.readableBytes() > 2) {

        Position position = new Position();
        position.setProtocol(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        int end = buf.readerIndex() + buf.readUnsignedByte();

        position.setTime(new Date(buf.readUnsignedInt() * 1000));

        int flags = buf.readUnsignedByte();
        position.set(Position.KEY_SATELLITES, BitUtil.from(flags, 2));
        position.setValid(BitUtil.to(flags, 2) > 0);

        // Latitude
        double lat = buf.readUnsignedMedium();
        lat = lat * -180 / 16777216 + 90;
        position.setLatitude(lat);

        // Longitude
        double lon = buf.readUnsignedMedium();
        lon = lon * 360 / 16777216 - 180;
        position.setLongitude(lon);

        // Status
        flags = buf.readUnsignedByte();
        position.set(Position.KEY_IGNITION, BitUtil.check(flags, 0));
        position.set(Position.KEY_RSSI, BitUtil.between(flags, 2, 5));
        position.setCourse((BitUtil.from(flags, 5) * 45 + 180) % 360);

        // Speed
        int speed = buf.readUnsignedByte();
        if (speed < 250) {
            position.setSpeed(UnitsConverter.knotsFromKph(speed));
        }

        decodeExtraData(position, buf, end);

        positions.add(position);
    }

    return positions;
}