Example usage for java.lang Short byteValue

List of usage examples for java.lang Short byteValue

Introduction

In this page you can find the example usage for java.lang Short byteValue.

Prototype

public byte byteValue() 

Source Link

Document

Returns the value of this Short as a byte after a narrowing primitive conversion.

Usage

From source file:Main.java

public static void main(String[] args) {
    Short shortObject = new Short("10");
    byte b = shortObject.byteValue();
    System.out.println("byte:" + b);
}

From source file:Main.java

public static void main(String[] args) {
    Short sObj = new Short("10");

    byte b = sObj.byteValue();
    System.out.println(b);//from   www. j av a 2  s.c  o  m

    short s = sObj.shortValue();
    System.out.println(s);

    int i = sObj.intValue();
    System.out.println(i);

    float f = sObj.floatValue();
    System.out.println(f);

    double d = sObj.doubleValue();
    System.out.println(d);

    long l = sObj.longValue();
    System.out.println(l);
}

From source file:com.hortonworks.registries.schemaregistry.SchemaVersionStateStorable.java

public void setStateId(Short stateId) {
    this.stateId = stateId.byteValue();
}

From source file:org.apache.ode.bpel.memdao.BpelDAOConnectionImpl.java

@SuppressWarnings("unchecked")
public Collection<ProcessInstanceDAO> instanceQuery(InstanceFilter filter) {
    if (filter.getLimit() == 0) {
        return Collections.EMPTY_LIST;
    }/* w  ww .j  a  v a2 s  .com*/
    List<ProcessInstanceDAO> matched = new ArrayList<ProcessInstanceDAO>();
    // Selecting
    selectionCompleted: for (ProcessDaoImpl proc : _store.values()) {
        boolean pmatch = true;
        if (filter.getNameFilter() != null
                && !equalsOrWildcardMatch(filter.getNameFilter(), proc.getProcessId().getLocalPart()))
            pmatch = false;
        if (filter.getNamespaceFilter() != null
                && !equalsOrWildcardMatch(filter.getNamespaceFilter(), proc.getProcessId().getNamespaceURI()))
            pmatch = false;

        if (pmatch) {
            for (ProcessInstanceDAO inst : proc._instances.values()) {
                boolean match = true;

                if (filter.getStatusFilter() != null) {
                    boolean statusMatch = false;
                    for (Short status : filter.convertFilterState()) {
                        if (inst.getState() == status.byteValue())
                            statusMatch = true;
                    }
                    if (!statusMatch)
                        match = false;
                }
                if (filter.getStartedDateFilter() != null
                        && !dateMatch(filter.getStartedDateFilter(), inst.getCreateTime(), filter))
                    match = false;
                if (filter.getLastActiveDateFilter() != null
                        && !dateMatch(filter.getLastActiveDateFilter(), inst.getLastActiveTime(), filter))
                    match = false;

                //                    if (filter.getPropertyValuesFilter() != null) {
                //                        for (Map.Entry propEntry : filter.getPropertyValuesFilter().entrySet()) {
                //                            boolean entryMatched = false;
                //                            for (ProcessPropertyDAO prop : proc.getProperties()) {
                //                                if (prop.getName().equals(propEntry.getKey())
                //                                        && (propEntry.getValue().equals(prop.getMixedContent())
                //                                        || propEntry.getValue().equals(prop.getSimpleContent()))) {
                //                                    entryMatched = true;
                //                                }
                //                            }
                //                            if (!entryMatched) {
                //                                match = false;
                //                            }
                //                        }
                //                    }

                if (match) {
                    matched.add(inst);
                    if (matched.size() == filter.getLimit()) {
                        break selectionCompleted;
                    }
                }
            }
        }
    }
    // And ordering
    if (filter.getOrders() != null) {
        final List<String> orders = filter.getOrders();

        Collections.sort(matched, new Comparator<ProcessInstanceDAO>() {
            public int compare(ProcessInstanceDAO o1, ProcessInstanceDAO o2) {
                for (String orderKey : orders) {
                    int result = compareInstanceUsingKey(orderKey, o1, o2);
                    if (result != 0)
                        return result;
                }
                return 0;
            }
        });
    }

    return matched;
}

From source file:org.onosproject.routing.bgp.BgpUpdate.java

/**
 * Parse BGP Path Attributes from the BGP UPDATE message.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param message the message to parse/* w  w  w.jav a2  s.  c om*/
 * @param decodedBgpRoutes the container to store the decoded BGP Route
 * Entries. It might already contain some route entries such as withdrawn
 * IPv4 prefixes
 * @throws BgpMessage.BgpParseException
 */
// CHECKSTYLE IGNORE MethodLength FOR NEXT 300 LINES
private static void parsePathAttributes(BgpSession bgpSession, ChannelHandlerContext ctx, ChannelBuffer message,
        DecodedBgpRoutes decodedBgpRoutes) throws BgpMessage.BgpParseException {

    //
    // Parsed values
    //
    Short origin = -1; // Mandatory
    BgpRouteEntry.AsPath asPath = null; // Mandatory
    // Legacy NLRI (RFC 4271). Mandatory NEXT_HOP if legacy NLRI is used
    MpNlri legacyNlri = new MpNlri(BgpConstants.Open.Capabilities.MultiprotocolExtensions.AFI_IPV4,
            BgpConstants.Open.Capabilities.MultiprotocolExtensions.SAFI_UNICAST);
    long multiExitDisc = // Optional
            BgpConstants.Update.MultiExitDisc.LOWEST_MULTI_EXIT_DISC;
    Long localPref = null; // Mandatory
    Long aggregatorAsNumber = null; // Optional: unused
    Ip4Address aggregatorIpAddress = null; // Optional: unused
    Collection<MpNlri> mpNlriReachList = new ArrayList<>(); // Optional
    Collection<MpNlri> mpNlriUnreachList = new ArrayList<>(); // Optional

    //
    // Get and verify the Path Attributes Length
    //
    int pathAttributeLength = message.readUnsignedShort();
    if (pathAttributeLength > message.readableBytes()) {
        // ERROR: Malformed Attribute List
        actionsBgpUpdateMalformedAttributeList(bgpSession, ctx);
        String errorMsg = "Malformed Attribute List";
        throw new BgpMessage.BgpParseException(errorMsg);
    }
    if (pathAttributeLength == 0) {
        return;
    }

    //
    // Parse the Path Attributes
    //
    int pathAttributeEnd = message.readerIndex() + pathAttributeLength;
    while (message.readerIndex() < pathAttributeEnd) {
        int attrFlags = message.readUnsignedByte();
        if (message.readerIndex() >= pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(bgpSession, ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpMessage.BgpParseException(errorMsg);
        }
        int attrTypeCode = message.readUnsignedByte();

        // The Attribute Flags
        boolean optionalBit = ((0x80 & attrFlags) != 0);
        boolean transitiveBit = ((0x40 & attrFlags) != 0);
        boolean partialBit = ((0x20 & attrFlags) != 0);
        boolean extendedLengthBit = ((0x10 & attrFlags) != 0);

        // The Attribute Length
        int attrLen = 0;
        int attrLenOctets = 1;
        if (extendedLengthBit) {
            attrLenOctets = 2;
        }
        if (message.readerIndex() + attrLenOctets > pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(bgpSession, ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpMessage.BgpParseException(errorMsg);
        }
        if (extendedLengthBit) {
            attrLen = message.readUnsignedShort();
        } else {
            attrLen = message.readUnsignedByte();
        }
        if (message.readerIndex() + attrLen > pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(bgpSession, ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpMessage.BgpParseException(errorMsg);
        }

        // Verify the Attribute Flags
        verifyBgpUpdateAttributeFlags(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);

        //
        // Extract the Attribute Value based on the Attribute Type Code
        //
        switch (attrTypeCode) {

        case BgpConstants.Update.Origin.TYPE:
            // Attribute Type Code ORIGIN
            origin = parseAttributeTypeOrigin(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case BgpConstants.Update.AsPath.TYPE:
            // Attribute Type Code AS_PATH
            asPath = parseAttributeTypeAsPath(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case BgpConstants.Update.NextHop.TYPE:
            // Attribute Type Code NEXT_HOP
            legacyNlri.nextHop4 = parseAttributeTypeNextHop(bgpSession, ctx, attrTypeCode, attrLen, attrFlags,
                    message);
            break;

        case BgpConstants.Update.MultiExitDisc.TYPE:
            // Attribute Type Code MULTI_EXIT_DISC
            multiExitDisc = parseAttributeTypeMultiExitDisc(bgpSession, ctx, attrTypeCode, attrLen, attrFlags,
                    message);
            break;

        case BgpConstants.Update.LocalPref.TYPE:
            // Attribute Type Code LOCAL_PREF
            localPref = parseAttributeTypeLocalPref(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case BgpConstants.Update.AtomicAggregate.TYPE:
            // Attribute Type Code ATOMIC_AGGREGATE
            parseAttributeTypeAtomicAggregate(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
            // Nothing to do: this attribute is primarily informational
            break;

        case BgpConstants.Update.Aggregator.TYPE:
            // Attribute Type Code AGGREGATOR
            Pair<Long, Ip4Address> aggregator = parseAttributeTypeAggregator(bgpSession, ctx, attrTypeCode,
                    attrLen, attrFlags, message);
            aggregatorAsNumber = aggregator.getLeft();
            aggregatorIpAddress = aggregator.getRight();
            break;

        case BgpConstants.Update.MpReachNlri.TYPE:
            // Attribute Type Code MP_REACH_NLRI
            MpNlri mpNlriReach = parseAttributeTypeMpReachNlri(bgpSession, ctx, attrTypeCode, attrLen,
                    attrFlags, message);
            if (mpNlriReach != null) {
                mpNlriReachList.add(mpNlriReach);
            }
            break;

        case BgpConstants.Update.MpUnreachNlri.TYPE:
            // Attribute Type Code MP_UNREACH_NLRI
            MpNlri mpNlriUnreach = parseAttributeTypeMpUnreachNlri(bgpSession, ctx, attrTypeCode, attrLen,
                    attrFlags, message);
            if (mpNlriUnreach != null) {
                mpNlriUnreachList.add(mpNlriUnreach);
            }
            break;

        default:
            // NOTE: Parse any new Attribute Types if needed
            if (!optionalBit) {
                // ERROR: Unrecognized Well-known Attribute
                actionsBgpUpdateUnrecognizedWellKnownAttribute(bgpSession, ctx, attrTypeCode, attrLen,
                        attrFlags, message);
                String errorMsg = "Unrecognized Well-known Attribute: " + attrTypeCode;
                throw new BgpMessage.BgpParseException(errorMsg);
            }

            // Skip the data from the unrecognized attribute
            log.debug("BGP RX UPDATE message from {}: " + "Unrecognized Attribute Type {}",
                    bgpSession.remoteInfo().address(), attrTypeCode);
            message.skipBytes(attrLen);
            break;
        }
    }

    //
    // Parse the NLRI (Network Layer Reachability Information)
    //
    int nlriLength = message.readableBytes();
    try {
        Collection<Ip4Prefix> addedPrefixes4 = parsePackedIp4Prefixes(nlriLength, message);
        // Store it inside the legacy NLRI wrapper
        legacyNlri.nlri4 = addedPrefixes4;
    } catch (BgpMessage.BgpParseException e) {
        // ERROR: Invalid Network Field
        log.debug("Exception parsing NLRI from BGP peer {}: ", bgpSession.remoteInfo().bgpId(), e);
        actionsBgpUpdateInvalidNetworkField(bgpSession, ctx);
        // Rethrow the exception
        throw e;
    }

    // Verify the Well-known Attributes
    verifyBgpUpdateWellKnownAttributes(bgpSession, ctx, origin, asPath, localPref, legacyNlri, mpNlriReachList);

    //
    // Generate the deleted routes
    //
    for (MpNlri mpNlri : mpNlriUnreachList) {
        BgpRouteEntry bgpRouteEntry;

        // The deleted IPv4 routes
        for (Ip4Prefix prefix : mpNlri.nlri4) {
            bgpRouteEntry = bgpSession.findBgpRoute(prefix);
            if (bgpRouteEntry != null) {
                decodedBgpRoutes.deletedUnicastRoutes4.put(prefix, bgpRouteEntry);
            }
        }

        // The deleted IPv6 routes
        for (Ip6Prefix prefix : mpNlri.nlri6) {
            bgpRouteEntry = bgpSession.findBgpRoute(prefix);
            if (bgpRouteEntry != null) {
                decodedBgpRoutes.deletedUnicastRoutes6.put(prefix, bgpRouteEntry);
            }
        }
    }

    //
    // Generate the added routes
    //
    mpNlriReachList.add(legacyNlri);
    for (MpNlri mpNlri : mpNlriReachList) {
        BgpRouteEntry bgpRouteEntry;

        // The added IPv4 routes
        for (Ip4Prefix prefix : mpNlri.nlri4) {
            bgpRouteEntry = new BgpRouteEntry(bgpSession, prefix, mpNlri.nextHop4, origin.byteValue(), asPath,
                    localPref);
            bgpRouteEntry.setMultiExitDisc(multiExitDisc);
            if (bgpRouteEntry.hasAsPathLoop(bgpSession.localInfo().asNumber())) {
                log.debug("BGP RX UPDATE message IGNORED from {}: {} " + "nextHop {}: contains AS Path loop",
                        bgpSession.remoteInfo().address(), prefix, mpNlri.nextHop4);
                continue;
            } else {
                log.debug("BGP RX UPDATE message ADDED from {}: {} nextHop {}",
                        bgpSession.remoteInfo().address(), prefix, mpNlri.nextHop4);
            }
            // Remove from the collection of deleted routes
            decodedBgpRoutes.deletedUnicastRoutes4.remove(prefix);
            decodedBgpRoutes.addedUnicastRoutes4.put(prefix, bgpRouteEntry);
        }

        // The added IPv6 routes
        for (Ip6Prefix prefix : mpNlri.nlri6) {
            bgpRouteEntry = new BgpRouteEntry(bgpSession, prefix, mpNlri.nextHop6, origin.byteValue(), asPath,
                    localPref);
            bgpRouteEntry.setMultiExitDisc(multiExitDisc);
            if (bgpRouteEntry.hasAsPathLoop(bgpSession.localInfo().asNumber())) {
                log.debug("BGP RX UPDATE message IGNORED from {}: {} " + "nextHop {}: contains AS Path loop",
                        bgpSession.remoteInfo().address(), prefix, mpNlri.nextHop6);
                continue;
            } else {
                log.debug("BGP RX UPDATE message ADDED from {}: {} nextHop {}",
                        bgpSession.remoteInfo().address(), prefix, mpNlri.nextHop6);
            }
            // Remove from the collection of deleted routes
            decodedBgpRoutes.deletedUnicastRoutes6.remove(prefix);
            decodedBgpRoutes.addedUnicastRoutes6.put(prefix, bgpRouteEntry);
        }
    }
}

From source file:org.onosproject.sdnip.bgp.BgpSession.java

/**
 * Parse BGP Path Attributes from the BGP UPDATE message.
 *
 * @param ctx the Channel Handler Context
 * @param message the message to parse/*from w  ww . j  a  v a 2  s.  c om*/
 * @return a collection of the result BGP Route Entries
 * @throws BgpParseException
 */
private Collection<BgpRouteEntry> parsePathAttributes(ChannelHandlerContext ctx, ChannelBuffer message)
        throws BgpParseException {
    Map<Ip4Prefix, BgpRouteEntry> addedRoutes = new HashMap<>();

    //
    // Parsed values
    //
    Short origin = -1; // Mandatory
    BgpRouteEntry.AsPath asPath = null; // Mandatory
    Ip4Address nextHop = null; // Mandatory
    long multiExitDisc = // Optional
            BgpConstants.Update.MultiExitDisc.LOWEST_MULTI_EXIT_DISC;
    Long localPref = null; // Mandatory
    Long aggregatorAsNumber = null; // Optional: unused
    Ip4Address aggregatorIpAddress = null; // Optional: unused

    //
    // Get and verify the Path Attributes Length
    //
    int pathAttributeLength = message.readUnsignedShort();
    if (pathAttributeLength > message.readableBytes()) {
        // ERROR: Malformed Attribute List
        actionsBgpUpdateMalformedAttributeList(ctx);
        String errorMsg = "Malformed Attribute List";
        throw new BgpParseException(errorMsg);
    }
    if (pathAttributeLength == 0) {
        return addedRoutes.values();
    }

    //
    // Parse the Path Attributes
    //
    int pathAttributeEnd = message.readerIndex() + pathAttributeLength;
    while (message.readerIndex() < pathAttributeEnd) {
        int attrFlags = message.readUnsignedByte();
        if (message.readerIndex() >= pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpParseException(errorMsg);
        }
        int attrTypeCode = message.readUnsignedByte();

        // The Attribute Flags
        boolean optionalBit = ((0x80 & attrFlags) != 0);
        boolean transitiveBit = ((0x40 & attrFlags) != 0);
        boolean partialBit = ((0x20 & attrFlags) != 0);
        boolean extendedLengthBit = ((0x10 & attrFlags) != 0);

        // The Attribute Length
        int attrLen = 0;
        int attrLenOctets = 1;
        if (extendedLengthBit) {
            attrLenOctets = 2;
        }
        if (message.readerIndex() + attrLenOctets > pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpParseException(errorMsg);
        }
        if (extendedLengthBit) {
            attrLen = message.readUnsignedShort();
        } else {
            attrLen = message.readUnsignedByte();
        }
        if (message.readerIndex() + attrLen > pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpParseException(errorMsg);
        }

        //
        // Verify the Attribute Flags
        //
        verifyBgpUpdateAttributeFlags(ctx, attrTypeCode, attrLen, attrFlags, message);

        //
        // Extract the Attribute Value based on the Attribute Type Code
        //
        switch (attrTypeCode) {

        case BgpConstants.Update.Origin.TYPE:
            // Attribute Type Code ORIGIN
            origin = parseAttributeTypeOrigin(ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case BgpConstants.Update.AsPath.TYPE:
            // Attribute Type Code AS_PATH
            asPath = parseAttributeTypeAsPath(ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case BgpConstants.Update.NextHop.TYPE:
            // Attribute Type Code NEXT_HOP
            nextHop = parseAttributeTypeNextHop(ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case BgpConstants.Update.MultiExitDisc.TYPE:
            // Attribute Type Code MULTI_EXIT_DISC
            multiExitDisc = parseAttributeTypeMultiExitDisc(ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case BgpConstants.Update.LocalPref.TYPE:
            // Attribute Type Code LOCAL_PREF
            localPref = parseAttributeTypeLocalPref(ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case BgpConstants.Update.AtomicAggregate.TYPE:
            // Attribute Type Code ATOMIC_AGGREGATE
            parseAttributeTypeAtomicAggregate(ctx, attrTypeCode, attrLen, attrFlags, message);
            // Nothing to do: this attribute is primarily informational
            break;

        case BgpConstants.Update.Aggregator.TYPE:
            // Attribute Type Code AGGREGATOR
            Pair<Long, Ip4Address> aggregator = parseAttributeTypeAggregator(ctx, attrTypeCode, attrLen,
                    attrFlags, message);
            aggregatorAsNumber = aggregator.getLeft();
            aggregatorIpAddress = aggregator.getRight();
            break;

        default:
            // NOTE: Parse any new Attribute Types if needed
            if (!optionalBit) {
                // ERROR: Unrecognized Well-known Attribute
                actionsBgpUpdateUnrecognizedWellKnownAttribute(ctx, attrTypeCode, attrLen, attrFlags, message);
                String errorMsg = "Unrecognized Well-known Attribute: " + attrTypeCode;
                throw new BgpParseException(errorMsg);
            }

            // Skip the data from the unrecognized attribute
            log.debug("BGP RX UPDATE message from {}: " + "Unrecognized Attribute Type {}", remoteAddress,
                    attrTypeCode);
            message.skipBytes(attrLen);
            break;
        }
    }

    //
    // Verify the Well-known Attributes
    //
    verifyBgpUpdateWellKnownAttributes(ctx, origin, asPath, nextHop, localPref);

    //
    // Parse the NLRI (Network Layer Reachability Information)
    //
    Collection<Ip4Prefix> addedPrefixes = null;
    int nlriLength = message.readableBytes();
    try {
        addedPrefixes = parsePackedPrefixes(nlriLength, message);
    } catch (BgpParseException e) {
        // ERROR: Invalid Network Field
        log.debug("Exception parsing NLRI from BGP peer {}: ", remoteBgpId, e);
        actionsBgpUpdateInvalidNetworkField(ctx);
        // Rethrow the exception
        throw e;
    }

    // Generate the added routes
    for (Ip4Prefix prefix : addedPrefixes) {
        BgpRouteEntry bgpRouteEntry = new BgpRouteEntry(this, prefix, nextHop, origin.byteValue(), asPath,
                localPref);
        bgpRouteEntry.setMultiExitDisc(multiExitDisc);
        if (bgpRouteEntry.hasAsPathLoop(localAs)) {
            log.debug("BGP RX UPDATE message IGNORED from {}: {} " + "nextHop {}: contains AS Path loop",
                    remoteAddress, prefix, nextHop);
            continue;
        } else {
            log.debug("BGP RX UPDATE message ADDED from {}: {} nextHop {}", remoteAddress, prefix, nextHop);
        }
        addedRoutes.put(prefix, bgpRouteEntry);
    }

    return addedRoutes.values();
}

From source file:org.onosproject.sdnip.bgp.BgpUpdate.java

/**
 * Parse BGP Path Attributes from the BGP UPDATE message.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param message the message to parse/* w w  w .  j  a v  a  2s. c o m*/
 * @param decodedBgpRoutes the container to store the decoded BGP Route
 * Entries. It might already contain some route entries such as withdrawn
 * IPv4 prefixes
 * @throws BgpParseException
 */
// CHECKSTYLE IGNORE MethodLength FOR NEXT 300 LINES
private static void parsePathAttributes(BgpSession bgpSession, ChannelHandlerContext ctx, ChannelBuffer message,
        DecodedBgpRoutes decodedBgpRoutes) throws BgpParseException {

    //
    // Parsed values
    //
    Short origin = -1; // Mandatory
    BgpRouteEntry.AsPath asPath = null; // Mandatory
    // Legacy NLRI (RFC 4271). Mandatory NEXT_HOP if legacy NLRI is used
    MpNlri legacyNlri = new MpNlri(MultiprotocolExtensions.AFI_IPV4, MultiprotocolExtensions.SAFI_UNICAST);
    long multiExitDisc = // Optional
            Update.MultiExitDisc.LOWEST_MULTI_EXIT_DISC;
    Long localPref = null; // Mandatory
    Long aggregatorAsNumber = null; // Optional: unused
    Ip4Address aggregatorIpAddress = null; // Optional: unused
    Collection<MpNlri> mpNlriReachList = new ArrayList<>(); // Optional
    Collection<MpNlri> mpNlriUnreachList = new ArrayList<>(); // Optional

    //
    // Get and verify the Path Attributes Length
    //
    int pathAttributeLength = message.readUnsignedShort();
    if (pathAttributeLength > message.readableBytes()) {
        // ERROR: Malformed Attribute List
        actionsBgpUpdateMalformedAttributeList(bgpSession, ctx);
        String errorMsg = "Malformed Attribute List";
        throw new BgpParseException(errorMsg);
    }
    if (pathAttributeLength == 0) {
        return;
    }

    //
    // Parse the Path Attributes
    //
    int pathAttributeEnd = message.readerIndex() + pathAttributeLength;
    while (message.readerIndex() < pathAttributeEnd) {
        int attrFlags = message.readUnsignedByte();
        if (message.readerIndex() >= pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(bgpSession, ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpParseException(errorMsg);
        }
        int attrTypeCode = message.readUnsignedByte();

        // The Attribute Flags
        boolean optionalBit = ((0x80 & attrFlags) != 0);
        boolean transitiveBit = ((0x40 & attrFlags) != 0);
        boolean partialBit = ((0x20 & attrFlags) != 0);
        boolean extendedLengthBit = ((0x10 & attrFlags) != 0);

        // The Attribute Length
        int attrLen = 0;
        int attrLenOctets = 1;
        if (extendedLengthBit) {
            attrLenOctets = 2;
        }
        if (message.readerIndex() + attrLenOctets > pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(bgpSession, ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpParseException(errorMsg);
        }
        if (extendedLengthBit) {
            attrLen = message.readUnsignedShort();
        } else {
            attrLen = message.readUnsignedByte();
        }
        if (message.readerIndex() + attrLen > pathAttributeEnd) {
            // ERROR: Malformed Attribute List
            actionsBgpUpdateMalformedAttributeList(bgpSession, ctx);
            String errorMsg = "Malformed Attribute List";
            throw new BgpParseException(errorMsg);
        }

        // Verify the Attribute Flags
        verifyBgpUpdateAttributeFlags(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);

        //
        // Extract the Attribute Value based on the Attribute Type Code
        //
        switch (attrTypeCode) {

        case Update.Origin.TYPE:
            // Attribute Type Code ORIGIN
            origin = parseAttributeTypeOrigin(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case Update.AsPath.TYPE:
            // Attribute Type Code AS_PATH
            asPath = parseAttributeTypeAsPath(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case Update.NextHop.TYPE:
            // Attribute Type Code NEXT_HOP
            legacyNlri.nextHop4 = parseAttributeTypeNextHop(bgpSession, ctx, attrTypeCode, attrLen, attrFlags,
                    message);
            break;

        case Update.MultiExitDisc.TYPE:
            // Attribute Type Code MULTI_EXIT_DISC
            multiExitDisc = parseAttributeTypeMultiExitDisc(bgpSession, ctx, attrTypeCode, attrLen, attrFlags,
                    message);
            break;

        case Update.LocalPref.TYPE:
            // Attribute Type Code LOCAL_PREF
            localPref = parseAttributeTypeLocalPref(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
            break;

        case Update.AtomicAggregate.TYPE:
            // Attribute Type Code ATOMIC_AGGREGATE
            parseAttributeTypeAtomicAggregate(bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
            // Nothing to do: this attribute is primarily informational
            break;

        case Update.Aggregator.TYPE:
            // Attribute Type Code AGGREGATOR
            Pair<Long, Ip4Address> aggregator = parseAttributeTypeAggregator(bgpSession, ctx, attrTypeCode,
                    attrLen, attrFlags, message);
            aggregatorAsNumber = aggregator.getLeft();
            aggregatorIpAddress = aggregator.getRight();
            break;

        case Update.MpReachNlri.TYPE:
            // Attribute Type Code MP_REACH_NLRI
            MpNlri mpNlriReach = parseAttributeTypeMpReachNlri(bgpSession, ctx, attrTypeCode, attrLen,
                    attrFlags, message);
            if (mpNlriReach != null) {
                mpNlriReachList.add(mpNlriReach);
            }
            break;

        case Update.MpUnreachNlri.TYPE:
            // Attribute Type Code MP_UNREACH_NLRI
            MpNlri mpNlriUnreach = parseAttributeTypeMpUnreachNlri(bgpSession, ctx, attrTypeCode, attrLen,
                    attrFlags, message);
            if (mpNlriUnreach != null) {
                mpNlriUnreachList.add(mpNlriUnreach);
            }
            break;

        default:
            // NOTE: Parse any new Attribute Types if needed
            if (!optionalBit) {
                // ERROR: Unrecognized Well-known Attribute
                actionsBgpUpdateUnrecognizedWellKnownAttribute(bgpSession, ctx, attrTypeCode, attrLen,
                        attrFlags, message);
                String errorMsg = "Unrecognized Well-known Attribute: " + attrTypeCode;
                throw new BgpParseException(errorMsg);
            }

            // Skip the data from the unrecognized attribute
            log.debug("BGP RX UPDATE message from {}: " + "Unrecognized Attribute Type {}",
                    bgpSession.remoteInfo().address(), attrTypeCode);
            message.skipBytes(attrLen);
            break;
        }
    }

    //
    // Parse the NLRI (Network Layer Reachability Information)
    //
    int nlriLength = message.readableBytes();
    try {
        Collection<Ip4Prefix> addedPrefixes4 = parsePackedIp4Prefixes(nlriLength, message);
        // Store it inside the legacy NLRI wrapper
        legacyNlri.nlri4 = addedPrefixes4;
    } catch (BgpParseException e) {
        // ERROR: Invalid Network Field
        log.debug("Exception parsing NLRI from BGP peer {}: ", bgpSession.remoteInfo().bgpId(), e);
        actionsBgpUpdateInvalidNetworkField(bgpSession, ctx);
        // Rethrow the exception
        throw e;
    }

    // Verify the Well-known Attributes
    verifyBgpUpdateWellKnownAttributes(bgpSession, ctx, origin, asPath, localPref, legacyNlri, mpNlriReachList);

    //
    // Generate the deleted routes
    //
    for (MpNlri mpNlri : mpNlriUnreachList) {
        BgpRouteEntry bgpRouteEntry;

        // The deleted IPv4 routes
        for (Ip4Prefix prefix : mpNlri.nlri4) {
            bgpRouteEntry = bgpSession.findBgpRoute(prefix);
            if (bgpRouteEntry != null) {
                decodedBgpRoutes.deletedUnicastRoutes4.put(prefix, bgpRouteEntry);
            }
        }

        // The deleted IPv6 routes
        for (Ip6Prefix prefix : mpNlri.nlri6) {
            bgpRouteEntry = bgpSession.findBgpRoute(prefix);
            if (bgpRouteEntry != null) {
                decodedBgpRoutes.deletedUnicastRoutes6.put(prefix, bgpRouteEntry);
            }
        }
    }

    //
    // Generate the added routes
    //
    mpNlriReachList.add(legacyNlri);
    for (MpNlri mpNlri : mpNlriReachList) {
        BgpRouteEntry bgpRouteEntry;

        // The added IPv4 routes
        for (Ip4Prefix prefix : mpNlri.nlri4) {
            bgpRouteEntry = new BgpRouteEntry(bgpSession, prefix, mpNlri.nextHop4, origin.byteValue(), asPath,
                    localPref);
            bgpRouteEntry.setMultiExitDisc(multiExitDisc);
            if (bgpRouteEntry.hasAsPathLoop(bgpSession.localInfo().asNumber())) {
                log.debug("BGP RX UPDATE message IGNORED from {}: {} " + "nextHop {}: contains AS Path loop",
                        bgpSession.remoteInfo().address(), prefix, mpNlri.nextHop4);
                continue;
            } else {
                log.debug("BGP RX UPDATE message ADDED from {}: {} nextHop {}",
                        bgpSession.remoteInfo().address(), prefix, mpNlri.nextHop4);
            }
            // Remove from the collection of deleted routes
            decodedBgpRoutes.deletedUnicastRoutes4.remove(prefix);
            decodedBgpRoutes.addedUnicastRoutes4.put(prefix, bgpRouteEntry);
        }

        // The added IPv6 routes
        for (Ip6Prefix prefix : mpNlri.nlri6) {
            bgpRouteEntry = new BgpRouteEntry(bgpSession, prefix, mpNlri.nextHop6, origin.byteValue(), asPath,
                    localPref);
            bgpRouteEntry.setMultiExitDisc(multiExitDisc);
            if (bgpRouteEntry.hasAsPathLoop(bgpSession.localInfo().asNumber())) {
                log.debug("BGP RX UPDATE message IGNORED from {}: {} " + "nextHop {}: contains AS Path loop",
                        bgpSession.remoteInfo().address(), prefix, mpNlri.nextHop6);
                continue;
            } else {
                log.debug("BGP RX UPDATE message ADDED from {}: {} nextHop {}",
                        bgpSession.remoteInfo().address(), prefix, mpNlri.nextHop6);
            }
            // Remove from the collection of deleted routes
            decodedBgpRoutes.deletedUnicastRoutes6.remove(prefix);
            decodedBgpRoutes.addedUnicastRoutes6.put(prefix, bgpRouteEntry);
        }
    }
}

From source file:org.opendaylight.netvirt.dhcpservice.DhcpPktHandler.java

protected byte[] convertToClasslessRouteOption(String dest, String router) {
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    if (dest == null || router == null) {
        return null;
    }/*w w w.  j  a  va2 s .  c o  m*/

    //get prefix
    Short prefix = null;
    String[] parts = dest.split("/");
    if (parts.length < 2) {
        prefix = (short) 0;
    } else {
        prefix = Short.valueOf(parts[1]);
    }

    byteArray.write(prefix.byteValue());
    SubnetUtils util = new SubnetUtils(dest);
    SubnetInfo info = util.getInfo();
    String strNetAddr = info.getNetworkAddress();
    try {
        byte[] netAddr = InetAddress.getByName(strNetAddr).getAddress();
        //Strip any trailing 0s from netAddr
        for (int i = 0; i < netAddr.length; i++) {
            if (netAddr[i] != 0) {
                byteArray.write(netAddr, i, 1);
            }
        }
        byteArray.write(InetAddress.getByName(router).getAddress());
    } catch (IOException e) {
        return null;
    }
    return byteArray.toByteArray();
}

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpPktHandler.java

protected byte[] convertToClasslessRouteOption(String dest, String router) {
    ByteArrayOutputStream bArr = new ByteArrayOutputStream();
    if ((dest == null || router == null)) {
        return null;
    }/* w w  w  .  j ava 2  s  .  c om*/

    //get prefix
    Short prefix = null;
    String[] parts = dest.split("/");
    if (parts.length < 2) {
        prefix = new Short((short) 0);
    } else {
        prefix = Short.valueOf(parts[1]);
    }

    bArr.write(prefix.byteValue());
    SubnetUtils util = new SubnetUtils(dest);
    SubnetInfo info = util.getInfo();
    String strNetAddr = info.getNetworkAddress();
    try {
        byte[] netAddr = InetAddress.getByName(strNetAddr).getAddress();
        //Strip any trailing 0s from netAddr
        for (int i = 0; i < netAddr.length; i++) {
            if (netAddr[i] != 0) {
                bArr.write(netAddr, i, 1);
            }
        }
        bArr.write(InetAddress.getByName(router).getAddress());
    } catch (IOException e) {
        return null;
    }
    return bArr.toByteArray();
}