byteAggregator.writeBytes(Ipv4Util.bytesForAddress(((Ipv4NextHopCase) cnextHop).getIpv4NextHop().getGlobal()));
} else if (cnextHop instanceof Ipv6NextHopCase) {
final Ipv6NextHop nextHop = ((Ipv6NextHopCase) cnextHop).getIpv6NextHop();
- if (nextHop.getGlobal() != null) {
- byteAggregator.writeBytes(Ipv6Util.bytesForAddress(nextHop.getGlobal()));
+ if (nextHop.getGlobal() == null) {
+ throw new IllegalArgumentException("Ipv6 Next Hop is missing Global address.");
}
+ byteAggregator.writeBytes(Ipv6Util.bytesForAddress(nextHop.getGlobal()));
if (nextHop.getLinkLocal() != null) {
byteAggregator.writeBytes(Ipv6Util.bytesForAddress(nextHop.getLinkLocal()));
}
*/
package org.opendaylight.bgp.concepts;
+import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
+import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Test;
+import org.opendaylight.protocol.util.ByteArray;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.CNextHop;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.Ipv4NextHopCase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.Ipv4NextHopCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.Ipv6NextHopCase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.Ipv6NextHopCaseBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.ipv4.next.hop._case.Ipv4NextHopBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.ipv6.next.hop._case.Ipv6NextHopBuilder;
public class NextHopUtilTest {
+ private static final byte[] ipv4B = { 42, 42, 42, 42 };
+ private static final byte[] ipv6B = { 0x20, 1, 0x0d, (byte) 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+ private static final byte[] ipv6lB = { 0x20, 1, 0x0d, (byte) 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, (byte) 0xfe, (byte) 0x80, 0, 0, 0, 0, 0, 0, (byte) 0xc0, 1, 0x0b, (byte) 0xff, (byte) 0xfe, 0x7e, 0, 0 };
+
+ private static final Ipv4Address ipv4 = new Ipv4Address("42.42.42.42");
+ private static final Ipv6Address ipv6 = new Ipv6Address("2001:db8::1");
+ private static final Ipv6Address ipv6l = new Ipv6Address("fe80::c001:bff:fe7e:0");
+
+ @Test
+ public void testSerializeNextHop() {
+ CNextHop hop = new Ipv4NextHopCaseBuilder().setIpv4NextHop(new Ipv4NextHopBuilder().setGlobal(ipv4).build()).build();
+ final ByteBuf buffer = Unpooled.buffer();
+ NextHopUtil.serializeNextHop(hop, buffer);
+ assertArrayEquals(ipv4B, ByteArray.readAllBytes(buffer));
+
+ hop = new Ipv6NextHopCaseBuilder().setIpv6NextHop(new Ipv6NextHopBuilder().setGlobal(ipv6).build()).build();
+ buffer.clear();
+ NextHopUtil.serializeNextHop(hop, buffer);
+ assertArrayEquals(ipv6B, ByteArray.readAllBytes(buffer));
+
+ hop = new Ipv6NextHopCaseBuilder().setIpv6NextHop(new Ipv6NextHopBuilder().setGlobal(ipv6).setLinkLocal(ipv6l).build()).build();
+ buffer.clear();
+ NextHopUtil.serializeNextHop(hop, buffer);
+ assertArrayEquals(ipv6lB, ByteArray.readAllBytes(buffer));
+
+ hop = new Ipv6NextHopCaseBuilder().setIpv6NextHop(new Ipv6NextHopBuilder().setLinkLocal(ipv6l).build()).build();
+ buffer.clear();
+ try {
+ NextHopUtil.serializeNextHop(hop, buffer);
+ fail("Exception should happen");
+ } catch (final IllegalArgumentException e) {
+ assertEquals("Ipv6 Next Hop is missing Global address.", e.getMessage());
+ }
+ }
+
@Test
- public void testNlriUtil() {
+ public void testParseNextHop() {
CNextHop hop = null;
- final byte[] ipv4 = new byte[] { 42, 42, 42, 42 };
try {
- hop = NextHopUtil.parseNextHop(Unpooled.wrappedBuffer(ipv4));
+ hop = NextHopUtil.parseNextHop(Unpooled.wrappedBuffer(ipv4B));
} catch (final IllegalArgumentException e) {
fail("This exception should not happen");
}
- assertEquals("42.42.42.42", ((Ipv4NextHopCase) hop).getIpv4NextHop().getGlobal().getValue());
+ assertEquals(ipv4, ((Ipv4NextHopCase) hop).getIpv4NextHop().getGlobal());
- final byte[] ipv6 = new byte[] { (byte) 0x20, (byte) 0x01, (byte) 0x0d, (byte) 0xb8, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01 };
try {
- hop = NextHopUtil.parseNextHop(Unpooled.wrappedBuffer(ipv6));
+ hop = NextHopUtil.parseNextHop(Unpooled.wrappedBuffer(ipv6B));
} catch (final IllegalArgumentException e) {
fail("This exception should not happen");
}
- assertEquals("2001:db8::1", ((Ipv6NextHopCase) hop).getIpv6NextHop().getGlobal().getValue());
+ assertEquals(ipv6, ((Ipv6NextHopCase) hop).getIpv6NextHop().getGlobal());
assertNull(((Ipv6NextHopCase) hop).getIpv6NextHop().getLinkLocal());
- final byte[] ipv6l = new byte[] { (byte) 0x20, (byte) 0x01, (byte) 0x0d, (byte) 0xb8, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00,
- 01, (byte) 0xfe, (byte) 0x80, 00, 00, 00, 00, 00, 00, (byte) 0xc0, 01, 0x0b, (byte) 0xff, (byte) 0xfe, 0x7e, 00, 00 };
try {
- hop = NextHopUtil.parseNextHop(Unpooled.wrappedBuffer(ipv6l));
+ hop = NextHopUtil.parseNextHop(Unpooled.wrappedBuffer(ipv6lB));
} catch (final IllegalArgumentException e) {
fail("This exception should not happen");
}
- assertEquals("2001:db8::1", ((Ipv6NextHopCase) hop).getIpv6NextHop().getGlobal().getValue());
- assertEquals("fe80::c001:bff:fe7e:0", ((Ipv6NextHopCase) hop).getIpv6NextHop().getLinkLocal().getValue());
+ assertEquals(ipv6, ((Ipv6NextHopCase) hop).getIpv6NextHop().getGlobal());
+ assertEquals(ipv6l, ((Ipv6NextHopCase) hop).getIpv6NextHop().getLinkLocal());
final byte[] wrong = new byte[] { (byte) 0x20, (byte) 0x01, (byte) 0x0d };
try {
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.base.Preconditions;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+
import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
import org.opendaylight.protocol.bgp.rib.RibReference;
import org.opendaylight.protocol.bgp.rib.spi.AbstractAdjRIBsIn;
import org.opendaylight.protocol.bgp.rib.spi.Peer;
+import org.opendaylight.protocol.util.ByteArray;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.LinkstateDestination;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.bgp.rib.rib.loc.rib.tables.routes.linkstate.routes._case.LinkstateRoutes;
final class LinkstateAdjRIBsIn extends AbstractAdjRIBsIn<CLinkstateDestination, LinkstateRoute> {
- private abstract static class LinkstateRIBEntryData<A extends LinkStateAttribute> extends
- RIBEntryData<CLinkstateDestination, LinkstateRoute> {
+ private abstract static class LinkstateRIBEntryData<A extends LinkStateAttribute> extends RIBEntryData<CLinkstateDestination, LinkstateRoute> {
private final A lsattr;
protected LinkstateRIBEntryData(final PathAttributes attributes, final A lsattr) {
@Override
public InstanceIdentifier<LinkstateRoute> identifierForKey(final InstanceIdentifier<Tables> basePath, final CLinkstateDestination key) {
+ final ByteBuf keyBuf = Unpooled.buffer();
+ LinkstateNlriParser.serializeNlri(key, keyBuf);
return basePath.builder().child(LinkstateRoutes.class).child(LinkstateRoute.class,
- new LinkstateRouteKey(LinkstateNlriParser.serializeNlri(key))).toInstance();
+ new LinkstateRouteKey(ByteArray.readAllBytes(keyBuf))).toInstance();
}
@Override
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.net.InetAddresses;
-import com.google.common.primitives.UnsignedBytes;
-
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
-
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.Map.Entry;
-
import org.opendaylight.protocol.bgp.parser.BGPParsingException;
import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
private static final int EXTENDED_ROUTE_TAG_LENGTH = 8;
- private static final int SRLG_LENGTH = 4;
-
private static final int UNRESERVED_BW_COUNT = 8;
private static final int BANDWIDTH_LENGTH = 4;
private static final int LDP_BIT = 7;
private static final int RSVP_BIT = 6;
+ private static final int UP_DOWN_BIT = 7;
+
private NlriType getNlriType(final PathAttributesBuilder pab) {
final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes1 mpr = pab.getAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes1.class);
if (mpr != null && mpr.getMpReachNlri() != null) {
/*
* e.g. IS-IS Area Identifier TLV can occur multiple times
*/
- final Multimap<Integer, byte[]> map = HashMultimap.create();
+ final Multimap<Integer, ByteBuf> map = HashMultimap.create();
while (buffer.isReadable()) {
final int type = buffer.readUnsignedShort();
final int length = buffer.readUnsignedShort();
- final byte[] value = ByteArray.readBytes(buffer, length);
+ final ByteBuf value = buffer.slice(buffer.readerIndex(), length);
map.put(type, value);
+ buffer.skipBytes(length);
}
final LinkstatePathAttributeBuilder builder = new LinkstatePathAttributeBuilder();
* @param attributes key is the tlv type and value is the value of the tlv
* @return {@link LinkStateAttribute}
*/
- private static LinkStateAttribute parseLinkAttributes(final Multimap<Integer, byte[]> attributes) {
+ private static LinkStateAttribute parseLinkAttributes(final Multimap<Integer, ByteBuf> attributes) {
final LinkAttributesBuilder builder = new LinkAttributesBuilder();
- for (final Entry<Integer, byte[]> entry : attributes.entries()) {
+ for (final Entry<Integer, ByteBuf> entry : attributes.entries()) {
LOG.trace("Link attribute TLV {}", entry.getKey());
final int key = entry.getKey();
- final byte[] value = entry.getValue();
+ final ByteBuf value = entry.getValue();
switch (key) {
case TlvCode.LOCAL_IPV4_ROUTER_ID:
- final Ipv4RouterIdentifier lipv4 = new Ipv4RouterIdentifier(Ipv4Util.addressForBytes(value));
+ final Ipv4RouterIdentifier lipv4 = new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value));
builder.setLocalIpv4RouterId(lipv4);
LOG.debug("Parsed IPv4 Router-ID of local node: {}", lipv4);
break;
case TlvCode.LOCAL_IPV6_ROUTER_ID:
- final Ipv6RouterIdentifier lipv6 = new Ipv6RouterIdentifier(Ipv6Util.addressForBytes(value));
+ final Ipv6RouterIdentifier lipv6 = new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value));
builder.setLocalIpv6RouterId(lipv6);
LOG.debug("Parsed IPv6 Router-ID of local node: {}", lipv6);
break;
case TlvCode.REMOTE_IPV4_ROUTER_ID:
- final Ipv4RouterIdentifier ripv4 = new Ipv4RouterIdentifier(Ipv4Util.addressForBytes(value));
+ final Ipv4RouterIdentifier ripv4 = new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value));
builder.setRemoteIpv4RouterId(ripv4);
LOG.debug("Parsed IPv4 Router-ID of remote node: {}", ripv4);
break;
case TlvCode.REMOTE_IPV6_ROUTER_ID:
- final Ipv6RouterIdentifier ripv6 = new Ipv6RouterIdentifier(Ipv6Util.addressForBytes(value));
+ final Ipv6RouterIdentifier ripv6 = new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value));
builder.setRemoteIpv6RouterId(ripv6);
LOG.debug("Parsed IPv6 Router-ID of remote node: {}", ripv6);
break;
case TlvCode.ADMIN_GROUP:
- builder.setAdminGroup(new AdministrativeGroup(ByteArray.bytesToLong(value)));
+ builder.setAdminGroup(new AdministrativeGroup(value.readUnsignedInt()));
LOG.debug("Parsed Administrative Group {}", builder.getAdminGroup());
break;
case TlvCode.MAX_BANDWIDTH:
- builder.setMaxLinkBandwidth(new Bandwidth(value));
+ builder.setMaxLinkBandwidth(new Bandwidth(ByteArray.readAllBytes(value)));
LOG.debug("Parsed Max Bandwidth {}", builder.getMaxLinkBandwidth());
break;
case TlvCode.MAX_RESERVABLE_BANDWIDTH:
- builder.setMaxReservableBandwidth(new Bandwidth(value));
+ builder.setMaxReservableBandwidth(new Bandwidth(ByteArray.readAllBytes(value)));
LOG.debug("Parsed Max Reservable Bandwidth {}", builder.getMaxReservableBandwidth());
break;
case TlvCode.UNRESERVED_BANDWIDTH:
- int index = 0;
- final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.link.state.UnreservedBandwidth> unreservedBandwidth = Lists.newArrayList();
+ final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.link.state.UnreservedBandwidth> unreservedBandwidth = new ArrayList<>(UNRESERVED_BW_COUNT);
for (int i = 0; i < UNRESERVED_BW_COUNT; i++) {
- final byte[] v = ByteArray.subByte(value, index, BANDWIDTH_LENGTH);
- unreservedBandwidth.add(new UnreservedBandwidthBuilder().setBandwidth(new Bandwidth(v)).setPriority((short) i).build());
- index += BANDWIDTH_LENGTH;
+ final ByteBuf v = value.slice(value.readerIndex(), BANDWIDTH_LENGTH);
+ unreservedBandwidth.add(new UnreservedBandwidthBuilder().setBandwidth(new Bandwidth(ByteArray.readAllBytes(v))).setPriority((short) i).build());
+ value.skipBytes(BANDWIDTH_LENGTH);
}
builder.setUnreservedBandwidth(unreservedBandwidth);
LOG.debug("Parsed Unreserved Bandwidth {}", builder.getUnreservedBandwidth());
break;
case TlvCode.TE_METRIC:
- builder.setTeMetric(new TeMetric(ByteArray.bytesToLong(value)));
+ builder.setTeMetric(new TeMetric(ByteArray.bytesToLong(ByteArray.readAllBytes(value))));
LOG.debug("Parsed Metric {}", builder.getTeMetric());
break;
case TlvCode.LINK_PROTECTION_TYPE:
- final LinkProtectionType lpt = LinkProtectionType.forValue(UnsignedBytes.toInt(value[1]));
+ final int l = value.readShort();
+ final LinkProtectionType lpt = LinkProtectionType.forValue(l);
if (lpt == null) {
- LOG.warn("Link Protection Type not recognized: {}", UnsignedBytes.toInt(value[1]));
+ LOG.warn("Link Protection Type not recognized: {}", l);
break;
}
builder.setLinkProtection(lpt);
LOG.debug("Parsed Link Protection Type {}", lpt);
break;
case TlvCode.MPLS_PROTOCOL:
- final boolean[] bits = ByteArray.parseBits(value[0]);
- builder.setMplsProtocol(new MplsProtocolMask(bits[0], bits[1]));
+ final BitSet bits = BitSet.valueOf(ByteArray.readAllBytes(value));
+ builder.setMplsProtocol(new MplsProtocolMask(bits.get(LDP_BIT), bits.get(RSVP_BIT)));
LOG.debug("Parsed MPLS Protocols: {}", builder.getMplsProtocol());
break;
case TlvCode.METRIC:
- builder.setMetric(new Metric(ByteArray.bytesToLong(value)));
+ // length can 3, 2 or 1
+ builder.setMetric(new Metric(ByteArray.bytesToLong(ByteArray.readAllBytes(value))));
LOG.debug("Parsed Metric {}", builder.getMetric());
break;
case TlvCode.SHARED_RISK_LINK_GROUP:
- int i = 0;
- final List<SrlgId> sharedRiskLinkGroups = Lists.newArrayList();
- while (i != value.length) {
- sharedRiskLinkGroups.add(new SrlgId(ByteArray.bytesToLong(ByteArray.subByte(value, i, SRLG_LENGTH))));
- i += SRLG_LENGTH;
+ final List<SrlgId> sharedRiskLinkGroups = new ArrayList<>();
+ while (value.isReadable()) {
+ sharedRiskLinkGroups.add(new SrlgId(value.readUnsignedInt()));
}
builder.setSharedRiskLinkGroups(sharedRiskLinkGroups);
LOG.debug("Parsed Shared Risk Link Groups {}", Arrays.toString(sharedRiskLinkGroups.toArray()));
break;
case TlvCode.LINK_OPAQUE:
- final byte[] opaque = value;
- LOG.debug("Parsed Opaque value : {}", Arrays.toString(opaque));
+ LOG.debug("Parsed Opaque value : {}", ByteBufUtil.hexDump(value));
break;
case TlvCode.LINK_NAME:
- final String name = new String(value, Charsets.US_ASCII);
+ final String name = new String(ByteArray.readAllBytes(value), Charsets.US_ASCII);
builder.setLinkName(name);
LOG.debug("Parsed Link Name : {}", name);
break;
* @param attributes key is the tlv type and value is the value of the tlv
* @return {@link LinkStateAttribute}
*/
- private static LinkStateAttribute parseNodeAttributes(final Multimap<Integer, byte[]> attributes) {
+ private static LinkStateAttribute parseNodeAttributes(final Multimap<Integer, ByteBuf> attributes) {
final List<TopologyIdentifier> topologyMembership = Lists.newArrayList();
final List<IsisAreaIdentifier> areaMembership = Lists.newArrayList();
final NodeAttributesBuilder builder = new NodeAttributesBuilder();
- for (final Entry<Integer, byte[]> entry : attributes.entries()) {
+ for (final Entry<Integer, ByteBuf> entry : attributes.entries()) {
final int key = entry.getKey();
- final byte[] value = entry.getValue();
+ final ByteBuf value = entry.getValue();
LOG.trace("Node attribute TLV {}", key);
switch (key) {
case TlvCode.MULTI_TOPOLOGY_ID:
- int i = 0;
- while (i != value.length) {
- final TopologyIdentifier topId = new TopologyIdentifier(ByteArray.bytesToInt(ByteArray.subByte(value, i, 2)) & 0x3fff);
+ while (value.isReadable()) {
+ final TopologyIdentifier topId = new TopologyIdentifier(value.readUnsignedShort() & LinkstateNlriParser.TOPOLOGY_ID_OFFSET);
topologyMembership.add(topId);
LOG.debug("Parsed Topology Identifier: {}", topId);
- i += 2;
}
break;
case TlvCode.NODE_FLAG_BITS:
- final boolean[] flags = ByteArray.parseBits(value[0]);
- builder.setNodeFlags(new NodeFlagBits(flags[0], flags[1], flags[2], flags[3]));
- LOG.debug("Parsed Overload bit: {}, attached bit: {}, external bit: {}, area border router: {}.", flags[0], flags[1],
- flags[2], flags[3]);
+ final BitSet flags = BitSet.valueOf(ByteArray.readAllBytes(value));
+ builder.setNodeFlags(new NodeFlagBits(flags.get(OVERLOAD_BIT), flags.get(ATTACHED_BIT), flags.get(EXTERNAL_BIT), flags.get(ABBR_BIT)));
+ LOG.debug("Parsed Overload bit: {}, attached bit: {}, external bit: {}, area border router: {}.",
+ flags.get(OVERLOAD_BIT), flags.get(ATTACHED_BIT), flags.get(EXTERNAL_BIT), flags.get(ABBR_BIT));
break;
case TlvCode.NODE_OPAQUE:
- LOG.debug("Ignoring opaque value: {}.", Arrays.toString(value));
+ LOG.debug("Ignoring opaque value: {}.", ByteBufUtil.hexDump(value));
break;
case TlvCode.DYNAMIC_HOSTNAME:
- builder.setDynamicHostname(new String(value, Charsets.US_ASCII));
+ builder.setDynamicHostname(new String(ByteArray.readAllBytes(value), Charsets.US_ASCII));
LOG.debug("Parsed Node Name {}", builder.getDynamicHostname());
break;
case TlvCode.ISIS_AREA_IDENTIFIER:
- final IsisAreaIdentifier ai = new IsisAreaIdentifier(value);
+ final IsisAreaIdentifier ai = new IsisAreaIdentifier(ByteArray.readAllBytes(value));
areaMembership.add(ai);
LOG.debug("Parsed AreaIdentifier {}", ai);
break;
case TlvCode.LOCAL_IPV4_ROUTER_ID:
- final Ipv4RouterIdentifier ip4 = new Ipv4RouterIdentifier(Ipv4Util.addressForBytes(value));
+ final Ipv4RouterIdentifier ip4 = new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value));
builder.setIpv4RouterId(ip4);
LOG.debug("Parsed IPv4 Router Identifier {}", ip4);
break;
case TlvCode.LOCAL_IPV6_ROUTER_ID:
- final Ipv6RouterIdentifier ip6 = new Ipv6RouterIdentifier(Ipv6Util.addressForBytes(value));
+ final Ipv6RouterIdentifier ip6 = new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value));
builder.setIpv6RouterId(ip6);
LOG.debug("Parsed IPv6 Router Identifier {}", ip6);
break;
* @param attributes key is the tlv type and value are the value bytes of the tlv
* @return {@link LinkStateAttribute}
*/
- private static LinkStateAttribute parsePrefixAttributes(final Multimap<Integer, byte[]> attributes) {
+ private static LinkStateAttribute parsePrefixAttributes(final Multimap<Integer, ByteBuf> attributes) {
final PrefixAttributesBuilder builder = new PrefixAttributesBuilder();
final List<RouteTag> routeTags = Lists.newArrayList();
final List<ExtendedRouteTag> exRouteTags = Lists.newArrayList();
- for (final Entry<Integer, byte[]> entry : attributes.entries()) {
+ for (final Entry<Integer, ByteBuf> entry : attributes.entries()) {
final int key = entry.getKey();
- final byte[] value = entry.getValue();
+ final ByteBuf value = entry.getValue();
LOG.trace("Prefix attribute TLV {}", key);
switch (key) {
case TlvCode.IGP_FLAGS:
- final boolean[] flags = ByteArray.parseBits(value[0]);
- final boolean upDownBit = flags[0];
+ final BitSet flags = BitSet.valueOf(ByteArray.readAllBytes(value));
+ final boolean upDownBit = flags.get(UP_DOWN_BIT);
builder.setIgpBits(new IgpBitsBuilder().setUpDown(new UpDown(upDownBit)).build());
LOG.debug("Parsed IGP flag (up/down bit) : {}", upDownBit);
break;
case TlvCode.ROUTE_TAG:
- int offset = 0;
- while (offset != value.length) {
- final RouteTag routeTag = new RouteTag(ByteArray.subByte(value, offset, ROUTE_TAG_LENGTH));
+ while (value.isReadable()) {
+ final RouteTag routeTag = new RouteTag(ByteArray.readBytes(value, ROUTE_TAG_LENGTH));
routeTags.add(routeTag);
LOG.debug("Parsed Route Tag: {}", routeTag);
- offset += ROUTE_TAG_LENGTH;
}
break;
case TlvCode.EXTENDED_ROUTE_TAG:
- offset = 0;
- while (offset != value.length) {
- final ExtendedRouteTag exRouteTag = new ExtendedRouteTag(ByteArray.subByte(value, offset, EXTENDED_ROUTE_TAG_LENGTH));
+ while (value.isReadable()) {
+ final ExtendedRouteTag exRouteTag = new ExtendedRouteTag(ByteArray.readBytes(value, EXTENDED_ROUTE_TAG_LENGTH));
exRouteTags.add(exRouteTag);
LOG.debug("Parsed Extended Route Tag: {}", exRouteTag);
- offset += EXTENDED_ROUTE_TAG_LENGTH;
}
break;
case TlvCode.PREFIX_METRIC:
- final IgpMetric metric = new IgpMetric(ByteArray.bytesToLong(value));
+ final IgpMetric metric = new IgpMetric(value.readUnsignedInt());
builder.setPrefixMetric(metric);
LOG.debug("Parsed Metric: {}", metric);
break;
case TlvCode.FORWARDING_ADDRESS:
IpAddress fwdAddress = null;
- switch (value.length) {
+ switch (value.readableBytes()) {
case Ipv4Util.IP4_LENGTH:
- fwdAddress = new IpAddress(Ipv4Util.addressForBytes(value));
+ fwdAddress = new IpAddress(Ipv4Util.addressForByteBuf(value));
break;
case Ipv6Util.IPV6_LENGTH:
- fwdAddress = new IpAddress(Ipv6Util.addressForBytes(value));
+ fwdAddress = new IpAddress(Ipv6Util.addressForByteBuf(value));
break;
default:
- LOG.debug("Ignoring unsupported forwarding address length {}", value.length);
+ LOG.debug("Ignoring unsupported forwarding address length {}", value.readableBytes());
}
builder.setOspfForwardingAddress(fwdAddress);
LOG.debug("Parsed FWD Address: {}", fwdAddress);
break;
case TlvCode.PREFIX_OPAQUE:
- LOG.debug("Parsed Opaque value: {}, not preserving it", ByteArray.bytesToHexString(value));
+ LOG.debug("Parsed Opaque value: {}, not preserving it", ByteBufUtil.hexDump(value));
break;
default:
LOG.warn("TLV {} is not a valid prefix attribute, ignoring it", key);
BitSet igpBit = new BitSet();
Boolean bit = prefixAtrributes.getIgpBits().getUpDown().isUpDown();
if (bit != null) {
- igpBit.set(7, bit);
+ igpBit.set(UP_DOWN_BIT, bit);
}
writeTLV(TlvCode.IGP_FLAGS, Unpooled.wrappedBuffer(igpBit.toByteArray()), byteAggregator);
}
* @param value TLV value
* @param byteAggregator final ByteBuf where the tlv should be serialized
*/
- private static void writeTLV(final int type, final ByteBuf value, final ByteBuf byteAggregator){
+ protected static void writeTLV(final int type, final ByteBuf value, final ByteBuf byteAggregator){
byteAggregator.writeShort(type);
byteAggregator.writeShort(value.writerIndex());
byteAggregator.writeBytes(value);
import com.google.common.primitives.UnsignedInteger;
import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import java.math.BigInteger;
-import java.util.Arrays;
import java.util.List;
import org.opendaylight.protocol.bgp.parser.BGPParsingException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.PathAttributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes2;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpReachNlri;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpReachNlriBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpUnreachNlri;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpUnreachNlriBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.reach.nlri.AdvertizedRoutes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.concepts.rev131125.IsoSystemIdentifier;
private static final int ROUTE_DISTINGUISHER_LENGTH = 8;
private static final int PROTOCOL_ID_LENGTH = 1;
private static final int IDENTIFIER_LENGTH = 8;
- private static final int LINK_IDENTIFIER_LENGTH = 4;
+ private static final int OSPF_ROUTER_ID_LENGTH = 4;
private static final int ISO_SYSTEM_ID_LENGTH = 6;
private static final int PSN_LENGTH = 1;
private static final int TYPE_LENGTH = 2;
private static final int LENGTH_SIZE = 2;
+ protected static final int TOPOLOGY_ID_OFFSET = 0x3fff;
+
private final boolean isVpn;
public LinkstateNlriParser(final boolean isVpn) {
while (buffer.isReadable()) {
final int type = buffer.readUnsignedShort();
final int length = buffer.readUnsignedShort();
- final byte[] value = ByteArray.readBytes(buffer, length);
- LOG.trace("Parsing Link Descriptor: {}", Arrays.toString(value));
+ final ByteBuf value = buffer.slice(buffer.readerIndex(), length);
+ LOG.trace("Parsing Link Descriptor: {}", ByteBufUtil.hexDump(value));
switch (type) {
case TlvCode.LINK_LR_IDENTIFIERS:
- builder.setLinkLocalIdentifier(ByteArray.bytesToUint32(ByteArray.subByte(value, 0, LINK_IDENTIFIER_LENGTH)).longValue());
- builder.setLinkRemoteIdentifier(ByteArray.bytesToUint32(
- ByteArray.subByte(value, LINK_IDENTIFIER_LENGTH, LINK_IDENTIFIER_LENGTH)).longValue());
+ builder.setLinkLocalIdentifier(value.readUnsignedInt());
+ builder.setLinkRemoteIdentifier(value.readUnsignedInt());
LOG.debug("Parsed link local {} remote {} Identifiers.", builder.getLinkLocalIdentifier(),
builder.getLinkRemoteIdentifier());
break;
case TlvCode.IPV4_IFACE_ADDRESS:
- final Ipv4InterfaceIdentifier lipv4 = new Ipv4InterfaceIdentifier(Ipv4Util.addressForBytes(value));
+ final Ipv4InterfaceIdentifier lipv4 = new Ipv4InterfaceIdentifier(Ipv4Util.addressForByteBuf(value));
builder.setIpv4InterfaceAddress(lipv4);
LOG.debug("Parsed IPv4 interface address {}.", lipv4);
break;
case TlvCode.IPV4_NEIGHBOR_ADDRESS:
- final Ipv4InterfaceIdentifier ripv4 = new Ipv4InterfaceIdentifier(Ipv4Util.addressForBytes(value));
+ final Ipv4InterfaceIdentifier ripv4 = new Ipv4InterfaceIdentifier(Ipv4Util.addressForByteBuf(value));
builder.setIpv4NeighborAddress(ripv4);
LOG.debug("Parsed IPv4 neighbor address {}.", ripv4);
break;
case TlvCode.IPV6_IFACE_ADDRESS:
- final Ipv6InterfaceIdentifier lipv6 = new Ipv6InterfaceIdentifier(Ipv6Util.addressForBytes(value));
+ final Ipv6InterfaceIdentifier lipv6 = new Ipv6InterfaceIdentifier(Ipv6Util.addressForByteBuf(value));
builder.setIpv6InterfaceAddress(lipv6);
LOG.debug("Parsed IPv6 interface address {}.", lipv6);
break;
case TlvCode.IPV6_NEIGHBOR_ADDRESS:
- final Ipv6InterfaceIdentifier ripv6 = new Ipv6InterfaceIdentifier(Ipv6Util.addressForBytes(value));
+ final Ipv6InterfaceIdentifier ripv6 = new Ipv6InterfaceIdentifier(Ipv6Util.addressForByteBuf(value));
builder.setIpv6NeighborAddress(ripv6);
LOG.debug("Parsed IPv6 neighbor address {}.", ripv6);
break;
case TlvCode.MULTI_TOPOLOGY_ID:
- final TopologyIdentifier topId = new TopologyIdentifier(ByteArray.bytesToInt(value) & 0x3fff);
+ final TopologyIdentifier topId = new TopologyIdentifier(value.readUnsignedShort() & LinkstateNlriParser.TOPOLOGY_ID_OFFSET);
builder.setMultiTopologyId(topId);
LOG.debug("Parsed topology identifier {}.", topId);
break;
default:
throw new BGPParsingException("Link Descriptor not recognized, type: " + type);
}
+ buffer.skipBytes(length);
}
LOG.trace("Finished parsing Link descriptors.");
return builder.build();
while (buffer.isReadable()) {
final int type = buffer.readUnsignedShort();
final int length = buffer.readUnsignedShort();
- final byte[] value = ByteArray.readBytes(buffer, length);
- LOG.trace("Parsing Node Descriptor: {}", Arrays.toString(value));
+ final ByteBuf value = buffer.slice(buffer.readerIndex(), length);
+ LOG.trace("Parsing Node Descriptor: {}", ByteBufUtil.hexDump(value));
switch (type) {
case TlvCode.AS_NUMBER:
- asnumber = new AsNumber(ByteArray.bytesToLong(value));
+ asnumber = new AsNumber(value.readUnsignedInt());
LOG.debug("Parsed {}", asnumber);
break;
case TlvCode.BGP_LS_ID:
- bgpId = new DomainIdentifier(UnsignedInteger.fromIntBits(ByteArray.bytesToInt(value)).longValue());
+ bgpId = new DomainIdentifier(value.readUnsignedInt());
LOG.debug("Parsed {}", bgpId);
break;
case TlvCode.AREA_ID:
- ai = new AreaIdentifier(UnsignedInteger.fromIntBits(ByteArray.bytesToInt(value)).longValue());
+ ai = new AreaIdentifier(value.readUnsignedInt());
LOG.debug("Parsed area identifier {}", ai);
break;
case TlvCode.IGP_ROUTER_ID:
default:
throw new BGPParsingException("Node Descriptor not recognized, type: " + type);
}
+ buffer.skipBytes(length);
}
LOG.trace("Finished parsing Node descriptors.");
return (local) ? new LocalNodeDescriptorsBuilder().setAsNumber(asnumber).setDomainId(bgpId).setAreaId(ai).setCRouterIdentifier(
: new RemoteNodeDescriptorsBuilder().setAsNumber(asnumber).setDomainId(bgpId).setAreaId(ai).setCRouterIdentifier(routerId).build();
}
- private static CRouterIdentifier parseRouterId(final byte[] value) throws BGPParsingException {
- if (value.length == ISO_SYSTEM_ID_LENGTH) {
+ private static CRouterIdentifier parseRouterId(final ByteBuf value) throws BGPParsingException {
+ if (value.readableBytes() == ISO_SYSTEM_ID_LENGTH || (value.readableBytes() == ISO_SYSTEM_ID_LENGTH + PSN_LENGTH && value.getByte(ISO_SYSTEM_ID_LENGTH) == 0)) {
return new IsisNodeCaseBuilder().setIsisNode(
- new IsisNodeBuilder().setIsoSystemId(new IsoSystemIdentifier(ByteArray.subByte(value, 0, ISO_SYSTEM_ID_LENGTH))).build()).build();
+ new IsisNodeBuilder().setIsoSystemId(new IsoSystemIdentifier(ByteArray.readBytes(value, ISO_SYSTEM_ID_LENGTH))).build()).build();
}
- if (value.length == ISO_SYSTEM_ID_LENGTH + PSN_LENGTH) {
- if (value[ISO_SYSTEM_ID_LENGTH] == 0) {
- LOG.warn("PSN octet is 0. Ignoring System ID.");
- return new IsisNodeCaseBuilder().setIsisNode(
- new IsisNodeBuilder().setIsoSystemId(new IsoSystemIdentifier(ByteArray.subByte(value, 0, ISO_SYSTEM_ID_LENGTH))).build()).build();
- } else {
- final IsIsRouterIdentifier iri = new IsIsRouterIdentifierBuilder().setIsoSystemId(
- new IsoSystemIdentifier(ByteArray.subByte(value, 0, ISO_SYSTEM_ID_LENGTH))).build();
- return new IsisPseudonodeCaseBuilder().setIsisPseudonode(new IsisPseudonodeBuilder().setIsIsRouterIdentifier(iri).setPsn(
- (short) UnsignedBytes.toInt(value[ISO_SYSTEM_ID_LENGTH])).build()).build();
- }
+ if (value.readableBytes() == ISO_SYSTEM_ID_LENGTH + PSN_LENGTH) {
+ final IsIsRouterIdentifier iri = new IsIsRouterIdentifierBuilder().setIsoSystemId(
+ new IsoSystemIdentifier(ByteArray.readBytes(value, ISO_SYSTEM_ID_LENGTH))).build();
+ return new IsisPseudonodeCaseBuilder().setIsisPseudonode(new IsisPseudonodeBuilder().setIsIsRouterIdentifier(iri).setPsn((short) value.readByte()).build()).build();
}
- if (value.length == 4) {
+ if (value.readableBytes() == OSPF_ROUTER_ID_LENGTH) {
return new OspfNodeCaseBuilder().setOspfNode(
- new OspfNodeBuilder().setOspfRouterId(ByteArray.bytesToUint32(value).longValue()).build()).build();
+ new OspfNodeBuilder().setOspfRouterId(value.readUnsignedInt()).build()).build();
}
- if (value.length == 8) {
- final byte[] o = ByteArray.subByte(value, 0, 4);
- final OspfInterfaceIdentifier a = new OspfInterfaceIdentifier(ByteArray.bytesToUint32(ByteArray.subByte(value, 4, 4)).longValue());
+ if (value.readableBytes() == 8) {
return new OspfPseudonodeCaseBuilder().setOspfPseudonode(
- new OspfPseudonodeBuilder().setOspfRouterId(ByteArray.bytesToUint32(o).longValue()).setLanInterface(a).build()).build();
+ new OspfPseudonodeBuilder().setOspfRouterId(value.readUnsignedInt()).setLanInterface(new OspfInterfaceIdentifier(value.readUnsignedInt())).build()).build();
}
- throw new BGPParsingException("Router Id of invalid length " + value.length);
+ throw new BGPParsingException("Router Id of invalid length " + value.readableBytes());
}
private static PrefixDescriptors parsePrefixDescriptors(final ByteBuf buffer, final boolean ipv4) throws BGPParsingException {
while (buffer.isReadable()) {
final int type = buffer.readUnsignedShort();
final int length = buffer.readUnsignedShort();
- final byte[] value = ByteArray.readBytes(buffer, length);
- LOG.trace("Parsing Prefix Descriptor: {}", Arrays.toString(value));
+ final ByteBuf value = buffer.slice(buffer.readerIndex(), length);
+ LOG.trace("Parsing Prefix Descriptor: {}", ByteBufUtil.hexDump(value));
switch (type) {
case TlvCode.MULTI_TOPOLOGY_ID:
- final TopologyIdentifier topologyId = new TopologyIdentifier(ByteArray.bytesToInt(value) & 0x3fff);
+ final TopologyIdentifier topologyId = new TopologyIdentifier(value.readShort() & LinkstateNlriParser.TOPOLOGY_ID_OFFSET);
builder.setMultiTopologyId(topologyId);
LOG.trace("Parsed Topology Identifier: {}", topologyId);
break;
case TlvCode.OSPF_ROUTE_TYPE:
- final int rt = ByteArray.bytesToInt(value);
+ final int rt = value.readByte();
final OspfRouteType routeType = OspfRouteType.forValue(rt);
if (routeType == null) {
throw new BGPParsingException("Unknown OSPF Route Type: " + rt);
break;
case TlvCode.IP_REACHABILITY:
IpPrefix prefix = null;
- final int prefixLength = UnsignedBytes.toInt(value[0]);
+ final int prefixLength = value.readByte();
final int size = prefixLength / Byte.SIZE + ((prefixLength % Byte.SIZE == 0) ? 0 : 1);
- if (size != value.length - 1) {
- LOG.debug("Expected length {}, actual length {}.", size, value.length - 1);
- throw new BGPParsingException("Illegal length of IP reachability TLV: " + (value.length - 1));
+ if (size != value.readableBytes()) {
+ LOG.debug("Expected length {}, actual length {}.", size, value.readableBytes());
+ throw new BGPParsingException("Illegal length of IP reachability TLV: " + (value.readableBytes()));
}
if (ipv4) {
- prefix = new IpPrefix(Ipv4Util.prefixForBytes(ByteArray.subByte(value, 1, size), prefixLength));
+ prefix = new IpPrefix(Ipv4Util.prefixForBytes(ByteArray.readBytes(value, size), prefixLength));
} else {
- prefix = new IpPrefix(Ipv6Util.prefixForBytes(ByteArray.subByte(value, 1, size), prefixLength));
+ prefix = new IpPrefix(Ipv6Util.prefixForBytes(ByteArray.readBytes(value, size), prefixLength));
}
builder.setIpReachabilityInformation(prefix);
LOG.trace("Parsed IP reachability info: {}", prefix);
default:
throw new BGPParsingException("Prefix Descriptor not recognized, type: " + type);
}
+ buffer.skipBytes(length);
}
LOG.debug("Finished parsing Prefix descriptors.");
return builder.build();
builder.setDistinguisher(distinguisher);
}
// parse source protocol
- final ProtocolId sp = ProtocolId.forValue(UnsignedBytes.toInt(nlri.readByte()));
+ final ProtocolId sp = ProtocolId.forValue(nlri.readByte());
builder.setProtocolId(sp);
// parse identifier
* Serializes Linkstate NLRI to byte array. We need this as NLRI serves as a key in upper layers.
*
* @param destination Linkstate NLRI to be serialized
- * @return byte array
*/
- public static byte[] serializeNlri(final CLinkstateDestination destination) {
- final ByteBuf finalBuffer = Unpooled.buffer();
- finalBuffer.writeShort(destination.getNlriType().getIntValue());
- final ByteBuf buffer = Unpooled.buffer();
+ public static void serializeNlri(final CLinkstateDestination destination, final ByteBuf buffer) {
+ final ByteBuf nlriByteBuf = Unpooled.buffer();
if (destination.getDistinguisher() != null) {
- buffer.writeBytes(destination.getDistinguisher().getValue().toByteArray());
+ nlriByteBuf.writeBytes(destination.getDistinguisher().getValue().toByteArray());
}
- buffer.writeByte(destination.getProtocolId().getIntValue());
- buffer.writeBytes(ByteArray.longToBytes(destination.getIdentifier().getValue().longValue(), IDENTIFIER_LENGTH));
+ nlriByteBuf.writeByte(destination.getProtocolId().getIntValue());
+ nlriByteBuf.writeLong(destination.getIdentifier().getValue().longValue());
// serialize local node descriptors
- final byte[] ldescs = serializeNodeDescriptors(destination.getLocalNodeDescriptors());
- buffer.writeShort(TlvCode.LOCAL_NODE_DESCRIPTORS);
- buffer.writeShort(ldescs.length);
- buffer.writeBytes(ldescs);
+ final ByteBuf ldescs = Unpooled.buffer();
+ serializeNodeDescriptors(destination.getLocalNodeDescriptors(), ldescs);
+ LinkstateAttributeParser.writeTLV(TlvCode.LOCAL_NODE_DESCRIPTORS, ldescs, nlriByteBuf);
switch (destination.getNlriType()) {
case Ipv4Prefix:
case Ipv6Prefix:
if (destination.getPrefixDescriptors() != null) {
- serializePrefixDescriptors(buffer, destination.getPrefixDescriptors());
+ serializePrefixDescriptors(destination.getPrefixDescriptors(), nlriByteBuf);
}
break;
case Link:
- final byte[] rdescs = serializeNodeDescriptors(destination.getRemoteNodeDescriptors());
- buffer.writeShort(TlvCode.REMOTE_NODE_DESCRIPTORS);
- buffer.writeShort(rdescs.length);
- buffer.writeBytes(rdescs);
+ final ByteBuf rdescs = Unpooled.buffer();
+ serializeNodeDescriptors(destination.getRemoteNodeDescriptors(), rdescs);
+ LinkstateAttributeParser.writeTLV(TlvCode.REMOTE_NODE_DESCRIPTORS, rdescs, nlriByteBuf);
if (destination.getLinkDescriptors() != null) {
- serializeLinkDescriptors(buffer, destination.getLinkDescriptors());
+ serializeLinkDescriptors(destination.getLinkDescriptors(), nlriByteBuf);
}
break;
case Node:
LOG.warn("Unknown NLRI Type.");
break;
}
- finalBuffer.writeShort(buffer.readableBytes());
- finalBuffer.writeBytes(buffer);
- return ByteArray.subByte(finalBuffer.array(), 0, finalBuffer.readableBytes());
+ LinkstateAttributeParser.writeTLV(destination.getNlriType().getIntValue(), nlriByteBuf, buffer);
}
- private static byte[] serializeNodeDescriptors(final NodeIdentifier descriptors) {
- final ByteBuf buffer = Unpooled.buffer();
- final int length = Integer.SIZE / Byte.SIZE;
+ private static void serializeNodeDescriptors(final NodeIdentifier descriptors, final ByteBuf buffer) {
if (descriptors.getAsNumber() != null) {
- buffer.writeShort(TlvCode.AS_NUMBER);
- buffer.writeShort(length);
- buffer.writeInt(UnsignedInteger.valueOf(descriptors.getAsNumber().getValue()).intValue());
+ LinkstateAttributeParser.writeTLV(TlvCode.AS_NUMBER, Unpooled.copyInt(UnsignedInteger.valueOf(descriptors.getAsNumber().getValue()).intValue()), buffer);
}
if (descriptors.getDomainId() != null) {
- buffer.writeShort(TlvCode.BGP_LS_ID);
- buffer.writeShort(length);
- buffer.writeInt(UnsignedInteger.valueOf(descriptors.getDomainId().getValue()).intValue());
+ LinkstateAttributeParser.writeTLV(TlvCode.BGP_LS_ID, Unpooled.copyInt(UnsignedInteger.valueOf(descriptors.getDomainId().getValue()).intValue()), buffer);
}
if (descriptors.getAreaId() != null) {
- buffer.writeShort(TlvCode.AREA_ID);
- buffer.writeShort(length);
- buffer.writeInt(UnsignedInteger.valueOf(descriptors.getAreaId().getValue()).intValue());
+ LinkstateAttributeParser.writeTLV(TlvCode.AREA_ID, Unpooled.copyInt(UnsignedInteger.valueOf(descriptors.getAreaId().getValue()).intValue()), buffer);
}
if (descriptors.getCRouterIdentifier() != null) {
- final byte[] value = serializeRouterId(descriptors.getCRouterIdentifier());
- buffer.writeShort(TlvCode.IGP_ROUTER_ID);
- buffer.writeShort(value.length);
- buffer.writeBytes(value);
+ final ByteBuf routerIdBuf = Unpooled.buffer();
+ serializeRouterId(descriptors.getCRouterIdentifier(), routerIdBuf);
+ LinkstateAttributeParser.writeTLV(TlvCode.IGP_ROUTER_ID, routerIdBuf, buffer);
}
- return ByteArray.readAllBytes(buffer);
}
- private static byte[] serializeRouterId(final CRouterIdentifier routerId) {
- byte[] bytes = null;
+ private static void serializeRouterId(final CRouterIdentifier routerId, final ByteBuf buffer) {
if (routerId instanceof IsisNodeCase) {
final IsisNode isis = ((IsisNodeCase) routerId).getIsisNode();
- bytes = isis.getIsoSystemId().getValue();
+ buffer.writeBytes(isis.getIsoSystemId().getValue());
} else if (routerId instanceof IsisPseudonodeCase) {
- bytes = new byte[ISO_SYSTEM_ID_LENGTH + PSN_LENGTH];
final IsisPseudonode isis = ((IsisPseudonodeCase) routerId).getIsisPseudonode();
- ByteArray.copyWhole(isis.getIsIsRouterIdentifier().getIsoSystemId().getValue(), bytes, 0);
- bytes[6] = UnsignedBytes.checkedCast((isis.getPsn() != null) ? isis.getPsn() : 0);
+ buffer.writeBytes(isis.getIsIsRouterIdentifier().getIsoSystemId().getValue());
+ buffer.writeByte(((isis.getPsn() != null) ? isis.getPsn() : 0));
} else if (routerId instanceof OspfNodeCase) {
- bytes = ByteArray.uint32ToBytes(((OspfNodeCase) routerId).getOspfNode().getOspfRouterId());
+ buffer.writeInt(UnsignedInteger.valueOf(((OspfNodeCase) routerId).getOspfNode().getOspfRouterId()).intValue());
} else if (routerId instanceof OspfPseudonodeCase) {
final OspfPseudonode node = ((OspfPseudonodeCase) routerId).getOspfPseudonode();
- bytes = new byte[2 * Integer.SIZE / Byte.SIZE];
- ByteArray.copyWhole(ByteArray.uint32ToBytes(node.getOspfRouterId()), bytes, 0);
- ByteArray.copyWhole(ByteArray.uint32ToBytes(node.getLanInterface().getValue()), bytes, Integer.SIZE / Byte.SIZE);
+ buffer.writeInt(UnsignedInteger.valueOf(node.getOspfRouterId()).intValue());
+ buffer.writeInt(UnsignedInteger.valueOf(node.getLanInterface().getValue()).intValue());
}
- return bytes;
}
- private static void serializeLinkDescriptors(final ByteBuf buffer, final LinkDescriptors descriptors) {
+ private static void serializeLinkDescriptors(final LinkDescriptors descriptors, final ByteBuf buffer) {
if (descriptors.getLinkLocalIdentifier() != null && descriptors.getLinkRemoteIdentifier() != null) {
- buffer.writeShort(TlvCode.LINK_LR_IDENTIFIERS);
- buffer.writeShort(LINK_IDENTIFIER_LENGTH);
- buffer.writeInt(UnsignedInteger.valueOf(descriptors.getLinkLocalIdentifier()).intValue());
- buffer.writeInt(UnsignedInteger.valueOf(descriptors.getLinkRemoteIdentifier()).intValue());
+ LinkstateAttributeParser.writeTLV(TlvCode.LINK_LR_IDENTIFIERS, Unpooled.copyInt(descriptors.getLinkLocalIdentifier().intValue()), buffer);
}
if (descriptors.getIpv4InterfaceAddress() != null) {
- final byte[] ipv4Address = Ipv4Util.bytesForAddress(descriptors.getIpv4InterfaceAddress());
- buffer.writeShort(TlvCode.IPV4_IFACE_ADDRESS);
- buffer.writeShort(ipv4Address.length);
- buffer.writeBytes(ipv4Address);
+ LinkstateAttributeParser.writeTLV(TlvCode.IPV4_IFACE_ADDRESS, Unpooled.wrappedBuffer(Ipv4Util.bytesForAddress(descriptors.getIpv4InterfaceAddress())), buffer);
}
if (descriptors.getIpv4NeighborAddress() != null) {
- final byte[] ipv4Address = Ipv4Util.bytesForAddress(descriptors.getIpv4NeighborAddress());
- buffer.writeShort(TlvCode.IPV4_NEIGHBOR_ADDRESS);
- buffer.writeShort(ipv4Address.length);
- buffer.writeBytes(ipv4Address);
+ LinkstateAttributeParser.writeTLV(TlvCode.IPV4_NEIGHBOR_ADDRESS, Unpooled.wrappedBuffer(Ipv4Util.bytesForAddress(descriptors.getIpv4NeighborAddress())), buffer);
}
if (descriptors.getIpv6InterfaceAddress() != null) {
- final byte[] ipv6Address = Ipv6Util.bytesForAddress(descriptors.getIpv6InterfaceAddress());
- buffer.writeShort(TlvCode.IPV6_IFACE_ADDRESS);
- buffer.writeShort(ipv6Address.length);
- buffer.writeBytes(ipv6Address);
+ LinkstateAttributeParser.writeTLV(TlvCode.IPV6_IFACE_ADDRESS, Unpooled.wrappedBuffer(Ipv6Util.bytesForAddress(descriptors.getIpv6InterfaceAddress())), buffer);
}
if (descriptors.getIpv6NeighborAddress() != null) {
- final byte[] ipv6Address = Ipv6Util.bytesForAddress(descriptors.getIpv6NeighborAddress());
- buffer.writeShort(TlvCode.IPV6_NEIGHBOR_ADDRESS);
- buffer.writeShort(ipv6Address.length);
- buffer.writeBytes(ipv6Address);
+ LinkstateAttributeParser.writeTLV(TlvCode.IPV6_NEIGHBOR_ADDRESS, Unpooled.wrappedBuffer(Ipv6Util.bytesForAddress(descriptors.getIpv6NeighborAddress())), buffer);
}
if (descriptors.getMultiTopologyId() != null) {
- buffer.writeShort(TlvCode.MULTI_TOPOLOGY_ID);
- buffer.writeShort(Short.SIZE / Byte.SIZE);
- buffer.writeShort(descriptors.getMultiTopologyId().getValue());
+ LinkstateAttributeParser.writeTLV(TlvCode.MULTI_TOPOLOGY_ID, Unpooled.copyShort(descriptors.getMultiTopologyId().getValue()), buffer);
}
}
- private static void serializePrefixDescriptors(final ByteBuf buffer, final PrefixDescriptors descriptors) {
+ private static void serializePrefixDescriptors(final PrefixDescriptors descriptors, final ByteBuf buffer) {
if (descriptors.getMultiTopologyId() != null) {
- buffer.writeShort(TlvCode.MULTI_TOPOLOGY_ID);
- buffer.writeShort(Short.SIZE / Byte.SIZE);
- buffer.writeShort(descriptors.getMultiTopologyId().getValue());
+ LinkstateAttributeParser.writeTLV(TlvCode.MULTI_TOPOLOGY_ID, Unpooled.copyShort(descriptors.getMultiTopologyId().getValue()), buffer);
}
if (descriptors.getOspfRouteType() != null) {
- buffer.writeShort(TlvCode.OSPF_ROUTE_TYPE);
- buffer.writeShort(1);
- buffer.writeByte(descriptors.getOspfRouteType().getIntValue());
+ LinkstateAttributeParser.writeTLV(TlvCode.OSPF_ROUTE_TYPE,
+ Unpooled.wrappedBuffer(new byte[] {UnsignedBytes.checkedCast(descriptors.getOspfRouteType().getIntValue()) }), buffer);
}
if (descriptors.getIpReachabilityInformation() != null) {
final IpPrefix prefix = descriptors.getIpReachabilityInformation();
byte[] prefixBytes = null;
- final int prefixLength = Ipv4Util.getPrefixLength(prefix);
if (prefix.getIpv4Prefix() != null) {
- prefixBytes = ByteArray.trim(ByteArray.subByte(Ipv4Util.bytesForPrefix(prefix.getIpv4Prefix()), 0,
- Ipv4Util.bytesForPrefix(prefix.getIpv4Prefix()).length - 1));
+ prefixBytes = Ipv4Util.bytesForPrefixBegin(prefix.getIpv4Prefix());
} else if (prefix.getIpv6Prefix() != null) {
- prefixBytes = ByteArray.trim(ByteArray.subByte(Ipv6Util.bytesForPrefix(prefix.getIpv6Prefix()), 0,
- Ipv6Util.bytesForPrefix(prefix.getIpv6Prefix()).length - 1));
+ prefixBytes = Ipv6Util.bytesForPrefixBegin(prefix.getIpv6Prefix());
}
- buffer.writeShort(TlvCode.IP_REACHABILITY);
- buffer.writeShort(1 + prefixBytes.length);
- buffer.writeByte(prefixLength);
- buffer.writeBytes(prefixBytes);
+ LinkstateAttributeParser.writeTLV(TlvCode.IP_REACHABILITY, Unpooled.wrappedBuffer(prefixBytes), buffer);
}
}
@Override
- public void serializeAttribute(DataObject attribute, ByteBuf byteAggregator) {
- PathAttributes pathAttributes = (PathAttributes) attribute;
- PathAttributes1 pathAttributes1 = pathAttributes.getAugmentation(PathAttributes1.class);
- PathAttributes2 pathAttributes2 = pathAttributes.getAugmentation(PathAttributes2.class);
- if (pathAttributes1 == null
- && pathAttributes2 == null) {
+ public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+ final PathAttributes pathAttributes = (PathAttributes) attribute;
+ final PathAttributes1 pathAttributes1 = pathAttributes.getAugmentation(PathAttributes1.class);
+ final PathAttributes2 pathAttributes2 = pathAttributes.getAugmentation(PathAttributes2.class);
+ if (pathAttributes1 == null && pathAttributes2 == null) {
return;
}
if (pathAttributes1 != null) {
- MpReachNlri mpReachNlri = pathAttributes1.getMpReachNlri();
- if (mpReachNlri.getAdvertizedRoutes() != null &&
- mpReachNlri.getAdvertizedRoutes().getDestinationType()
+ final AdvertizedRoutes routes = (pathAttributes1.getMpReachNlri()).getAdvertizedRoutes();
+ if (routes != null &&
+ routes.getDestinationType()
instanceof
org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationLinkstateCase) {
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationLinkstateCase
- linkstateCase = (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationLinkstateCase) mpReachNlri.getAdvertizedRoutes().getDestinationType();
- for (CLinkstateDestination cLinkstateDestination : linkstateCase.getDestinationLinkstate().getCLinkstateDestination()) {
- byteAggregator.writeBytes(serializeNlri(cLinkstateDestination));
+ final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationLinkstateCase
+ linkstateCase = (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationLinkstateCase) routes.getDestinationType();
+
+ for (final CLinkstateDestination cLinkstateDestination : linkstateCase.getDestinationLinkstate().getCLinkstateDestination()) {
+ serializeNlri(cLinkstateDestination, byteAggregator);
}
}
- }
- if (pathAttributes2 != null) {
+ } else if (pathAttributes2 != null) {
MpUnreachNlri mpUnreachNlri = pathAttributes2.getMpUnreachNlri();
if (mpUnreachNlri.getWithdrawnRoutes() != null && mpUnreachNlri.getWithdrawnRoutes().getDestinationType() instanceof DestinationLinkstateCase) {
DestinationLinkstateCase linkstateCase = (DestinationLinkstateCase) mpUnreachNlri.getWithdrawnRoutes().getDestinationType();
for (CLinkstateDestination cLinkstateDestination : linkstateCase.getDestinationLinkstate().getCLinkstateDestination()) {
- byteAggregator.writeBytes(serializeNlri(cLinkstateDestination));
+ serializeNlri(cLinkstateDestination, byteAggregator);
}
}
}
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+
+import com.google.common.collect.Lists;
+
+import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.math.BigInteger;
+import java.util.List;
import org.junit.Test;
import org.opendaylight.protocol.bgp.parser.BGPParsingException;
+import org.opendaylight.protocol.util.ByteArray;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.DomainIdentifier;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.node.identifier.c.router.identifier.isis.pseudonode._case.IsisPseudonodeBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.node.identifier.c.router.identifier.ospf.node._case.OspfNodeBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationLinkstateCase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationLinkstateCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.destination.linkstate._case.DestinationLinkstate;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.destination.linkstate._case.DestinationLinkstateBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.PathAttributes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.PathAttributesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes1;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes1Builder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes2;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes2Builder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpReachNlriBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpUnreachNlriBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.reach.nlri.AdvertizedRoutes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.unreach.nlri.WithdrawnRoutes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.concepts.rev131125.IsoSystemIdentifier;
public class LinkstateNlriParserTest {
(byte) 0x02, (byte) 0x00, (byte) 0x0F, (byte) 0x01, (byte) 0x08, (byte) 0x00, (byte) 0x01, (byte) 0x03, (byte) 0x01, (byte) 0x09,
(byte) 0x00, (byte) 0x03, (byte) 0x10, (byte) 0xFF, (byte) 0xFF };
- @Test
- public void testNodeNlri() throws BGPParsingException {
+ private CLinkstateDestination dest;
+
+ private void setUp(final byte[] data) throws BGPParsingException {
final LinkstateNlriParser parser = new LinkstateNlriParser(false);
final MpReachNlriBuilder builder = new MpReachNlriBuilder();
- parser.parseNlri(Unpooled.copiedBuffer(this.nodeNlri), builder);
+ parser.parseNlri(Unpooled.copiedBuffer(data), builder);
final DestinationLinkstate ls = ((DestinationLinkstateCase) builder.getAdvertizedRoutes().getDestinationType()).getDestinationLinkstate();
-
assertEquals(1, ls.getCLinkstateDestination().size());
- final CLinkstateDestination dest = ls.getCLinkstateDestination().get(0);
+ this.dest = ls.getCLinkstateDestination().get(0);
+ }
+
+ @Test
+ public void testNodeNlri() throws BGPParsingException {
+ setUp(this.nodeNlri);
- assertEquals(NlriType.Node, dest.getNlriType());
- assertNull(dest.getDistinguisher());
- assertEquals(ProtocolId.IsisLevel2, dest.getProtocolId());
- assertEquals(BigInteger.ONE, dest.getIdentifier().getValue());
+ assertEquals(NlriType.Node, this.dest.getNlriType());
+ assertNull(this.dest.getDistinguisher());
+ assertEquals(ProtocolId.IsisLevel2, this.dest.getProtocolId());
+ assertEquals(BigInteger.ONE, this.dest.getIdentifier().getValue());
- final LocalNodeDescriptors nodeD = dest.getLocalNodeDescriptors();
+ final LocalNodeDescriptors nodeD = this.dest.getLocalNodeDescriptors();
assertEquals(new AsNumber(72L), nodeD.getAsNumber());
assertEquals(new DomainIdentifier(0x28282828L), nodeD.getDomainId());
assertEquals(new IsisPseudonodeCaseBuilder().setIsisPseudonode(
- new IsisPseudonodeBuilder().setPsn((short) 5).setIsIsRouterIdentifier(
- new IsIsRouterIdentifierBuilder().setIsoSystemId(
- new IsoSystemIdentifier(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
- (byte) 0x39 })).build()).build()).build(), nodeD.getCRouterIdentifier());
+ new IsisPseudonodeBuilder().setPsn((short) 5).setIsIsRouterIdentifier(
+ new IsIsRouterIdentifierBuilder().setIsoSystemId(
+ new IsoSystemIdentifier(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+ (byte) 0x39 })).build()).build()).build(), nodeD.getCRouterIdentifier());
- assertNull(dest.getRemoteNodeDescriptors());
+ assertNull(this.dest.getRemoteNodeDescriptors());
- assertArrayEquals(this.nodeNlri, LinkstateNlriParser.serializeNlri(dest));
+ final ByteBuf buffer = Unpooled.buffer();
+ LinkstateNlriParser.serializeNlri(this.dest, buffer);
+ assertArrayEquals(this.nodeNlri, ByteArray.readAllBytes(buffer));
}
@Test
public void testLinkNlri() throws BGPParsingException {
- final LinkstateNlriParser parser = new LinkstateNlriParser(false);
- final MpReachNlriBuilder builder = new MpReachNlriBuilder();
- parser.parseNlri(Unpooled.copiedBuffer(this.linkNlri), builder);
+ setUp(this.linkNlri);
- final DestinationLinkstate ls = ((DestinationLinkstateCase) builder.getAdvertizedRoutes().getDestinationType()).getDestinationLinkstate();
+ assertEquals(NlriType.Link, this.dest.getNlriType());
+ assertNull(this.dest.getDistinguisher());
+ assertEquals(ProtocolId.IsisLevel2, this.dest.getProtocolId());
+ assertEquals(BigInteger.ONE, this.dest.getIdentifier().getValue());
- assertEquals(1, ls.getCLinkstateDestination().size());
-
- final CLinkstateDestination dest = ls.getCLinkstateDestination().get(0);
-
- assertEquals(NlriType.Link, dest.getNlriType());
- assertNull(dest.getDistinguisher());
- assertEquals(ProtocolId.IsisLevel2, dest.getProtocolId());
- assertEquals(BigInteger.ONE, dest.getIdentifier().getValue());
-
- final LocalNodeDescriptors local = dest.getLocalNodeDescriptors();
+ final LocalNodeDescriptors local = this.dest.getLocalNodeDescriptors();
assertEquals(new AsNumber(72L), local.getAsNumber());
assertEquals(new DomainIdentifier(0x28282828L), local.getDomainId());
assertEquals(
- new IsisNodeCaseBuilder().setIsisNode(
- new IsisNodeBuilder().setIsoSystemId(
- new IsoSystemIdentifier(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
- (byte) 0x42 })).build()).build(), local.getCRouterIdentifier());
- final RemoteNodeDescriptors remote = dest.getRemoteNodeDescriptors();
+ new IsisNodeCaseBuilder().setIsisNode(
+ new IsisNodeBuilder().setIsoSystemId(
+ new IsoSystemIdentifier(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+ (byte) 0x42 })).build()).build(), local.getCRouterIdentifier());
+ final RemoteNodeDescriptors remote = this.dest.getRemoteNodeDescriptors();
assertEquals(new AsNumber(72L), remote.getAsNumber());
assertEquals(new DomainIdentifier(0x28282828L), remote.getDomainId());
assertEquals(new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x00000040L).build()).build(),
- remote.getCRouterIdentifier());
- final LinkDescriptors ld = dest.getLinkDescriptors();
+ remote.getCRouterIdentifier());
+ final LinkDescriptors ld = this.dest.getLinkDescriptors();
assertEquals("197.20.160.42", ld.getIpv4InterfaceAddress().getValue());
assertEquals("197.20.160.40", ld.getIpv4NeighborAddress().getValue());
- assertArrayEquals(this.linkNlri, LinkstateNlriParser.serializeNlri(dest));
+ final ByteBuf buffer = Unpooled.buffer();
+ LinkstateNlriParser.serializeNlri(this.dest, buffer);
+ assertArrayEquals(this.linkNlri, ByteArray.readAllBytes(buffer));
}
@Test
public void testPrefixNlri() throws BGPParsingException {
- final LinkstateNlriParser parser = new LinkstateNlriParser(false);
- final MpReachNlriBuilder builder = new MpReachNlriBuilder();
- parser.parseNlri(Unpooled.copiedBuffer(this.prefixNlri), builder);
+ setUp(this.prefixNlri);
- final DestinationLinkstate ls = ((DestinationLinkstateCase) builder.getAdvertizedRoutes().getDestinationType()).getDestinationLinkstate();
+ assertEquals(NlriType.Ipv4Prefix, this.dest.getNlriType());
+ assertNull(this.dest.getDistinguisher());
+ assertEquals(ProtocolId.IsisLevel2, this.dest.getProtocolId());
+ assertEquals(BigInteger.ONE, this.dest.getIdentifier().getValue());
- assertEquals(1, ls.getCLinkstateDestination().size());
-
- final CLinkstateDestination dest = ls.getCLinkstateDestination().get(0);
-
- assertEquals(NlriType.Ipv4Prefix, dest.getNlriType());
- assertNull(dest.getDistinguisher());
- assertEquals(ProtocolId.IsisLevel2, dest.getProtocolId());
- assertEquals(BigInteger.ONE, dest.getIdentifier().getValue());
-
- final LocalNodeDescriptors local = dest.getLocalNodeDescriptors();
+ final LocalNodeDescriptors local = this.dest.getLocalNodeDescriptors();
assertEquals(new AsNumber(72L), local.getAsNumber());
assertEquals(new DomainIdentifier(0x28282828L), local.getDomainId());
assertEquals(
- new IsisNodeCaseBuilder().setIsisNode(
- new IsisNodeBuilder().setIsoSystemId(
- new IsoSystemIdentifier(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
- (byte) 0x42 })).build()).build(), local.getCRouterIdentifier());
- assertNull(dest.getRemoteNodeDescriptors());
+ new IsisNodeCaseBuilder().setIsisNode(
+ new IsisNodeBuilder().setIsoSystemId(
+ new IsoSystemIdentifier(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+ (byte) 0x42 })).build()).build(), local.getCRouterIdentifier());
+ assertNull(this.dest.getRemoteNodeDescriptors());
- final PrefixDescriptors pd = dest.getPrefixDescriptors();
+ final PrefixDescriptors pd = this.dest.getPrefixDescriptors();
assertEquals(OspfRouteType.External1, pd.getOspfRouteType());
assertEquals(new TopologyIdentifier(15), pd.getMultiTopologyId());
assertEquals(new Ipv4Prefix("255.255.0.0/16"), pd.getIpReachabilityInformation().getIpv4Prefix());
- assertArrayEquals(this.prefixNlri, LinkstateNlriParser.serializeNlri(dest));
+ final ByteBuf buffer = Unpooled.buffer();
+ LinkstateNlriParser.serializeNlri(this.dest, buffer);
+ assertArrayEquals(this.prefixNlri, ByteArray.readAllBytes(buffer));
+ }
+
+ @Test
+ public void testSerializeAttribute() throws BGPParsingException {
+ final LinkstateNlriParser parser = new LinkstateNlriParser(true);
+ setUp(this.prefixNlri);
+ final List<CLinkstateDestination> dests = Lists.newArrayList( this.dest );
+ final DestinationLinkstateCase dlc = new DestinationLinkstateCaseBuilder().setDestinationLinkstate(new DestinationLinkstateBuilder().setCLinkstateDestination(dests).build()).build();
+ final AdvertizedRoutes aroutes = new AdvertizedRoutesBuilder().setDestinationType(dlc).build();
+ final PathAttributes1 reach = new PathAttributes1Builder().setMpReachNlri(new MpReachNlriBuilder().setAdvertizedRoutes(aroutes).build()).build();
+
+ PathAttributes pa = new PathAttributesBuilder().addAugmentation(PathAttributes1.class, reach).build();
+
+ ByteBuf result = Unpooled.buffer();
+ parser.serializeAttribute(pa, result);
+ assertArrayEquals(this.prefixNlri, ByteArray.getAllBytes(result));
+
+ setUp(this.nodeNlri);
+ final List<CLinkstateDestination> destsU = Lists.newArrayList( this.dest );
+ final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.unreach.nlri.withdrawn.routes.destination.type.DestinationLinkstateCase dlcU =
+ new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.unreach.nlri.withdrawn.routes.destination.type.DestinationLinkstateCaseBuilder().setDestinationLinkstate(
+ new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.update.path.attributes.mp.unreach.nlri.withdrawn.routes.destination.type.destination.linkstate._case.DestinationLinkstateBuilder().setCLinkstateDestination(destsU).build()).build();
+ final WithdrawnRoutes wroutes = new WithdrawnRoutesBuilder().setDestinationType(dlcU).build();
+ final PathAttributes2 unreach = new PathAttributes2Builder().setMpUnreachNlri(new MpUnreachNlriBuilder().setWithdrawnRoutes(wroutes).build()).build();
+
+ pa = new PathAttributesBuilder().addAugmentation(PathAttributes2.class, unreach).build();
+
+ result = Unpooled.buffer();
+ parser.serializeAttribute(pa, result);
+ assertArrayEquals(this.nodeNlri, ByteArray.getAllBytes(result));
}
}
public final class AsNumberUtil {
private AsNumberUtil() {
- throw new UnsupportedOperationException("Utility class should never be instantiated");
}
/**
public BGPParsingException(final String message, final Exception cause) {
super(message, cause);
}
-
- /**
- *
- * @return error message.
- *
- * @deprecated Use getMessage() instead.
- */
- @Deprecated
- public String getError() {
- return this.getMessage();
- }
}
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParametersBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.c.parameters.As4BytesCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.c.parameters.as4.bytes._case.As4BytesCapabilityBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.c.parameters.MultiprotocolCaseBuilder;
public class APITest {
public void testParsingException() {
final BGPParsingException de = new BGPParsingException("Some message");
assertEquals("Some message", de.getMessage());
+
+ final BGPParsingException de1 = new BGPParsingException("Some message", new IllegalArgumentException("text"));
+ assertEquals("text", de1.getCause().getMessage());
}
@Test
public void testAsNumberUtil() {
final List<BgpParameters> params = new ArrayList<>();
params.add(new BgpParametersBuilder().setCParameters(
- new As4BytesCaseBuilder().setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(new AsNumber(35L)).build()).build()).build());
+ new MultiprotocolCaseBuilder().setMultiprotocolCapability(null).build()).build());
+ params.add(new BgpParametersBuilder().setCParameters(
+ new As4BytesCaseBuilder().setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(new AsNumber(35L)).build()).build()).build());
final Open open1 = new OpenBuilder().setBgpParameters(params).build();
assertEquals(35L, AsNumberUtil.advertizedAsNumber(open1).getValue().longValue());
}
@Override
- public void serializeMessage(final Notification message, ByteBuf bytes) {
+ public void serializeMessage(final Notification message, final ByteBuf bytes) {
Preconditions.checkArgument(message instanceof Keepalive);
bytes.writeBytes(KEEPALIVE_BYTES.slice());
}
*/
package org.opendaylight.protocol.bgp.parser.impl.message;
-import com.google.common.primitives.UnsignedBytes;
+import com.google.common.base.Preconditions;
+
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
+
import java.util.Arrays;
+
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPError;
import org.opendaylight.protocol.bgp.parser.spi.MessageParser;
* Serializes BGP Notification message.
*
* @param msg to be serialized
- * @return BGP Notification message converted to byte array
+ * @param ByteBuf where the message will be serialized
*/
@Override
- public void serializeMessage(final Notification msg, ByteBuf bytes) {
- if (msg == null) {
- throw new IllegalArgumentException("BGP Notification message cannot be null");
- }
-
+ public void serializeMessage(final Notification msg, final ByteBuf bytes) {
+ Preconditions.checkArgument(msg != null, "BGP Notification message cannot be null");
final Notify ntf = (Notify) msg;
LOG.trace("Started serializing Notification message: {}", ntf);
byte[] data = ntf.getData();
- final ByteBuf msgBody = Unpooled.buffer(ERROR_SIZE + (data != null ? data.length : 0));
-
+ final ByteBuf msgBody = Unpooled.buffer();
msgBody.writeByte(ntf.getErrorCode());
-
msgBody.writeByte(ntf.getErrorSubcode());
-
if (data != null) {
msgBody.writeBytes(data);
}
-
- MessageUtil.formatMessage(TYPE, msgBody, bytes);
LOG.trace("Notification message serialized to: {}", ByteBufUtil.hexDump(bytes));
+ MessageUtil.formatMessage(TYPE, msgBody, bytes);
}
/**
* Parses BGP Notification message to bytes.
*
- * @param body byte array to be parsed
+ * @param body ByteBuf to be parsed
* @return BGPNotification message
- * @throws BGPDocumentedException
+ * @throws BGPDocumentedException if parsing goes wrong
*/
@Override
public Notify parseMessageBody(final ByteBuf body, final int messageLength) throws BGPDocumentedException {
- if (body == null) {
- throw new IllegalArgumentException("Byte array cannot be null.");
- }
- LOG.trace("Started parsing of notification message: {}", Arrays.toString(ByteArray.getAllBytes(body)));
-
+ Preconditions.checkArgument(body != null, "Byte buffer cannot be null.");
+ LOG.trace("Started parsing of notification message: {}", ByteBufUtil.hexDump(body));
if (body.readableBytes() < ERROR_SIZE) {
throw BGPDocumentedException.badMessageLength("Notification message too small.", messageLength);
}
- final int errorCode = UnsignedBytes.toInt(body.readByte());
- final int errorSubcode = UnsignedBytes.toInt(body.readByte());
-
- byte[] data = null;
- if (body.readableBytes() != 0) {
- data = ByteArray.readAllBytes(body);
- }
+ final int errorCode = body.readUnsignedByte();
+ final int errorSubcode = body.readUnsignedByte();
final NotifyBuilder builder = new NotifyBuilder().setErrorCode((short) errorCode).setErrorSubcode((short) errorSubcode);
- if (data != null) {
- builder.setData(data);
+ if (body.isReadable()) {
+ builder.setData(ByteArray.readAllBytes(body));
}
LOG.debug("BGP Notification message was parsed: err = {}, data = {}.", BGPError.forValue(errorCode, errorSubcode),
- Arrays.toString(data));
+ Arrays.toString(builder.getData()));
return builder.build();
}
}
package org.opendaylight.protocol.bgp.parser.impl.message;
import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.google.common.primitives.UnsignedBytes;
+
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
+
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPError;
import org.opendaylight.protocol.bgp.parser.BGPParsingException;
import org.opendaylight.protocol.bgp.parser.spi.MessageSerializer;
import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
import org.opendaylight.protocol.bgp.parser.spi.ParameterRegistry;
-import org.opendaylight.protocol.util.ByteArray;
import org.opendaylight.protocol.util.Ipv4Util;
import org.opendaylight.protocol.util.Values;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
* Serializes given BGP Open message to byte array, without the header.
*
* @param msg BGP Open message to be serialized.
- * @return BGP Open message converted to byte array
+ * @param bytes ByteBuf where the message will be serialized
*/
@Override
- public void serializeMessage(final Notification msg, ByteBuf bytes) {
- if (msg == null) {
- throw new IllegalArgumentException("BGPOpen message cannot be null");
- }
+ public void serializeMessage(final Notification msg, final ByteBuf bytes) {
+ Preconditions.checkArgument(msg != null, "BGP Open message cannot be null");
LOG.trace("Started serializing open message: {}", msg);
final Open open = (Open) msg;
-
- final ByteBuf paramsBuffer = Unpooled.buffer();
- if (open.getBgpParameters() != null) {
- for (final BgpParameters param : open.getBgpParameters()) {
- this.reg.serializeParameter(param, paramsBuffer);
- }
- }
final ByteBuf msgBody = Unpooled.buffer();
msgBody.writeByte(BGP_VERSION);
msgBody.writeShort(open.getHoldTimer());
msgBody.writeBytes(Ipv4Util.bytesForAddress(open.getBgpIdentifier()));
+ final ByteBuf paramsBuffer = Unpooled.buffer();
+ if (open.getBgpParameters() != null) {
+ for (final BgpParameters param : open.getBgpParameters()) {
+ this.reg.serializeParameter(param, paramsBuffer);
+ }
+ }
msgBody.writeByte(paramsBuffer.writerIndex());
msgBody.writeBytes(paramsBuffer);
- MessageUtil.formatMessage(TYPE, msgBody, bytes);
LOG.trace("Open message serialized to: {}", ByteBufUtil.hexDump(bytes));
+ MessageUtil.formatMessage(TYPE, msgBody, bytes);
}
/**
*/
@Override
public Open parseMessageBody(final ByteBuf body, final int messageLength) throws BGPDocumentedException {
- if (body == null) {
- throw new IllegalArgumentException("Byte array cannot be null.");
- }
- LOG.trace("Started parsing of open message: {}", Arrays.toString(ByteArray.getAllBytes(body)));
+ Preconditions.checkArgument(body != null, "Byte array cannot be null.");
+ LOG.trace("Started parsing of open message: {}", ByteBufUtil.hexDump(body));
if (body.readableBytes() < MIN_MSG_LENGTH) {
throw BGPDocumentedException.badMessageLength("Open message too small.", messageLength);
}
- int version = UnsignedBytes.toInt(body.readByte());
+ int version = body.readUnsignedByte();
if (version != BGP_VERSION) {
throw new BGPDocumentedException("BGP Protocol version " + version + " not supported.", BGPError.VERSION_NOT_SUPPORTED);
}
}
Ipv4Address bgpId = null;
try {
- bgpId = Ipv4Util.addressForBytes(ByteArray.readBytes(body, BGP_ID_SIZE));
+ bgpId = Ipv4Util.addressForByteBuf(body);
} catch (final IllegalArgumentException e) {
throw new BGPDocumentedException("BGP Identifier is not a valid IPv4 Address", BGPError.BAD_BGP_ID, e);
}
- final int optLength = UnsignedBytes.toInt(body.readByte());
+ final int optLength = body.readUnsignedByte();
- final List<BgpParameters> optParams = Lists.newArrayList();
+ final List<BgpParameters> optParams = new ArrayList<>();
if (optLength > 0) {
fillParams(body.slice(body.readerIndex(), optLength), optParams);
}
LOG.debug("BGP Open message was parsed: AS = {}, holdTimer = {}, bgpId = {}, optParams = {}", as, holdTime, bgpId, optParams);
return new OpenBuilder().setMyAsNumber(as.getValue().intValue()).setHoldTimer(holdTime).setBgpIdentifier(bgpId).setBgpParameters(
- optParams).build();
+ optParams).build();
}
private void fillParams(final ByteBuf buffer, final List<BgpParameters> params) throws BGPDocumentedException {
- Preconditions.checkArgument(buffer != null && buffer.readableBytes() != 0, "Byte array cannot be null or empty.");
- LOG.trace("Started parsing of BGP parameter: {}", Arrays.toString(ByteArray.getAllBytes(buffer)));
- while (buffer.readableBytes() != 0) {
+ Preconditions.checkArgument(buffer != null && buffer.isReadable(), "Byte array cannot be null or empty.");
+ LOG.trace("Started parsing of BGP parameter: {}", ByteBufUtil.hexDump(buffer));
+ while (buffer.isReadable()) {
if (buffer.readableBytes() <= 2) {
throw new BGPDocumentedException("Malformed parameter encountered (" + buffer.readableBytes() + " bytes left)", BGPError.OPT_PARAM_NOT_SUPPORTED);
}
- final int paramType = UnsignedBytes.toInt(buffer.readByte());
- final int paramLength = UnsignedBytes.toInt(buffer.readByte());
+ final int paramType = buffer.readUnsignedByte();
+ final int paramLength = buffer.readUnsignedByte();
final ByteBuf paramBody = buffer.slice(buffer.readerIndex(), paramLength);
final BgpParameters param;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
+
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPParsingException;
import org.opendaylight.protocol.bgp.parser.spi.CapabilityParser;
public final class As4CapabilityHandler implements CapabilityParser, CapabilitySerializer {
public static final int CODE = 65;
- private static final int AS4_LENGTH = 4;
-
@Override
public CParameters parseCapability(final ByteBuf buffer) throws BGPDocumentedException, BGPParsingException {
return new As4BytesCaseBuilder().setAs4BytesCapability(
- new As4BytesCapabilityBuilder().setAsNumber(new AsNumber(buffer.readUnsignedInt())).build()).build();
+ new As4BytesCapabilityBuilder().setAsNumber(new AsNumber(buffer.readUnsignedInt())).build()).build();
}
@Override
package org.opendaylight.protocol.bgp.parser.impl.message.open;
import com.google.common.base.Preconditions;
-import com.google.common.primitives.UnsignedBytes;
import io.netty.buffer.ByteBuf;
-
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
+
import java.util.Arrays;
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
public BgpParameters parseParameter(final ByteBuf buffer) throws BGPParsingException, BGPDocumentedException {
Preconditions.checkArgument(buffer != null && buffer.readableBytes() != 0, "Byte array cannot be null or empty.");
LOG.trace("Started parsing of BGP Capability: {}", Arrays.toString(ByteArray.getAllBytes(buffer)));
- final int capCode = UnsignedBytes.toInt(buffer.readByte());
- final int capLength = UnsignedBytes.toInt(buffer.readByte());
+ final int capCode = buffer.readUnsignedByte();
+ final int capLength = buffer.readUnsignedByte();
final ByteBuf paramBody = buffer.slice(buffer.readerIndex(), capLength);
final CParameters ret = this.reg.parseCapability(capCode, paramBody);
if (ret == null) {
LOG.trace("Started serializing BGP Capability: {}", cap);
- ByteBuf bytes = Unpooled.buffer();
+ final ByteBuf bytes = Unpooled.buffer();
this.reg.serializeCapability(cap,bytes);
if (bytes == null) {
throw new IllegalArgumentException("Unhandled capability class" + cap.getImplementedInterface());
}
-
LOG.trace("BGP capability serialized to: {}", ByteBufUtil.hexDump(bytes));
-
ParameterUtil.formatParameter(TYPE, bytes,byteAggregator);
}
}
package org.opendaylight.protocol.bgp.parser.impl.message.open;
import com.google.common.base.Preconditions;
-import com.google.common.primitives.UnsignedBytes;
import io.netty.buffer.ByteBuf;
-
import io.netty.buffer.Unpooled;
+
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPParsingException;
import org.opendaylight.protocol.bgp.parser.spi.AddressFamilyRegistry;
private final AddressFamilyRegistry afiReg;
private final SubsequentAddressFamilyRegistry safiReg;
+ private static final int RESERVED = 1;
+
public MultiProtocolCapabilityHandler(final AddressFamilyRegistry afiReg, final SubsequentAddressFamilyRegistry safiReg) {
this.afiReg = Preconditions.checkNotNull(afiReg);
this.safiReg = Preconditions.checkNotNull(safiReg);
throw new BGPParsingException("Address Family Identifier: '" + afiVal + "' not supported.");
}
// skip reserved
- buffer.skipBytes(1);
- final int safiVal = UnsignedBytes.toInt(buffer.readByte());
+ buffer.skipBytes(RESERVED);
+ final int safiVal = buffer.readUnsignedByte();
final Class<? extends SubsequentAddressFamily> safi = this.safiReg.classForFamily(safiVal);
if (safi == null) {
throw new BGPParsingException("Subsequent Address Family Identifier: '" + safiVal + "' not supported.");
}
return new MultiprotocolCaseBuilder().setMultiprotocolCapability(
- new MultiprotocolCapabilityBuilder().setAfi(afi).setSafi(safi).build()).build();
+ new MultiprotocolCapabilityBuilder().setAfi(afi).setSafi(safi).build()).build();
}
@Override
public void serializeCapability(final CParameters capability, ByteBuf byteAggregator) {
final MultiprotocolCase mp = (MultiprotocolCase) capability;
-
+ final ByteBuf capBuffer = Unpooled.buffer();
final Class<? extends AddressFamily> afi = mp.getMultiprotocolCapability().getAfi();
final Integer afival = this.afiReg.numberForClass(afi);
Preconditions.checkArgument(afival != null, "Unhandled address family " + afi);
+ capBuffer.writeShort(afival);
final Class<? extends SubsequentAddressFamily> safi = mp.getMultiprotocolCapability().getSafi();
final Integer safival = this.safiReg.numberForClass(safi);
Preconditions.checkArgument(safival != null, "Unhandled subsequent address family " + safi);
+ capBuffer.writeZero(RESERVED);
+ capBuffer.writeByte(safival);
- CapabilityUtil.formatCapability(CODE, Unpooled.wrappedBuffer(new byte[] { UnsignedBytes.checkedCast(afival / 256),
- UnsignedBytes.checkedCast(afival % 256), 0, UnsignedBytes.checkedCast(safival) }), byteAggregator);
+ CapabilityUtil.formatCapability(CODE, capBuffer, byteAggregator);
}
}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.parser.impl;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertTrue;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
-import org.opendaylight.protocol.bgp.parser.impl.message.BGPUpdateMessageParser;
-import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
-import org.opendaylight.protocol.bgp.parser.spi.pojo.ServiceLoaderBGPExtensionProviderContext;
-import org.opendaylight.protocol.util.ByteArray;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.AsPath;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Communities;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.ExtendedCommunities;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.as.path.Segments;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.Nlri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.PathAttributes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.WithdrawnRoutes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes2;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ClusterIdentifier;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ExtendedCommunity;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.CNextHop;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.Ipv4NextHopCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.next.hop.c.next.hop.Ipv6NextHopCase;
-
-public class BGPUpdateAttributesSerializationTest {
-
- static final List<byte[]> inputBytes = new ArrayList<>();
- private static BGPUpdateMessageParser updateParser = new BGPUpdateMessageParser(ServiceLoaderBGPExtensionProviderContext.getSingletonInstance().getAttributeRegistry());
-
- private static int COUNTER = 10;//17;
-
- private static int MAX_SIZE = 300;
-
- @Before
- public void setupUpdateMessage() throws Exception {
-
- for (int i = 1; i <= COUNTER; i++) {
- final String name = "/up" + i + ".bin";
- final InputStream is = BGPParserTest.class.getResourceAsStream(name);
- if (is == null) {
- throw new IOException("Failed to get resource " + name);
- }
- final ByteArrayOutputStream bis = new ByteArrayOutputStream();
- final byte[] data = new byte[MAX_SIZE];
- int nRead = 0;
- while ((nRead = is.read(data, 0, data.length)) != -1) {
- bis.write(data, 0, nRead);
- }
- bis.flush();
-
- inputBytes.add(bis.toByteArray());
- }
- }
-
- private Update readUpdateMessageFromList(int listIndex) throws BGPDocumentedException {
- return readUpdateMessageBytes(Unpooled.copiedBuffer(inputBytes.get(listIndex)));
- }
-
- private Update readUpdateMessageBytes(ByteBuf messageBytes) throws BGPDocumentedException {
- final byte[] body = ByteArray.cutBytes(ByteArray.getAllBytes(messageBytes), MessageUtil.COMMON_HEADER_LENGTH);
- final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(ByteArray.getAllBytes(messageBytes), MessageUtil.MARKER_LENGTH, 2));
- return BGPUpdateAttributesSerializationTest.updateParser.parseMessageBody(Unpooled.copiedBuffer(body), messageLength);
- }
-
- private void assertEqualsPathAttributes(PathAttributes left, PathAttributes right) {
- if (left.getCNextHop() != null) {
- assertEqualsNextHop(left.getCNextHop(), right.getCNextHop());
- }
- if (left.getAsPath() != null) {
- assertEqualsAsPath(left.getAsPath(), right.getAsPath());
- }
- if (left.getExtendedCommunities() != null) {
- assertEqualsExtendedCommunities(left.getExtendedCommunities(), right.getExtendedCommunities());
- }
- if (left.getCommunities() != null) {
- assertEqualsCommunities(left.getCommunities(), right.getCommunities());
- }
- if (left.getAggregator() != null) {
- assertEquals(left.getAggregator().getAsNumber().getValue(), right.getAggregator().getAsNumber().getValue());
- assertEquals(left.getAggregator().getNetworkAddress().getValue(), right.getAggregator().getNetworkAddress().getValue());
- }
- if (left.getAtomicAggregate() != null) {
- assertEquals(left.getAtomicAggregate() != null, right.getAtomicAggregate() != null);
- }
- if (left.getClusterId() != null) {
- assertEqualsClusterId(left.getClusterId().getCluster(), right.getClusterId().getCluster());
- }
- if (left.getLocalPref() != null) {
- assertEquals(left.getLocalPref().getPref(), right.getLocalPref().getPref());
- }
- if (left.getMultiExitDisc() != null) {
- assertEquals(left.getMultiExitDisc().getMed(), right.getMultiExitDisc().getMed());
- }
- if (left.getOrigin() != null) {
- assertEquals(left.getOrigin().getValue().getIntValue(), right.getOrigin().getValue().getIntValue());
- }
- if (left.getOriginatorId() != null) {
- assertEquals(left.getOriginatorId().getOriginator().getValue(), right.getOriginatorId().getOriginator().getValue());
- }
- if (left.getAugmentation(PathAttributes1.class) != null) {
- assertNotNull(right.getAugmentation(PathAttributes1.class));
- }
- if (left.getAugmentation(PathAttributes2.class) != null) {
- assertNotNull(right.getAugmentation(PathAttributes2.class));
- }
- if (left.getAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1.class) != null) {
- assertNotNull(right.getAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1.class));
- }
- }
-
- private void assertEqualsClusterId(List<ClusterIdentifier> left, List<ClusterIdentifier> right) {
- assertEquals(left.size(), right.size());
- for (ClusterIdentifier clusterIdentifier : left) {
- right.remove(clusterIdentifier);
- }
- assertEquals(right.size(), 0);
- }
-
- private void assertEqualsCommunities(List<Communities> left, List<Communities> right) {
- assertEquals(left.size(), right.size());
- for (Communities communities : left) {
- right.remove(communities);
- }
- assertEquals(right.size(), 0);
- }
-
- private void assertEqualsExtendedCommunities(List<ExtendedCommunities> left, List<ExtendedCommunities> right) {
- assertEquals(left.size(), right.size());
- for (ExtendedCommunity extendedCommunity : left) {
- right.remove(extendedCommunity);
- }
- assertEquals(right.size(), 0);
- }
-
- private void assertEqualsAsPath(AsPath left, AsPath right) {
- for (Segments segments : left.getSegments()) {
- right.getSegments().remove(segments);
- }
- assertTrue(right.getSegments().size() == 0);
- }
-
- private void assertEqualsNextHop(CNextHop left, CNextHop right) {
- if (left instanceof Ipv4NextHopCase) {
- assertTrue(left instanceof Ipv4NextHopCase && right instanceof Ipv4NextHopCase);
- Ipv4NextHopCase leftIpv4NextHopCase = (Ipv4NextHopCase) left;
- Ipv4NextHopCase rightIpv4NextHopCase = (Ipv4NextHopCase) right;
- assertEquals(leftIpv4NextHopCase.getIpv4NextHop().getGlobal().getValue(), rightIpv4NextHopCase.getIpv4NextHop().getGlobal().getValue());
- }
- if (left instanceof Ipv6NextHopCase) {
- assertTrue(left instanceof Ipv6NextHopCase && right instanceof Ipv6NextHopCase);
- Ipv6NextHopCase leftIpv6NextHopCase = (Ipv6NextHopCase) left;
- Ipv6NextHopCase rightIpv6NextHopCase = (Ipv6NextHopCase) right;
- assertEquals(leftIpv6NextHopCase.getIpv6NextHop().getGlobal().getValue(), rightIpv6NextHopCase.getIpv6NextHop().getGlobal().getValue());
- assertEquals(leftIpv6NextHopCase.getIpv6NextHop().getLinkLocal().getValue(), rightIpv6NextHopCase.getIpv6NextHop().getLinkLocal().getValue());
- }
- }
-
- private void assertEqualsNlri(Nlri left, Nlri right) {
- assertEquals(left.getNlri().size(), right.getNlri().size());
- for (Ipv4Prefix ipv4Prefix : left.getNlri()) {
- right.getNlri().remove(ipv4Prefix);
- }
- assertEquals(right.getNlri().size(), 0);
- }
-
- private void assertWithdrawnRoutes(WithdrawnRoutes left, WithdrawnRoutes right) {
- assertEquals(left.getWithdrawnRoutes().size(), right.getWithdrawnRoutes().size());
- for (Ipv4Prefix ipv4Prefix : left.getWithdrawnRoutes()) {
- right.getWithdrawnRoutes().remove(ipv4Prefix);
- }
- assertEquals(right.getWithdrawnRoutes().size(), 0);
- }
-
- @Test
- public void testUpdateMessageSerialization() throws BGPDocumentedException {
- for (int i = 0; i < COUNTER; i++) {
- ByteBuf byteAggregator = Unpooled.buffer();
- Update originalMessage = readUpdateMessageFromList(i);
- updateParser.serializeMessage(originalMessage, byteAggregator);
- ByteBuf reconstructed = Unpooled.buffer();
- BGPUpdateAttributesSerializationTest.updateParser.serializeMessage(originalMessage, reconstructed);
- Update serializedMessage = readUpdateMessageBytes(reconstructed);
- if (originalMessage.getNlri() != null) {
- assertEqualsNlri(originalMessage.getNlri(), serializedMessage.getNlri());
- }
- if (originalMessage.getPathAttributes() != null) {
- assertEqualsPathAttributes(originalMessage.getPathAttributes(), serializedMessage.getPathAttributes());
- }
- if (originalMessage.getWithdrawnRoutes() != null) {
- assertWithdrawnRoutes(originalMessage.getWithdrawnRoutes(), serializedMessage.getWithdrawnRoutes());
- }
- }
- }
-}
@Test
public void testOpenMessage() throws UnknownHostException, BGPParsingException, BGPDocumentedException {
final Notification open = new OpenBuilder().setMyAsNumber(100).setHoldTimer(180).setBgpIdentifier(new Ipv4Address("20.20.20.20")).setVersion(
- new ProtocolVersion((short) 4)).build();
+ new ProtocolVersion((short) 4)).build();
ByteBuf bytes = Unpooled.buffer();
ParserTest.reg.serializeMessage(open, bytes);
assertArrayEquals(openBMsg, ByteArray.getAllBytes(bytes));
@Test
public void testNotificationMsg() throws BGPParsingException, BGPDocumentedException {
Notification notMsg = new NotifyBuilder().setErrorCode(BGPError.OPT_PARAM_NOT_SUPPORTED.getCode()).setErrorSubcode(
- BGPError.OPT_PARAM_NOT_SUPPORTED.getSubcode()).setData(new byte[] { 4, 9 }).build();
+ BGPError.OPT_PARAM_NOT_SUPPORTED.getSubcode()).setData(new byte[] { 4, 9 }).build();
ByteBuf bytes = Unpooled.buffer();
ParserTest.reg.serializeMessage(notMsg, bytes);
assertArrayEquals(notificationBMsg, ByteArray.subByte(bytes.array(),0,bytes.writerIndex()));
assertArrayEquals(new byte[] { 4, 9 }, ((Notify) m).getData());
notMsg = new NotifyBuilder().setErrorCode(BGPError.CONNECTION_NOT_SYNC.getCode()).setErrorSubcode(
- BGPError.CONNECTION_NOT_SYNC.getSubcode()).build();
+ BGPError.CONNECTION_NOT_SYNC.getSubcode()).build();
bytes.clear();
final List<BgpParameters> tlvs = Lists.newArrayList();
tlvs.add(new BgpParametersBuilder().setCParameters(
- new MultiprotocolCaseBuilder().setMultiprotocolCapability(
- new MultiprotocolCapabilityBuilder().setAfi(LinkstateAddressFamily.class).setSafi(
- LinkstateSubsequentAddressFamily.class).build()).build()).build());
+ new MultiprotocolCaseBuilder().setMultiprotocolCapability(
+ new MultiprotocolCapabilityBuilder().setAfi(LinkstateAddressFamily.class).setSafi(
+ LinkstateSubsequentAddressFamily.class).build()).build()).build());
tlvs.add(new BgpParametersBuilder().setCParameters(
- new MultiprotocolCaseBuilder().setMultiprotocolCapability(
- new MultiprotocolCapabilityBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).build()).build()).build());
+ new MultiprotocolCaseBuilder().setMultiprotocolCapability(
+ new MultiprotocolCapabilityBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).build()).build()).build());
final Map<BgpTableType, Boolean> tableTypes = Maps.newHashMap();
tableTypes.put(t1, true);
tableTypes.put(t2, true);
final Open open = new OpenBuilder().setMyAsNumber(72).setHoldTimer(180).setBgpIdentifier(new Ipv4Address("172.20.160.170")).setVersion(
- new ProtocolVersion((short) 4)).setBgpParameters(tlvs).build();
+ new ProtocolVersion((short) 4)).setBgpParameters(tlvs).build();
ByteBuf result = Unpooled.buffer();
ParserTest.reg.serializeMessage(open, result);