Fixed findbug issues in BGP. 58/9358/7
authorDana Kutenicsova <dkutenic@cisco.com>
Sun, 27 Jul 2014 20:38:49 +0000 (22:38 +0200)
committerRobert Varga <rovarga@cisco.com>
Tue, 29 Jul 2014 10:05:07 +0000 (10:05 +0000)
Change-Id: I3c2fb7433682d1ef3cafb77273849a3f397fb26a
Signed-off-by: Dana Kutenicsova <dkutenic@cisco.com>
40 files changed:
bgp/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/LinkstateAttributeParser.java
bgp/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/LinkstateNlriParser.java
bgp/linkstate/src/test/java/org/opendaylight/protocol/bgp/linkstate/LinkstateAttributeParserTest.java
bgp/parser-api/src/main/java/org/opendaylight/protocol/bgp/parser/BGPDocumentedException.java
bgp/parser-api/src/test/java/org/opendaylight/protocol/bgp/parser/APITest.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/BGPNotificationMessageParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/BGPOpenMessageParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/BGPUpdateMessageParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/open/As4CapabilityHandler.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/open/GracefulCapabilityHandler.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/open/MultiProtocolCapabilityHandler.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/AdvertizedRoutesSerializer.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/AggregatorAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/AsPathAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/AtomicAggregateAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/ClusterIdAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/CommunitiesAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/CommunitiesParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/ExtendedCommunitiesAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/Ipv4NlriParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/LocalPreferenceAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/MPReachAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/MPUnreachAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/MultiExitDiscriminatorAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/NextHopAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/OriginAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/OriginatorIdAttributeParser.java
bgp/parser-impl/src/main/java/org/opendaylight/protocol/bgp/parser/impl/message/update/WithdrawnRoutesSerializer.java
bgp/parser-impl/src/test/java/org/opendaylight/protocol/bgp/parser/impl/BGPParserTest.java
bgp/parser-impl/src/test/java/org/opendaylight/protocol/bgp/parser/impl/ParserTest.java
bgp/parser-mock/src/test/java/org/opendaylight/protocol/bgp/parser/mock/BGPMessageParserMockTest.java
bgp/rib-impl/src/main/java/org/opendaylight/controller/config/yang/bgp/rib/impl/BaseBGPParserModule.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPDispatcherImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPObjectComparator.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPPeer.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPSessionImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/Ipv6AdjRIBsIn.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/StrictBGPPeerRegistry.java
bgp/testtool/src/main/java/org/opendaylight/protocol/bgp/testtool/Main.java
bgp/util/src/test/java/org/opendaylight/protocol/bgp/util/BGPHexFileParserTest.java

index 6e717436978efc3d5a7c7a55d829448feed5782c..ca0e01f90814cb69f1f12948ecf5d199290788ed 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.protocol.bgp.linkstate;
 
 import com.google.common.base.Charsets;
+import com.google.common.base.Preconditions;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Multimap;
@@ -301,7 +302,7 @@ public class LinkstateAttributeParser implements AttributeParser, AttributeSeria
                 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));
+                    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: {}.", ByteBufUtil.hexDump(value));
@@ -417,6 +418,7 @@ public class LinkstateAttributeParser implements AttributeParser, AttributeSeria
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes1 pathAttributes1 = ((PathAttributes) attribute).getAugmentation(PathAttributes1.class);
         if (pathAttributes1 == null) {
             return;
@@ -486,7 +488,7 @@ public class LinkstateAttributeParser implements AttributeParser, AttributeSeria
             writeTLV(TlvCode.SHARED_RISK_LINK_GROUP, sharedRLGBuf, byteAggregator);
         }
         if (linkAttributes.getLinkName() != null) {
-            writeTLV(TlvCode.LINK_NAME, Unpooled.wrappedBuffer(linkAttributes.getLinkName().getBytes()), byteAggregator);
+            writeTLV(TlvCode.LINK_NAME, Unpooled.wrappedBuffer(Charsets.UTF_8.encode(linkAttributes.getLinkName())), byteAggregator);
         }
         LOG.trace("Finished serializing Link Attributes");
     }
@@ -519,7 +521,7 @@ public class LinkstateAttributeParser implements AttributeParser, AttributeSeria
         }
         serializeNodeFlagBits(nodeAttributes.getNodeFlags(), byteAggregator);
         if (nodeAttributes.getDynamicHostname() != null) {
-            writeTLV(TlvCode.DYNAMIC_HOSTNAME, Unpooled.wrappedBuffer(nodeAttributes.getDynamicHostname().getBytes()), byteAggregator);
+            writeTLV(TlvCode.DYNAMIC_HOSTNAME, Unpooled.wrappedBuffer(Charsets.UTF_8.encode(nodeAttributes.getDynamicHostname())), byteAggregator);
         }
         final List<IsisAreaIdentifier> isisList = nodeAttributes.getIsisAreaId();
         if (isisList != null && !isisList.isEmpty()) {
index 474d5bdcade8eebda2aa4b53be1989a66c3d5bb7..eb538e677d6ba459cfd4dc50e5c2824022206ac3 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.protocol.bgp.linkstate;
 
+import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 import com.google.common.primitives.UnsignedBytes;
 import com.google.common.primitives.UnsignedInteger;
@@ -96,7 +97,7 @@ public final class LinkstateNlriParser implements NlriParser, NlriSerializer {
     private static final int TYPE_LENGTH = 2;
     private static final int LENGTH_SIZE = 2;
 
-    protected static final int TOPOLOGY_ID_OFFSET = 0x3fff;
+    static final int TOPOLOGY_ID_OFFSET = 0x3fff;
 
     private final boolean isVpn;
 
@@ -319,7 +320,7 @@ public final class LinkstateNlriParser implements NlriParser, NlriSerializer {
             final int restLength = length - (this.isVpn ? ROUTE_DISTINGUISHER_LENGTH : 0) - PROTOCOL_ID_LENGTH - IDENTIFIER_LENGTH
                 - TYPE_LENGTH - LENGTH_SIZE - locallength;
             LOG.trace("Restlength {}", restLength);
-            ByteBuf rest = nlri.slice(nlri.readerIndex(), restLength);
+            final ByteBuf rest = nlri.slice(nlri.readerIndex(), restLength);
             switch (type) {
             case Link:
                 parseLink(builder, rest);
@@ -487,6 +488,7 @@ public final class LinkstateNlriParser implements NlriParser, NlriSerializer {
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes pathAttributes = (PathAttributes) attribute;
         final PathAttributes1 pathAttributes1 = pathAttributes.getAugmentation(PathAttributes1.class);
         final PathAttributes2 pathAttributes2 = pathAttributes.getAugmentation(PathAttributes2.class);
@@ -504,10 +506,10 @@ public final class LinkstateNlriParser implements NlriParser, NlriSerializer {
                 }
             }
         } else if (pathAttributes2 != null) {
-            MpUnreachNlri mpUnreachNlri = pathAttributes2.getMpUnreachNlri();
+            final 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()) {
+                final DestinationLinkstateCase linkstateCase = (DestinationLinkstateCase) mpUnreachNlri.getWithdrawnRoutes().getDestinationType();
+                for (final CLinkstateDestination cLinkstateDestination : linkstateCase.getDestinationLinkstate().getCLinkstateDestination()) {
                     serializeNlri(cLinkstateDestination, byteAggregator);
                 }
             }
index 914c683ac4cd2b45b357b5edc4601003ff1cd166..0a75dcbce45d05871f550cca0da2d6028b094a44 100644 (file)
@@ -97,7 +97,7 @@ public class LinkstateAttributeParserTest {
 
         assertEquals("42.42.42.42", ls.getLocalIpv4RouterId().getValue());
         assertEquals("43.43.43.43", ls.getRemoteIpv4RouterId().getValue());
-        assertEquals(new Long(0), ls.getAdminGroup().getValue());
+        assertEquals(Long.valueOf(0L), ls.getAdminGroup().getValue());
         assertArrayEquals(new byte[] { (byte) 0x49, (byte) 0x98, (byte) 0x96, (byte) 0x80 }, ls.getMaxLinkBandwidth().getValue());
         assertArrayEquals(new byte[] { (byte) 0x46, (byte) 0x43, (byte) 0x50, (byte) 0x00 }, ls.getMaxReservableBandwidth().getValue());
         assertNotNull(ls.getUnreservedBandwidth());
index 2a1e8979d89b834137dd0d80cc6cefac351a9511..ed508fee166ce72d99da8fef3cbc1ff2e25e6464 100644 (file)
@@ -9,9 +9,7 @@ package org.opendaylight.protocol.bgp.parser;
 
 import com.google.common.base.Preconditions;
 import com.google.common.primitives.UnsignedBytes;
-
 import java.util.Arrays;
-
 import org.opendaylight.protocol.util.Values;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -92,7 +90,7 @@ public final class BGPDocumentedException extends Exception {
      * @return byte array data
      */
     public byte[] getData() {
-        return this.data;
+        return (this.data != null) ? Arrays.copyOf(this.data, this.data.length) : new byte[0];
     }
 
     public static BGPDocumentedException badMessageLength(final String message, final int length) {
index f48aec19d5a94f042f647b3105e9d66e0d56ade2..6110abb75219b988aface21f218a63b537392cb1 100644 (file)
@@ -8,11 +8,9 @@
 package org.opendaylight.protocol.bgp.parser;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
 
 import java.util.ArrayList;
 import java.util.List;
-
 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.AsNumber;
@@ -31,7 +29,7 @@ public class APITest {
         final BGPDocumentedException de = new BGPDocumentedException("Some message", BGPError.BAD_BGP_ID);
         assertEquals("Some message", de.getMessage());
         assertEquals(BGPError.BAD_BGP_ID, de.getError());
-        assertNull(de.getData());
+        assertEquals(0, de.getData().length);
 
         final BGPDocumentedException doc = BGPDocumentedException.badMessageLength("Wrong length", 5000);
         assertEquals(5000, ByteArray.bytesToInt(doc.getData()));
index e4de04969f606f38080c98e62416bb8c21fe4787..2868c09cab3fe536faf95b293d81be30d0140502 100644 (file)
@@ -8,13 +8,10 @@
 package org.opendaylight.protocol.bgp.parser.impl.message;
 
 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;
@@ -46,11 +43,11 @@ public final class BGPNotificationMessageParser implements MessageParser, Messag
      */
     @Override
     public void serializeMessage(final Notification msg, final ByteBuf bytes) {
-        Preconditions.checkArgument(msg != null, "BGP Notification message cannot be null");
+        Preconditions.checkArgument(msg != null && msg instanceof Notify, "BGP Notification message cannot be null");
         final Notify ntf = (Notify) msg;
         LOG.trace("Started serializing Notification message: {}", ntf);
 
-        byte[] data = ntf.getData();
+        final byte[] data = ntf.getData();
         final ByteBuf msgBody = Unpooled.buffer();
         msgBody.writeByte(ntf.getErrorCode());
         msgBody.writeByte(ntf.getErrorSubcode());
index e4db7cd5d55c7891b919f9bcdb50b0eb5bfc78b8..4c47d9c699d6ac07d2e6e485b1cf7826412993e6 100644 (file)
@@ -8,15 +8,12 @@
 package org.opendaylight.protocol.bgp.parser.impl.message;
 
 import com.google.common.base.Preconditions;
-
 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;
@@ -69,7 +66,7 @@ public final class BGPOpenMessageParser implements MessageParser, MessageSeriali
      */
     @Override
     public void serializeMessage(final Notification msg, final ByteBuf bytes) {
-        Preconditions.checkArgument(msg != null, "BGP Open message cannot be null");
+        Preconditions.checkArgument(msg != null && msg instanceof Open, "BGP Open message cannot be null");
         LOG.trace("Started serializing open message: {}", msg);
         final Open open = (Open) msg;
         final ByteBuf msgBody = Unpooled.buffer();
@@ -113,7 +110,7 @@ public final class BGPOpenMessageParser implements MessageParser, MessageSeriali
         if (body.readableBytes() < MIN_MSG_LENGTH) {
             throw BGPDocumentedException.badMessageLength("Open message too small.", messageLength);
         }
-        int version = body.readUnsignedByte();
+        final int version = body.readUnsignedByte();
         if (version != BGP_VERSION) {
             throw new BGPDocumentedException("BGP Protocol version " + version + " not supported.", BGPError.VERSION_NOT_SUPPORTED);
         }
index 9732c62b28fba956034a5c394c7aa61a998b40f3..b0c266fe73920c80ffd7edf32d8cccd0d2303d65 100644 (file)
@@ -9,13 +9,10 @@ package org.opendaylight.protocol.bgp.parser.impl.message;
 
 
 import com.google.common.base.Preconditions;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufUtil;
 import io.netty.buffer.Unpooled;
-
 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;
@@ -97,14 +94,14 @@ public class BGPUpdateMessageParser implements MessageParser, MessageSerializer
         if (nlri != null && !nlri.isEmpty()) {
             eventBuilder.setNlri(new NlriBuilder().setNlri(nlri).build());
         }
-        Update msg = eventBuilder.build();
+        final Update msg = eventBuilder.build();
         LOG.debug("BGP Update message was parsed {}.", msg);
         return msg;
     }
 
     @Override
     public void serializeMessage(final Notification message, final ByteBuf bytes) {
-        Preconditions.checkArgument(message != null, "BGPUpdate message cannot be null");
+        Preconditions.checkArgument(message != null && message instanceof Update, "BGPUpdate message cannot be null");
         LOG.trace("Started serializing update message: {}", message);
         final Update update = (Update) message;
 
index 9e879b11db7b381fd4e9dbe67b5238742d670e55..5cd7bd1ec1731a4d97fb0584f1b8f4645b9963f5 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.open;
 
+import com.google.common.base.Preconditions;
 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;
@@ -31,7 +31,8 @@ public final class As4CapabilityHandler implements CapabilityParser, CapabilityS
     }
 
     @Override
-    public void serializeCapability(final CParameters capability, ByteBuf bytes) {
+    public void serializeCapability(final CParameters capability, final ByteBuf bytes) {
+        Preconditions.checkArgument(capability instanceof As4BytesCase);
         CapabilityUtil.formatCapability(CODE, putAS4BytesParameterValue((As4BytesCase) capability),bytes);
     }
 
index 21fbce54cb5506d9f825804a602376497e1637eb..8c980c1c035abf52febf5a43ca8de53dc1c71661 100644 (file)
@@ -64,7 +64,8 @@ public final class GracefulCapabilityHandler implements CapabilityParser, Capabi
     }
 
     @Override
-    public void serializeCapability(final CParameters capability, ByteBuf byteAggregator) {
+    public void serializeCapability(final CParameters capability, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(capability instanceof GracefulRestartCase);
         final GracefulRestartCapability grace = ((GracefulRestartCase) capability).getGracefulRestartCapability();
         final List<Tables> tables = grace.getTables();
 
index 6d88ef4ae88690c23e2cb390822fb1cc4b6f7a09..1990c2d98260ddf015ff3cce600aa082de198240 100644 (file)
@@ -8,10 +8,8 @@
 package org.opendaylight.protocol.bgp.parser.impl.message.open;
 
 import com.google.common.base.Preconditions;
-
 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;
@@ -58,7 +56,8 @@ public final class MultiProtocolCapabilityHandler implements CapabilityParser, C
     }
 
     @Override
-    public void serializeCapability(final CParameters capability, ByteBuf byteAggregator) {
+    public void serializeCapability(final CParameters capability, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(capability instanceof MultiprotocolCase);
         final MultiprotocolCase mp = (MultiprotocolCase) capability;
         final ByteBuf capBuffer = Unpooled.buffer();
         final Class<? extends AddressFamily> afi = mp.getMultiprotocolCapability().getAfi();
index 45af186e4f67fcd08e4d10e3b58466ae25c74656..a6f584082babb8f1e8460cb3fb6e8e1c802bd035 100644 (file)
@@ -7,8 +7,8 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
+import com.google.common.base.Preconditions;
 import io.netty.buffer.ByteBuf;
-
 import org.opendaylight.protocol.bgp.parser.spi.NlriSerializer;
 import org.opendaylight.protocol.util.Ipv4Util;
 import org.opendaylight.protocol.util.Ipv6Util;
@@ -26,6 +26,7 @@ public class AdvertizedRoutesSerializer implements NlriSerializer {
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes1 pathAttributes1 = ((PathAttributes) attribute).getAugmentation(PathAttributes1.class);
         if (pathAttributes1 == null) {
             return;
@@ -34,7 +35,7 @@ public class AdvertizedRoutesSerializer implements NlriSerializer {
         if (mpReachNlri == null) {
             return;
         }
-        AdvertizedRoutes routes = mpReachNlri.getAdvertizedRoutes();
+        final AdvertizedRoutes routes = mpReachNlri.getAdvertizedRoutes();
         if (routes.getDestinationType() instanceof DestinationIpv4Case) {
             final DestinationIpv4Case destinationIpv4Case = (DestinationIpv4Case) routes.getDestinationType();
             for (final Ipv4Prefix ipv4Prefix : destinationIpv4Case.getDestinationIpv4().getIpv4Prefixes()) {
index a382cb4836e34a3e49369afcd77ed75fbe59924a..253174775d340d483142592306a5b0eb84e7e796 100644 (file)
@@ -8,10 +8,8 @@
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
 import com.google.common.base.Preconditions;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeUtil;
@@ -51,6 +49,7 @@ public final class AggregatorAttributeParser implements AttributeParser, Attribu
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes pathAttributes = (PathAttributes) attribute;
         final Aggregator aggregator = pathAttributes.getAggregator();
         if (aggregator == null) {
index 0d061cab5c139f01f8a36d592744e73c7389e9c8..fe860cb58a896cbc7211317befee95df9e005190 100644 (file)
@@ -10,12 +10,9 @@ package org.opendaylight.protocol.bgp.parser.impl.message.update;
 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.Unpooled;
-
 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;
@@ -74,13 +71,13 @@ public final class AsPathAttributeParser implements AttributeParser, AttributeSe
 
             if (segmentType == SegmentType.AS_SEQUENCE) {
                 final List<AsSequence> numbers = AsPathSegmentParser.parseAsSequence(refCache, count, buffer.slice(buffer.readerIndex(),
-                        count * AsPathSegmentParser.AS_NUMBER_LENGTH));
+                    count * AsPathSegmentParser.AS_NUMBER_LENGTH));
                 ases.add(new SegmentsBuilder().setCSegment(
-                        new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(numbers).build()).build()).build());
+                    new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(numbers).build()).build()).build());
                 isSequence = true;
             } else {
                 final List<AsNumber> list = AsPathSegmentParser.parseAsSet(refCache, count, buffer.slice(buffer.readerIndex(), count
-                        * AsPathSegmentParser.AS_NUMBER_LENGTH));
+                    * AsPathSegmentParser.AS_NUMBER_LENGTH));
                 ases.add(new SegmentsBuilder().setCSegment(new ASetCaseBuilder().setASet(new ASetBuilder().setAsSet(list).build()).build()).build());
 
             }
@@ -100,19 +97,20 @@ public final class AsPathAttributeParser implements AttributeParser, AttributeSe
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes pathAttributes = (PathAttributes) attribute;
         final AsPath asPath = pathAttributes.getAsPath();
         if (asPath == null) {
             return;
         }
         final ByteBuf segmentsBuffer = Unpooled.buffer();
-        if (asPath.getSegments().size()>0) {
-            for (Segments segments : asPath.getSegments()) {
+        if (asPath.getSegments() != null) {
+            for (final Segments segments : asPath.getSegments()) {
                 if (segments.getCSegment() instanceof AListCase) {
-                    AListCase listCase = (AListCase) segments.getCSegment();
+                    final AListCase listCase = (AListCase) segments.getCSegment();
                     AsPathSegmentParser.serializeAsSequence(listCase, segmentsBuffer);
                 } else if (segments.getCSegment() instanceof ASetCase) {
-                    ASetCase set = (ASetCase) segments.getCSegment();
+                    final ASetCase set = (ASetCase) segments.getCSegment();
                     AsPathSegmentParser.serializeAsSet(set, segmentsBuffer);
                 } else {
                     LOG.warn("Segment class is neither AListCase nor ASetCase.");
index 413a7b2572bf99b945ae0c78b50251d103e980cf..f2387ceb09dda92e2809f5f616faa8a847733a04 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
+import com.google.common.base.Preconditions;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeUtil;
@@ -29,6 +29,7 @@ public final class AtomicAggregateAttributeParser implements AttributeParser,Att
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes pathAttributes = (PathAttributes) attribute;
         if (pathAttributes.getAtomicAggregate() == null) {
             return;
index 6faf68d97d64e31d41c06876e04696830ae66456..81d2958972d7baf8902d50fd2697ca87ea64007d 100644 (file)
@@ -7,13 +7,11 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
+import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import java.util.List;
-
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeUtil;
@@ -28,7 +26,6 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 public final class ClusterIdAttributeParser implements AttributeParser, AttributeSerializer {
 
     public static final int TYPE = 10;
-    public static final int ATTR_LENGTH = 4;
 
     @Override
     public void parseAttribute(final ByteBuf buffer, final PathAttributesBuilder builder) {
@@ -41,6 +38,7 @@ public final class ClusterIdAttributeParser implements AttributeParser, Attribut
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final ClusterId cid = ((PathAttributes) attribute).getClusterId();
         if (cid == null) {
             return;
index 9e513bc4eef0b86852a0c0b7288eda1b18d36229..b8a04471e5140c2d0fa27612ab596151a9c9293a 100644 (file)
@@ -26,7 +26,6 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 public final class CommunitiesAttributeParser implements AttributeParser, AttributeSerializer {
 
     public static final int TYPE = 8;
-    public static final int ATTR_LENGTH = 4;
 
     private final ReferenceCache refCache;
 
@@ -39,7 +38,7 @@ public final class CommunitiesAttributeParser implements AttributeParser, Attrib
         final List<Communities> set = Lists.newArrayList();
         while (buffer.isReadable()) {
             set.add((Communities) CommunitiesParser.parseCommunity(this.refCache, buffer.slice(buffer.readerIndex(),
-                    CommunitiesParser.COMMUNITY_LENGTH)));
+                CommunitiesParser.COMMUNITY_LENGTH)));
             buffer.skipBytes(CommunitiesParser.COMMUNITY_LENGTH);
         }
         builder.setCommunities(set);
@@ -47,6 +46,7 @@ public final class CommunitiesAttributeParser implements AttributeParser, Attrib
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes pathAttributes = (PathAttributes) attribute;
         final List<Communities> communities = pathAttributes.getCommunities();
         if (communities == null || communities.isEmpty()) {
index 2b8358e936be5495b4b9b5bfc907160907f0c2c3..84a2685aa5275cf3dc1e68098a6c9bd88a364a0e 100644 (file)
@@ -36,31 +36,29 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.type
  */
 public final class CommunitiesParser {
 
-    protected static final int EXTENDED_COMMUNITY_LENGTH = 8;
-
-    protected static final int COMMUNITY_LENGTH = 4;
+    public static final int COMMUNITY_LENGTH = 4;
 
     private static final int AS_LOCAL_ADMIN_LENGTH = 4;
 
     private static final int INET_LOCAL_ADMIN_LENGTH = 2;
 
-    protected static final short AS_TYPE_TRANS = 0;
+    private static final short AS_TYPE_TRANS = 0;
 
-    protected static final short AS_TYPE_NON_TRANS = 40;
+    private static final short AS_TYPE_NON_TRANS = 40;
 
-    protected static final short INET_TYPE_TRANS = 1;
+    private static final short INET_TYPE_TRANS = 1;
 
-    protected static final short INET_TYPE_NON_TRANS = 41;
+    private static final short INET_TYPE_NON_TRANS = 41;
 
-    protected static final short OPAQUE_TYPE_TRANS = 3;
+    private static final short OPAQUE_TYPE_TRANS = 3;
 
-    protected static final short OPAQUE_TYPE_NON_TRANS = 43;
+    private static final short OPAQUE_TYPE_NON_TRANS = 43;
 
-    protected static final short ROUTE_TYPE_ONLY = 2;
+    private static final short ROUTE_TYPE_ONLY = 2;
 
-    protected static final short ROUTE_TARGET_SUBTYPE = 2;
+    private static final short ROUTE_TARGET_SUBTYPE = 2;
 
-    protected static final short ROUTE_ORIGIN_SUBTYPE = 3;
+    private static final short ROUTE_ORIGIN_SUBTYPE = 3;
 
     private static final byte[] NO_EXPORT = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x01 };
 
@@ -85,7 +83,7 @@ public final class CommunitiesParser {
         if (buffer.readableBytes() != COMMUNITY_LENGTH) {
             throw new BGPDocumentedException("Community with wrong length: " + buffer.readableBytes(), BGPError.OPT_ATTR_ERROR);
         }
-        byte[] body = ByteArray.getBytes(buffer, COMMUNITY_LENGTH);
+        final byte[] body = ByteArray.getBytes(buffer, COMMUNITY_LENGTH);
         if (Arrays.equals(body, NO_EXPORT)) {
             return CommunityUtil.NO_EXPORT;
         } else if (Arrays.equals(body, NO_ADVERTISE)) {
index 4dc7ded5c35be6fd6dc8e6eb8a356ebc83619b5e..1127ab039832c65de14ca880cdce9d78c8460ec5 100644 (file)
@@ -8,9 +8,9 @@
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
 import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
+import java.util.ArrayList;
 import java.util.List;
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
@@ -32,6 +32,8 @@ public final class ExtendedCommunitiesAttributeParser implements AttributeParser
 
     public static final int TYPE = 16;
 
+    private static final int EXTENDED_COMMUNITY_LENGTH = 8;
+
     private final ReferenceCache refCache;
 
     public ExtendedCommunitiesAttributeParser(final ReferenceCache refCache) {
@@ -40,10 +42,10 @@ public final class ExtendedCommunitiesAttributeParser implements AttributeParser
 
     @Override
     public void parseAttribute(final ByteBuf buffer, final PathAttributesBuilder builder) throws BGPDocumentedException {
-        final List<ExtendedCommunities> set = Lists.newArrayList();
+        final List<ExtendedCommunities> set = new ArrayList<>();
         while (buffer.isReadable()) {
-            final ExtendedCommunities comm = CommunitiesParser.parseExtendedCommunity(this.refCache, buffer.slice(buffer.readerIndex(), CommunitiesParser.EXTENDED_COMMUNITY_LENGTH));
-            buffer.skipBytes(CommunitiesParser.EXTENDED_COMMUNITY_LENGTH);
+            final ExtendedCommunities comm = CommunitiesParser.parseExtendedCommunity(this.refCache, buffer.slice(buffer.readerIndex(), EXTENDED_COMMUNITY_LENGTH));
+            buffer.skipBytes(EXTENDED_COMMUNITY_LENGTH);
             set.add(comm);
         }
         builder.setExtendedCommunities(set);
@@ -51,6 +53,7 @@ public final class ExtendedCommunitiesAttributeParser implements AttributeParser
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes pathAttributes = (PathAttributes) attribute;
         final List<ExtendedCommunities> communitiesList = pathAttributes.getExtendedCommunities();
         if (communitiesList == null || communitiesList.isEmpty()) {
index 237491904145c90058d6933380a50161143d8793..fb8511885663e6bd86476b35512646b6b3cce9ae 100644 (file)
@@ -7,13 +7,14 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
+import com.google.common.base.Preconditions;
 import io.netty.buffer.ByteBuf;
-
 import org.opendaylight.protocol.bgp.parser.spi.NlriSerializer;
 import org.opendaylight.protocol.util.ByteArray;
 import org.opendaylight.protocol.util.Ipv4Util;
 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.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.multiprotocol.rev130919.destination.destination.type.DestinationIpv4Case;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.destination.destination.type.DestinationIpv4CaseBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.destination.destination.type.destination.ipv4._case.DestinationIpv4Builder;
@@ -24,11 +25,12 @@ public final class Ipv4NlriParser extends IpNlriParser implements NlriSerializer
     @Override
     protected DestinationIpv4Case parseNlri(final ByteBuf nlri) {
         return new DestinationIpv4CaseBuilder().setDestinationIpv4(
-                new DestinationIpv4Builder().setIpv4Prefixes(Ipv4Util.prefixListForBytes(ByteArray.readAllBytes(nlri))).build()).build();
+            new DestinationIpv4Builder().setIpv4Prefixes(Ipv4Util.prefixListForBytes(ByteArray.readAllBytes(nlri))).build()).build();
     }
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final Nlri nlri = (Nlri) attribute;
         for (final Ipv4Prefix ipv4Prefix : nlri.getNlri()) {
             byteAggregator.writeBytes(Ipv4Util.bytesForPrefix(ipv4Prefix));
index 004b27554000000041f7563e9733e4a38b751fca..5fbf2539463fe029b50001972b75aa1ae854fcdc 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
+import com.google.common.base.Preconditions;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeUtil;
@@ -22,7 +22,6 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 public final class LocalPreferenceAttributeParser implements AttributeParser,AttributeSerializer {
 
     public static final int TYPE = 5;
-    public static final int LOCAL_PREFS_LENGTH = 4;
 
     @Override
     public void parseAttribute(final ByteBuf buffer, final PathAttributesBuilder builder) {
@@ -31,6 +30,7 @@ public final class LocalPreferenceAttributeParser implements AttributeParser,Att
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final LocalPref lp = ((PathAttributes) attribute).getLocalPref();
         if (lp == null) {
             return;
index 43ceceb76a739bc75d2ddf324f065f0dbc87b867..b73d1507cc14a27a18f4256b470478e30aedb943 100644 (file)
@@ -8,10 +8,8 @@
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
 import com.google.common.base.Preconditions;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
@@ -31,7 +29,7 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 public final class MPReachAttributeParser implements AttributeParser, AttributeSerializer {
 
     public static final int TYPE = 14;
-    public static final int ATTR_LENGTH = 2;
+
     private final NlriRegistry reg;
 
     public MPReachAttributeParser(final NlriRegistry reg) {
@@ -50,6 +48,7 @@ public final class MPReachAttributeParser implements AttributeParser, AttributeS
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes pathAttributes = (PathAttributes) attribute;
         final PathAttributes1 pathAttributes1 = pathAttributes.getAugmentation(PathAttributes1.class);
         if (pathAttributes1 == null) {
index 4ed7fb2dd492cb38fc89f419d5d11432c14a3d84..38fc08913c3ba05994e267c07cc95a40106159ff 100644 (file)
@@ -8,10 +8,8 @@
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
 import com.google.common.base.Preconditions;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
@@ -29,7 +27,6 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 
 public final class MPUnreachAttributeParser implements AttributeParser, AttributeSerializer {
     public static final int TYPE = 15;
-    public static final int MAX_ATTR_LENGTH_FOR_SINGLE_BYTE = 127;
 
     private final NlriRegistry reg;
 
@@ -49,6 +46,7 @@ public final class MPUnreachAttributeParser implements AttributeParser, Attribut
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final PathAttributes pathAttributes = (PathAttributes) attribute;
         final PathAttributes2 pathAttributes2 = pathAttributes.getAugmentation(PathAttributes2.class);
         if (pathAttributes2 == null) {
index 52a312e6e0e02e5571057836c516b45e866ee305..8f0821b3a0f1fe2abf02a9aee3e191caa7ab010e 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
+import com.google.common.base.Preconditions;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeUtil;
@@ -30,6 +30,7 @@ public final class MultiExitDiscriminatorAttributeParser implements AttributePar
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final MultiExitDisc multiExitDisc = ((PathAttributes) attribute).getMultiExitDisc();
         if (multiExitDisc == null) {
             return;
index 3e23db1abb1bb7ca15bde6625bcf50f67165b9c2..a043796736be88fd85d115e4de0d24fa10ea5885 100644 (file)
@@ -8,10 +8,8 @@
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
 import com.google.common.base.Preconditions;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import org.opendaylight.bgp.concepts.NextHopUtil;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
@@ -34,6 +32,7 @@ public final class NextHopAttributeParser implements AttributeParser, AttributeS
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final CNextHop cNextHop = ((PathAttributes) attribute).getCNextHop();
         if (cNextHop == null) {
             return;
index b06e20bde11ee641b3da34d74b678eea9226bb96..3e570fb840398fc0f117b4bfd174e5eed7a87152 100644 (file)
@@ -7,11 +7,10 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
+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.BGPError;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
@@ -27,11 +26,10 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 public final class OriginAttributeParser implements AttributeParser, AttributeSerializer {
 
     public static final int TYPE = 1;
-    public static final int ATTR_LENGTH = 1;
 
     @Override
     public void parseAttribute(final ByteBuf buffer, final PathAttributesBuilder builder) throws BGPDocumentedException {
-        byte rawOrigin = buffer.readByte();
+        final byte rawOrigin = buffer.readByte();
         final BgpOrigin borigin = BgpOrigin.forValue(UnsignedBytes.toInt(rawOrigin));
         if (borigin == null) {
             throw new BGPDocumentedException("Unknown Origin type.", BGPError.ORIGIN_ATTR_NOT_VALID, new byte[] { (byte) 0x01, (byte) 0x01, rawOrigin} );
@@ -41,6 +39,7 @@ public final class OriginAttributeParser implements AttributeParser, AttributeSe
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final Origin origin = ((PathAttributes) attribute).getOrigin();
         if (origin == null) {
             return;
index 3520d66c5fe838dbeaf15e578a5f7bae56eabfb2..9cdc4409444a7fedce7353ea68a3d501e04567a9 100644 (file)
@@ -8,10 +8,8 @@
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
 import com.google.common.base.Preconditions;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
 import org.opendaylight.protocol.bgp.parser.spi.AttributeUtil;
@@ -34,6 +32,7 @@ public final class OriginatorIdAttributeParser implements AttributeParser,Attrib
 
     @Override
     public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
         final OriginatorId originator = ((PathAttributes) attribute).getOriginatorId();
         if (originator == null) {
             return;
index 7d3245f0ad7b7dcba603a77b2c542bc30d8d3632..fc22de88c66f8b08def80a87ed29ac1a32ff8d97 100644 (file)
@@ -7,8 +7,8 @@
  */
 package org.opendaylight.protocol.bgp.parser.impl.message.update;
 
+import com.google.common.base.Preconditions;
 import io.netty.buffer.ByteBuf;
-
 import org.opendaylight.protocol.bgp.parser.spi.NlriSerializer;
 import org.opendaylight.protocol.util.Ipv4Util;
 import org.opendaylight.protocol.util.Ipv6Util;
@@ -25,16 +25,17 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 public class WithdrawnRoutesSerializer implements NlriSerializer {
 
     @Override
-    public void serializeAttribute(DataObject attribute, ByteBuf byteAggregator) {
-        PathAttributes2 pathAttributes2 = ((PathAttributes) attribute).getAugmentation(PathAttributes2.class);
+    public void serializeAttribute(final DataObject attribute, final ByteBuf byteAggregator) {
+        Preconditions.checkArgument(attribute instanceof PathAttributes, "Attribute parameter is not a PathAttribute object.");
+        final PathAttributes2 pathAttributes2 = ((PathAttributes) attribute).getAugmentation(PathAttributes2.class);
         if (pathAttributes2 == null) {
             return;
         }
-        MpUnreachNlri mpUnreachNlri = pathAttributes2.getMpUnreachNlri();
+        final MpUnreachNlri mpUnreachNlri = pathAttributes2.getMpUnreachNlri();
         if (mpUnreachNlri == null) {
             return;
         }
-        WithdrawnRoutes routes = mpUnreachNlri.getWithdrawnRoutes();
+        final WithdrawnRoutes routes = mpUnreachNlri.getWithdrawnRoutes();
         if (routes != null) {
             if (routes.getDestinationType() instanceof DestinationIpv4Case) {
                 final DestinationIpv4Case destinationIpv4Case = (DestinationIpv4Case)routes.getDestinationType();
index 0c5ceae8fa669b9ae5a36f46c23eb4a81243cf34..48758a8c5c229ede8a6ed0fe6d97705bc9d78401 100644 (file)
@@ -138,26 +138,27 @@ public class BGPParserTest {
     @BeforeClass
     public static void setUp() throws Exception {
         updateParser = new BGPUpdateMessageParser(ServiceLoaderBGPExtensionProviderContext.getSingletonInstance().getAttributeRegistry());
-
         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);
+            try (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());
+                is.close();
             }
-            bis.flush();
-
-            inputBytes.add(bis.toByteArray());
         }
     }
 
+
     @Test
     public void testResource() {
         assertNotNull(inputBytes);
@@ -221,10 +222,10 @@ public class BGPParserTest {
         final List<AsSequence> asnums = Lists.newArrayList(new AsSequenceBuilder().setAs(new AsNumber(65002L)).build());
         final List<Segments> asPath = Lists.newArrayList();
         asPath.add(new SegmentsBuilder().setCSegment(
-                new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(asnums).build()).build()).build());
+            new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(asnums).build()).build()).build());
 
         final Ipv4NextHopCase nextHop = new Ipv4NextHopCaseBuilder().setIpv4NextHop(
-                new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("10.0.0.2")).build()).build();
+            new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("10.0.0.2")).build()).build();
 
         final List<Communities> comms = Lists.newArrayList();
         comms.add((Communities) CommunityUtil.NO_EXPORT);
@@ -356,13 +357,13 @@ public class BGPParserTest {
         final List<AsSequence> asnums = Lists.newArrayList(new AsSequenceBuilder().setAs(new AsNumber(65001L)).build());
         final List<Segments> asPath = Lists.newArrayList();
         asPath.add(new SegmentsBuilder().setCSegment(
-                new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(asnums).build()).build()).build());
+            new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(asnums).build()).build()).build());
 
         final Ipv6NextHopCase nextHop = new Ipv6NextHopCaseBuilder().setIpv6NextHop(
-                new Ipv6NextHopBuilder().setGlobal(new Ipv6Address("2001:db8::1")).setLinkLocal(new Ipv6Address("fe80::c001:bff:fe7e:0")).build()).build();
+            new Ipv6NextHopBuilder().setGlobal(new Ipv6Address("2001:db8::1")).setLinkLocal(new Ipv6Address("fe80::c001:bff:fe7e:0")).build()).build();
 
         final List<ClusterIdentifier> clusters = Lists.newArrayList(new ClusterIdentifier(new Ipv4Address("1.2.3.4")),
-                new ClusterIdentifier(new Ipv4Address("5.6.7.8")));
+            new ClusterIdentifier(new Ipv4Address("5.6.7.8")));
 
         // check path attributes
 
@@ -390,11 +391,11 @@ public class BGPParserTest {
         mpBuilder.setSafi(UnicastSubsequentAddressFamily.class);
         mpBuilder.setCNextHop(nextHop);
         mpBuilder.setAdvertizedRoutes(new AdvertizedRoutesBuilder().setDestinationType(
-                new DestinationIpv6CaseBuilder().setDestinationIpv6(new DestinationIpv6Builder().setIpv6Prefixes(prefs).build()).build()).build());
+            new DestinationIpv6CaseBuilder().setDestinationIpv6(new DestinationIpv6Builder().setIpv6Prefixes(prefs).build()).build()).build());
 
         paBuilder.addAugmentation(PathAttributes1.class, new PathAttributes1Builder().setMpReachNlri(mpBuilder.build()).build());
         assertEquals(paBuilder.getAugmentation(PathAttributes1.class).getMpReachNlri(),
-                attrs.getAugmentation(PathAttributes1.class).getMpReachNlri());
+            attrs.getAugmentation(PathAttributes1.class).getMpReachNlri());
 
         // check API message
 
@@ -467,14 +468,14 @@ public class BGPParserTest {
         final List<AsSequence> asnums = Lists.newArrayList(new AsSequenceBuilder().setAs(new AsNumber(30L)).build());
         final List<Segments> asPath = Lists.newArrayList();
         asPath.add(new SegmentsBuilder().setCSegment(
-                new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(asnums).build()).build()).build());
+            new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(asnums).build()).build()).build());
         asPath.add(new SegmentsBuilder().setCSegment(
-                new ASetCaseBuilder().setASet(new ASetBuilder().setAsSet(Lists.newArrayList(new AsNumber(10L), new AsNumber(20L))).build()).build()).build());
+            new ASetCaseBuilder().setASet(new ASetBuilder().setAsSet(Lists.newArrayList(new AsNumber(10L), new AsNumber(20L))).build()).build()).build());
 
         final Aggregator aggregator = new AggregatorBuilder().setAsNumber(new AsNumber((long) 30)).setNetworkAddress(
-                new Ipv4Address("10.0.0.9")).build();
+            new Ipv4Address("10.0.0.9")).build();
         final Ipv4NextHopCase nextHop = new Ipv4NextHopCaseBuilder().setIpv4NextHop(
-                new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("10.0.0.9")).build()).build();
+            new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("10.0.0.9")).build()).build();
 
         // check path attributes
         final PathAttributes attrs = message.getPathAttributes();
@@ -566,13 +567,13 @@ public class BGPParserTest {
 
         // attributes
         final Ipv4NextHopCase nextHop = new Ipv4NextHopCaseBuilder().setIpv4NextHop(
-                new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("3.3.3.3")).build()).build();
+            new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("3.3.3.3")).build()).build();
 
         final List<ExtendedCommunities> comms = Lists.newArrayList();
         comms.add(new ExtendedCommunitiesBuilder().setCommType((short) 1).setExtendedCommunity(
-                new Inet4SpecificExtendedCommunityCaseBuilder().setInet4SpecificExtendedCommunity(
-                        new Inet4SpecificExtendedCommunityBuilder().setTransitive(false).setGlobalAdministrator(
-                                new Ipv4Address("192.168.1.0")).setLocalAdministrator(new byte[] { 0x12, 0x34 }).build()).build()).build());
+            new Inet4SpecificExtendedCommunityCaseBuilder().setInet4SpecificExtendedCommunity(
+                new Inet4SpecificExtendedCommunityBuilder().setTransitive(false).setGlobalAdministrator(
+                    new Ipv4Address("192.168.1.0")).setLocalAdministrator(new byte[] { 0x12, 0x34 }).build()).build()).build());
 
         final List<Segments> asPath = Lists.newArrayList();
 
@@ -629,7 +630,7 @@ public class BGPParserTest {
 
         // check API message
         final Update expectedMessage = new UpdateBuilder().setWithdrawnRoutes(
-                new WithdrawnRoutesBuilder().setWithdrawnRoutes(prefs).build()).build();
+            new WithdrawnRoutesBuilder().setWithdrawnRoutes(prefs).build()).build();
 
         assertEquals(expectedMessage.getWithdrawnRoutes(), message.getWithdrawnRoutes());
 
@@ -884,15 +885,15 @@ public class BGPParserTest {
         assertNull(message.getWithdrawnRoutes());
 
         final Ipv4NextHopCase nextHop = new Ipv4NextHopCaseBuilder().setIpv4NextHop(
-                new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("25.25.25.1")).build()).build();
+            new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("25.25.25.1")).build()).build();
 
         final List<Segments> asPath = Lists.newArrayList();
 
         final LocalNodeDescriptorsBuilder lndBuilder = new LocalNodeDescriptorsBuilder().setAsNumber(new AsNumber((long) 100)).setDomainId(
-                new DomainIdentifier(0x19191901L)).setAreaId(new AreaIdentifier(0L));
+            new DomainIdentifier(0x19191901L)).setAreaId(new AreaIdentifier(0L));
 
         final RemoteNodeDescriptorsBuilder rndBuilder = new RemoteNodeDescriptorsBuilder().setAsNumber(new AsNumber((long) 100)).setDomainId(
-                new DomainIdentifier(0x19191901L)).setAreaId(new AreaIdentifier(0L));
+            new DomainIdentifier(0x19191901L)).setAreaId(new AreaIdentifier(0L));
 
         final CLinkstateDestinationBuilder clBuilder = new CLinkstateDestinationBuilder();
         clBuilder.setIdentifier(new Identifier(BigInteger.ONE));
@@ -907,30 +908,30 @@ public class BGPParserTest {
 
         final List<CLinkstateDestination> linkstates = Lists.newArrayList();
         clBuilder.setLocalNodeDescriptors(lndBuilder.setCRouterIdentifier(
-                new OspfPseudonodeCaseBuilder().setOspfPseudonode(
-                        new OspfPseudonodeBuilder().setOspfRouterId(0x03030304L).setLanInterface(new OspfInterfaceIdentifier(0x0b0b0b03L)).build()).build()).build());
+            new OspfPseudonodeCaseBuilder().setOspfPseudonode(
+                new OspfPseudonodeBuilder().setOspfRouterId(0x03030304L).setLanInterface(new OspfInterfaceIdentifier(0x0b0b0b03L)).build()).build()).build());
         clBuilder.setRemoteNodeDescriptors(rndBuilder.setCRouterIdentifier(
-                new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x03030304L).build()).build()).build());
+            new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x03030304L).build()).build()).build());
         clBuilder.setLinkDescriptors(new LinkDescriptorsBuilder().setIpv4InterfaceAddress(
-                new Ipv4InterfaceIdentifier(new Ipv4Address("11.11.11.3"))).build());
+            new Ipv4InterfaceIdentifier(new Ipv4Address("11.11.11.3"))).build());
         linkstates.add(clBuilder.build());
 
         clBuilder.setLocalNodeDescriptors(lndBuilder.setCRouterIdentifier(
-                new OspfPseudonodeCaseBuilder().setOspfPseudonode(
-                        new OspfPseudonodeBuilder().setOspfRouterId(0x03030304L).setLanInterface(new OspfInterfaceIdentifier(0x0b0b0b03L)).build()).build()).build());
+            new OspfPseudonodeCaseBuilder().setOspfPseudonode(
+                new OspfPseudonodeBuilder().setOspfRouterId(0x03030304L).setLanInterface(new OspfInterfaceIdentifier(0x0b0b0b03L)).build()).build()).build());
         clBuilder.setRemoteNodeDescriptors(rndBuilder.setCRouterIdentifier(
-                new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x01010102L).build()).build()).build());
+            new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x01010102L).build()).build()).build());
         clBuilder.setLinkDescriptors(new LinkDescriptorsBuilder().setIpv4InterfaceAddress(
-                new Ipv4InterfaceIdentifier(new Ipv4Address("11.11.11.1"))).build());
+            new Ipv4InterfaceIdentifier(new Ipv4Address("11.11.11.1"))).build());
         linkstates.add(clBuilder.build());
 
         clBuilder.setLocalNodeDescriptors(lndBuilder.setCRouterIdentifier(
-                new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x01010102L).build()).build()).build());
+            new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x01010102L).build()).build()).build());
         clBuilder.setRemoteNodeDescriptors(rndBuilder.setCRouterIdentifier(
-                new OspfPseudonodeCaseBuilder().setOspfPseudonode(
-                        new OspfPseudonodeBuilder().setOspfRouterId(0x03030304L).setLanInterface(new OspfInterfaceIdentifier(0x0b0b0b03L)).build()).build()).build());
+            new OspfPseudonodeCaseBuilder().setOspfPseudonode(
+                new OspfPseudonodeBuilder().setOspfRouterId(0x03030304L).setLanInterface(new OspfInterfaceIdentifier(0x0b0b0b03L)).build()).build()).build());
         clBuilder.setLinkDescriptors(new LinkDescriptorsBuilder().setIpv4InterfaceAddress(
-                new Ipv4InterfaceIdentifier(new Ipv4Address("11.11.11.1"))).build());
+            new Ipv4InterfaceIdentifier(new Ipv4Address("11.11.11.1"))).build());
         linkstates.add(clBuilder.build());
 
         lsBuilder.setMpReachNlri(mpBuilder.build());
@@ -958,7 +959,7 @@ public class BGPParserTest {
         dBuilder.setCLinkstateDestination(linkstates);
 
         mpBuilder.setAdvertizedRoutes(new AdvertizedRoutesBuilder().setDestinationType(
-                new DestinationLinkstateCaseBuilder().setDestinationLinkstate(dBuilder.build()).build()).build());
+            new DestinationLinkstateCaseBuilder().setDestinationLinkstate(dBuilder.build()).build()).build());
         lsBuilder.setMpReachNlri(mpBuilder.build());
 
         paBuilder.addAugmentation(PathAttributes1.class, lsBuilder.build());
@@ -966,15 +967,15 @@ public class BGPParserTest {
         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1Builder lsAttrBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1Builder();
 
         lsAttrBuilder.setLinkstatePathAttribute(new LinkstatePathAttributeBuilder().setLinkStateAttribute(
-                new LinkAttributesCaseBuilder().setLinkAttributes(new LinkAttributesBuilder().setMetric(new Metric(1L)).build()).build()).build());
+            new LinkAttributesCaseBuilder().setLinkAttributes(new LinkAttributesBuilder().setMetric(new Metric(1L)).build()).build()).build());
         paBuilder.addAugmentation(
-                org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1.class,
-                lsAttrBuilder.build());
+            org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1.class,
+            lsAttrBuilder.build());
 
         assertEquals(
-                lsAttrBuilder.build().getLinkstatePathAttribute(),
-                attrs.getAugmentation(
-                        org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1.class).getLinkstatePathAttribute());
+            lsAttrBuilder.build().getLinkstatePathAttribute(),
+            attrs.getAugmentation(
+                org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev131125.PathAttributes1.class).getLinkstatePathAttribute());
 
         final List<CLinkstateDestination> dests = ((DestinationLinkstateCase) mp.getAdvertizedRoutes().getDestinationType()).getDestinationLinkstate().getCLinkstateDestination();
 
@@ -1088,10 +1089,10 @@ public class BGPParserTest {
         // attributes
 
         final Ipv4NextHopCase nextHop = new Ipv4NextHopCaseBuilder().setIpv4NextHop(
-                new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("25.25.25.1")).build()).build();
+            new Ipv4NextHopBuilder().setGlobal(new Ipv4Address("25.25.25.1")).build()).build();
 
         final LocalNodeDescriptorsBuilder lndBuilder = new LocalNodeDescriptorsBuilder().setAsNumber(new AsNumber((long) 100)).setDomainId(
-                new DomainIdentifier(0x19191901L)).setAreaId(new AreaIdentifier(0L));
+            new DomainIdentifier(0x19191901L)).setAreaId(new AreaIdentifier(0L));
 
         final CLinkstateDestinationBuilder clBuilder = new CLinkstateDestinationBuilder();
         clBuilder.setIdentifier(new Identifier(BigInteger.ONE));
@@ -1100,16 +1101,16 @@ public class BGPParserTest {
 
         final List<CLinkstateDestination> linkstates = Lists.newArrayList();
         clBuilder.setLocalNodeDescriptors(lndBuilder.setCRouterIdentifier(
-                new OspfPseudonodeCaseBuilder().setOspfPseudonode(
-                        new OspfPseudonodeBuilder().setOspfRouterId(0x03030304L).setLanInterface(new OspfInterfaceIdentifier(0x0b0b0b03L)).build()).build()).build());
+            new OspfPseudonodeCaseBuilder().setOspfPseudonode(
+                new OspfPseudonodeBuilder().setOspfRouterId(0x03030304L).setLanInterface(new OspfInterfaceIdentifier(0x0b0b0b03L)).build()).build()).build());
         linkstates.add(clBuilder.build());
 
         clBuilder.setLocalNodeDescriptors(lndBuilder.setCRouterIdentifier(
-                new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x03030304L).build()).build()).build());
+            new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x03030304L).build()).build()).build());
         linkstates.add(clBuilder.build());
 
         clBuilder.setLocalNodeDescriptors(lndBuilder.setCRouterIdentifier(
-                new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x01010102L).build()).build()).build());
+            new OspfNodeCaseBuilder().setOspfNode(new OspfNodeBuilder().setOspfRouterId(0x01010102L).build()).build()).build());
         linkstates.add(clBuilder.build());
 
         final PathAttributes1Builder lsBuilder = new PathAttributes1Builder();
@@ -1122,7 +1123,7 @@ public class BGPParserTest {
         dBuilder.setCLinkstateDestination(linkstates);
 
         mpBuilder.setAdvertizedRoutes(new AdvertizedRoutesBuilder().setDestinationType(
-                new DestinationLinkstateCaseBuilder().setDestinationLinkstate(dBuilder.build()).build()).build());
+            new DestinationLinkstateCaseBuilder().setDestinationLinkstate(dBuilder.build()).build()).build());
         lsBuilder.setMpReachNlri(mpBuilder.build());
 
         final List<Segments> asPath = Lists.newArrayList();
index 8280ca6f4969691619f08538c169b641cb900095..c2b6a899037302d4be1e1842dfc27fb10718ef1a 100644 (file)
@@ -53,40 +53,33 @@ import org.opendaylight.yangtools.yang.binding.Notification;
 
 public class ParserTest {
 
-    public static final byte[] openBMsg = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+    private static final byte[] openBMsg = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0x00, (byte) 0x1d, (byte) 0x01, (byte) 0x04, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0xb4,
         (byte) 0x14, (byte) 0x14, (byte) 0x14, (byte) 0x14, (byte) 0x00 };
 
-    public static final byte[] keepAliveBMsg = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+    private static final byte[] keepAliveBMsg = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0x00, (byte) 0x13, (byte) 0x04 };
 
-    public static final byte[] notificationBMsg = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+    private static final byte[] notificationBMsg = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0xff, (byte) 0x00, (byte) 0x17, (byte) 0x03, (byte) 0x02, (byte) 0x04, (byte) 0x04, (byte) 0x09 };
 
-    public static final byte[] openWithCpblt1 = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+    private static final byte[] openWithCpblt1 = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0x00, (byte) 0x2d, (byte) 0x01, (byte) 0x04, (byte) 0x00, (byte) 0x48, (byte) 0x00, (byte) 0xb4,
         (byte) 0xac, (byte) 0x14, (byte) 0xa0, (byte) 0xaa, (byte) 0x10, (byte) 0x02, (byte) 0x06, (byte) 0x01, (byte) 0x04,
         (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x06, (byte) 0x01, (byte) 0x04, (byte) 0x40,
         (byte) 0x04, (byte) 0x00, (byte) 0x47 };
 
-    public static final byte[] openWithCpblt2 = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+    private static final byte[] openWithCpblt2 = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
         (byte) 0xff, (byte) 0x00, (byte) 0x2d, (byte) 0x01, (byte) 0x04, (byte) 0x00, (byte) 0x48, (byte) 0x00, (byte) 0xb4,
         (byte) 0xac, (byte) 0x14, (byte) 0xa0, (byte) 0xaa, (byte) 0x10, (byte) 0x02, (byte) 0x06, (byte) 0x01, (byte) 0x04,
         (byte) 0x40, (byte) 0x04, (byte) 0x00, (byte) 0x47, (byte) 0x02, (byte) 0x06, (byte) 0x01, (byte) 0x04, (byte) 0x00,
         (byte) 0x01, (byte) 0x00, (byte) 0x01 };
 
-    public static final byte[] updateMsg = {
-        (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
-        (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x00, 0x51, 0x02, 0x00, 0x00, 0x00, 0x36, 0x40, 0x01, 0x01, 0x00, 0x40, 0x02,
-        0x1a, 0x02, 0x06, 0x00, 0x00, (byte) 0xfe, 0x55, 0x00, 0x00, (byte) 0xfc, 0x12, 0x00, 0x00, 0x00, 0x6d, 0x00, 0x00, 0x02, (byte) 0xbd, 0x00, 0x00, 0x0d, 0x1c, 0x00, 0x00, 0x6a, 0x74, 0x40, 0x03,
-        0x04, 0x0a, 0x20, 0x00, (byte) 0xfe, (byte) 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x64, 0x18, (byte) 0xa8, (byte) 0xa1, (byte) 0xf7
-    };
-
     static MessageRegistry reg;
 
     @BeforeClass
@@ -126,7 +119,7 @@ public class ParserTest {
     @Test
     public void testKeepAliveMsg() throws BGPParsingException, BGPDocumentedException {
         final Notification keepAlive = new KeepaliveBuilder().build();
-        ByteBuf buffer = Unpooled.buffer();
+        final ByteBuf buffer = Unpooled.buffer();
         ParserTest.reg.serializeMessage(keepAlive, buffer);
         assertArrayEquals(keepAliveBMsg, ByteArray.getAllBytes(buffer));
 
@@ -155,8 +148,8 @@ public class ParserTest {
     @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();
-        ByteBuf bytes = Unpooled.buffer();
+                new ProtocolVersion((short) 4)).build();
+        final ByteBuf bytes = Unpooled.buffer();
         ParserTest.reg.serializeMessage(open, bytes);
         assertArrayEquals(openBMsg, ByteArray.getAllBytes(bytes));
 
@@ -224,8 +217,8 @@ public class ParserTest {
     @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();
-        ByteBuf bytes = Unpooled.buffer();
+                BGPError.OPT_PARAM_NOT_SUPPORTED.getSubcode()).setData(new byte[] { 4, 9 }).build();
+        final ByteBuf bytes = Unpooled.buffer();
         ParserTest.reg.serializeMessage(notMsg, bytes);
         assertArrayEquals(notificationBMsg, ByteArray.subByte(bytes.array(),0,bytes.writerIndex()));
 
@@ -304,7 +297,7 @@ public class ParserTest {
         final Open open = new OpenBuilder().setMyAsNumber(72).setHoldTimer(180).setBgpIdentifier(new Ipv4Address("172.20.160.170")).setVersion(
             new ProtocolVersion((short) 4)).setBgpParameters(tlvs).build();
 
-        ByteBuf result = Unpooled.buffer();
+        final ByteBuf result = Unpooled.buffer();
         ParserTest.reg.serializeMessage(open, result);
 
         // the capabilities can be swapped.
index 5a640f49996a2921bf8c2e3bd3fdc03ef75c94fe..1271b4e2889cbc362fef49acb539e139a2612da7 100644 (file)
@@ -13,10 +13,8 @@ import static org.junit.Assert.assertNotSame;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
-
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
-
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -24,7 +22,6 @@ import java.net.UnknownHostException;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
@@ -128,15 +125,16 @@ public class BGPMessageParserMockTest {
      * @param fileNumber parameter to distinguish between files from which bytes are read
      */
     private byte[] fillInputBytes(final int fileNumber) throws Exception {
-
-        final InputStream is = this.getClass().getResourceAsStream("/up" + fileNumber + ".bin");
         final ByteArrayOutputStream bis = new ByteArrayOutputStream();
         final byte[] data = new byte[60];
         int nRead = 0;
-        while ((nRead = is.read(data, 0, data.length)) != -1) {
-            bis.write(data, 0, nRead);
+        try (final InputStream is = this.getClass().getResourceAsStream("/up" + fileNumber + ".bin")) {
+            while ((nRead = is.read(data, 0, data.length)) != -1) {
+                bis.write(data, 0, nRead);
+            }
+            bis.flush();
+            is.close();
         }
-        bis.flush();
         return bis.toByteArray();
     }
 
@@ -152,9 +150,9 @@ public class BGPMessageParserMockTest {
         final List<AsSequence> asnums = Lists.newArrayList(new AsSequenceBuilder().setAs(new AsNumber(asn)).build());
         final List<Segments> asPath = Lists.newArrayList();
         asPath.add(new SegmentsBuilder().setCSegment(
-                new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(asnums).build()).build()).build());
+            new AListCaseBuilder().setAList(new AListBuilder().setAsSequence(asnums).build()).build()).build());
         final CNextHop nextHop = new Ipv6NextHopCaseBuilder().setIpv6NextHop(
-                new Ipv6NextHopBuilder().setGlobal(new Ipv6Address("2001:db8::1")).setLinkLocal(new Ipv6Address("fe80::c001:bff:fe7e:0")).build()).build();
+            new Ipv6NextHopBuilder().setGlobal(new Ipv6Address("2001:db8::1")).setLinkLocal(new Ipv6Address("fe80::c001:bff:fe7e:0")).build()).build();
 
         final Ipv6Prefix pref1 = new Ipv6Prefix("2001:db8:1:2::/64");
         final Ipv6Prefix pref2 = new Ipv6Prefix("2001:db8:1:1::/64");
@@ -169,8 +167,8 @@ public class BGPMessageParserMockTest {
         mpReachBuilder.setSafi(UnicastSubsequentAddressFamily.class);
         mpReachBuilder.setCNextHop(nextHop);
         mpReachBuilder.setAdvertizedRoutes(new AdvertizedRoutesBuilder().setDestinationType(
-                new DestinationIpv6CaseBuilder().setDestinationIpv6(
-                        new DestinationIpv6Builder().setIpv6Prefixes(Lists.newArrayList(pref1, pref2, pref3)).build()).build()).build());
+            new DestinationIpv6CaseBuilder().setDestinationIpv6(
+                new DestinationIpv6Builder().setIpv6Prefixes(Lists.newArrayList(pref1, pref2, pref3)).build()).build()).build());
 
         paBuilder.addAugmentation(PathAttributes1.class, new PathAttributes1Builder().setMpReachNlri(mpReachBuilder.build()).build());
 
@@ -189,13 +187,13 @@ public class BGPMessageParserMockTest {
         final List<BgpParameters> params = Lists.newArrayList();
 
         final CParameters par = new MultiprotocolCaseBuilder().setMultiprotocolCapability(
-                new MultiprotocolCapabilityBuilder().setAfi(Ipv4AddressFamily.class).setSafi(MplsLabeledVpnSubsequentAddressFamily.class).build()).build();
+            new MultiprotocolCapabilityBuilder().setAfi(Ipv4AddressFamily.class).setSafi(MplsLabeledVpnSubsequentAddressFamily.class).build()).build();
         params.add(new BgpParametersBuilder().setCParameters(par).build());
 
         final byte[] input = new byte[] { 5, 8, 13, 21 };
 
         openMap.put(Unpooled.copiedBuffer(input), new OpenBuilder().setMyAsNumber(30).setHoldTimer(30).setBgpParameters(params).setVersion(
-                new ProtocolVersion((short) 4)).build());
+            new ProtocolVersion((short) 4)).build());
 
         final BGPMessageParserMock mockParser = new BGPMessageParserMock(openMap);
 
index 4435a6952ca48d4ea7e7de7efa4ff9bd115126e5..f10b0ffd9d80e411e853596bec6de1e44b571fc5 100644 (file)
@@ -24,22 +24,16 @@ import org.opendaylight.protocol.bgp.parser.impl.BGPActivator;
 public final class BaseBGPParserModule extends org.opendaylight.controller.config.yang.bgp.rib.impl.AbstractBaseBGPParserModule {
 
     public BaseBGPParserModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+        final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
     }
 
     public BaseBGPParserModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final BaseBGPParserModule oldModule,
-            final java.lang.AutoCloseable oldInstance) {
+        final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final BaseBGPParserModule oldModule,
+        final java.lang.AutoCloseable oldInstance) {
         super(identifier, dependencyResolver, oldModule, oldInstance);
     }
 
-    @Override
-    public void validate() {
-        super.validate();
-        // Add custom validation for module attributes here.
-    }
-
     @Override
     public java.lang.AutoCloseable createInstance() {
         return new BGPActivator();
index 1c8c7894d659b2199aafaf362861018d783097cd..ab2f6714059ca5a71a167ede3b904c4c75da2ab0 100644 (file)
@@ -14,14 +14,11 @@ import io.netty.channel.EventLoopGroup;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.Promise;
-
 import java.net.InetSocketAddress;
-
 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
 import org.opendaylight.protocol.bgp.parser.spi.MessageRegistry;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
-import org.opendaylight.protocol.bgp.rib.impl.spi.BGPServerDispatcher;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionValidator;
 import org.opendaylight.protocol.framework.AbstractDispatcher;
 import org.opendaylight.protocol.framework.ReconnectStrategy;
@@ -35,7 +32,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.
 /**
  * Implementation of BGPDispatcher.
  */
-public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl, BGPSessionListener> implements BGPDispatcher, BGPServerDispatcher, AutoCloseable {
+public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl, BGPSessionListener> implements BGPDispatcher, AutoCloseable {
     private final MD5ServerChannelFactory<?> scf;
     private final MD5ChannelFactory<?> cf;
     private final BGPHandlerFactory hf;
@@ -54,7 +51,7 @@ public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl,
 
     @Override
     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress address,
-            final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
+        final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategy strategy) {
         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, listener);
         return super.createClient(address, strategy, new PipelineInitializer<BGPSessionImpl>() {
             @Override
@@ -68,10 +65,10 @@ public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl,
 
     @Override
     public Future<Void> createReconnectingClient(final InetSocketAddress address,
-            final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategyFactory connectStrategyFactory,
-            final ReconnectStrategyFactory reestablishStrategyFactory) {
+        final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategyFactory connectStrategyFactory,
+        final ReconnectStrategyFactory reestablishStrategyFactory) {
         return this.createReconnectingClient(address, remoteAs, listener, connectStrategyFactory, reestablishStrategyFactory,
-                null);
+            null);
     }
 
     @Override
@@ -80,8 +77,8 @@ public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl,
 
     @Override
     public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address,
-            final AsNumber remoteAs, final BGPPeerRegistry peerRegistry, final ReconnectStrategyFactory connectStrategyFactory,
-            final ReconnectStrategyFactory reestablishStrategyFactory, final KeyMapping keys) {
+        final AsNumber remoteAs, final BGPPeerRegistry peerRegistry, final ReconnectStrategyFactory connectStrategyFactory,
+        final ReconnectStrategyFactory reestablishStrategyFactory, final KeyMapping keys) {
         final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, peerRegistry);
 
         this.keys = keys;
@@ -123,23 +120,23 @@ public final class BGPDispatcherImpl extends AbstractDispatcher<BGPSessionImpl,
 
     @Override
     protected void customizeBootstrap(final Bootstrap b) {
-        if (keys != null && !keys.isEmpty()) {
-            if (cf == null) {
+        if (this.keys != null && !this.keys.isEmpty()) {
+            if (this.cf == null) {
                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
             }
-            b.channelFactory(cf);
-            b.option(MD5ChannelOption.TCP_MD5SIG, keys);
+            b.channelFactory(this.cf);
+            b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
         }
     }
 
     @Override
     protected void customizeBootstrap(final ServerBootstrap b) {
-        if (keys != null && !keys.isEmpty()) {
-            if (scf == null) {
+        if (this.keys != null && !this.keys.isEmpty()) {
+            if (this.scf == null) {
                 throw new UnsupportedOperationException("No key access instance available, cannot use key mapping");
             }
-            b.channelFactory(scf);
-            b.option(MD5ChannelOption.TCP_MD5SIG, keys);
+            b.channelFactory(this.scf);
+            b.option(MD5ChannelOption.TCP_MD5SIG, this.keys);
         }
     }
 
index dff584d5bf432101a62a4a9810d61401f771b855..66478404fb5efc45875d0c22e0eb8744d66708f4 100644 (file)
@@ -10,11 +10,9 @@ package org.opendaylight.protocol.bgp.rib.impl;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.net.InetAddresses;
-
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.List;
-
 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.Ipv4Address;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.PathAttributes;
@@ -56,7 +54,7 @@ final class BGPObjectComparator implements Comparator<PathAttributes> {
 
         // 2. prefer path with higher LOCAL_PREF
         if ((o1.getLocalPref() != null || o2.getLocalPref() != null)
-                && (o1.getLocalPref() != null && !o1.getLocalPref().equals(o2.getLocalPref()))) {
+            && (o1.getLocalPref() != null && !o1.getLocalPref().equals(o2.getLocalPref()))) {
             return o1.getLocalPref().getPref().compareTo(o2.getLocalPref().getPref());
         }
 
@@ -88,7 +86,7 @@ final class BGPObjectComparator implements Comparator<PathAttributes> {
 
         // 6. prefer the path with the lowest multi-exit discriminator (MED)
         if ((o1.getMultiExitDisc() != null || o2.getMultiExitDisc() != null)
-                && (o1.getMultiExitDisc() != null && !o1.getMultiExitDisc().equals(o2.getMultiExitDisc()))) {
+            && (o1.getMultiExitDisc() != null && !o1.getMultiExitDisc().equals(o2.getMultiExitDisc()))) {
             return o2.getMultiExitDisc().getMed().compareTo(o1.getMultiExitDisc().getMed());
         }
 
@@ -97,7 +95,7 @@ final class BGPObjectComparator implements Comparator<PathAttributes> {
         final AsNumber first = getPeerAs(o1.getAsPath().getSegments());
         final AsNumber second = getPeerAs(o2.getAsPath().getSegments());
         if ((first != null || second != null) && (first != null && !first.equals(second))) {
-            if (first == null || first.equals(this.ourAS)) {
+            if (first.equals(this.ourAS)) {
                 return -1;
             }
             if (second == null || second.equals(this.ourAS)) {
index 05f03738bcbdfd54344e34342363ced143073ac3..bbe19460edf788a5fb0667233951aad7b2c62ea1 100644 (file)
@@ -69,7 +69,7 @@ public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable {
         LOG.info("Session with peer {} went up with tables: {}", this.name, session.getAdvertisedTableTypes());
 
         this.session = session;
-        this.comparator = new BGPObjectComparator(this.rib.getLocalAs(), rib.getBgpIdentifier(), session.getBgpId());
+        this.comparator = new BGPObjectComparator(this.rib.getLocalAs(), this.rib.getBgpIdentifier(), session.getBgpId());
 
         for (final BgpTableType t : session.getAdvertisedTableTypes()) {
             final TablesKey key = new TablesKey(t.getAfi(), t.getSafi());
@@ -119,12 +119,12 @@ public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable {
     }
 
     @Override
-    public Comparator<PathAttributes> getComparator() {
+    public synchronized Comparator<PathAttributes> getComparator() {
         return this.comparator;
     }
 
     protected RIB getRib() {
-        return rib;
+        return this.rib;
     }
 
     @Override
index 7ef25879f3e715700921f436f0f9f286e95ebe82..e38e166172808acb083ec468005fee7ffa59628a 100644 (file)
@@ -156,7 +156,7 @@ public class BGPSessionImpl extends AbstractProtocolSession<Notification> implem
      * @param msg incoming message
      */
     @Override
-    public void handleMessage(final Notification msg) {
+    public synchronized void handleMessage(final Notification msg) {
         // Update last reception time
         this.lastMessageReceivedAt = System.nanoTime();
 
@@ -166,10 +166,10 @@ public class BGPSessionImpl extends AbstractProtocolSession<Notification> implem
         } else if (msg instanceof Notify) {
             // Notifications are handled internally
             LOG.info("Session closed because Notification message received: {} / {}", ((Notify) msg).getErrorCode(),
-                    ((Notify) msg).getErrorSubcode());
+                ((Notify) msg).getErrorSubcode());
             this.closeWithoutMessage();
             this.listener.onSessionTerminated(this, new BGPTerminationReason(BGPError.forValue(((Notify) msg).getErrorCode(),
-                    ((Notify) msg).getErrorSubcode())));
+                ((Notify) msg).getErrorSubcode())));
         } else if (msg instanceof Keepalive) {
             // Keepalives are handled internally
             LOG.trace("Received KeepAlive messsage.");
@@ -191,7 +191,7 @@ public class BGPSessionImpl extends AbstractProtocolSession<Notification> implem
         }
     }
 
-    void sendMessage(final Notification msg) {
+    synchronized void sendMessage(final Notification msg) {
         try {
             this.channel.writeAndFlush(msg);
             this.lastMessageSentAt = System.nanoTime();
index 65e6ff0b9a2f9957d5bf4f54c4b3f7ad37bbeb4e..b26177b09c0d4031604cf210c9a1307b8be88cb7 100644 (file)
@@ -44,7 +44,7 @@ final class Ipv6AdjRIBsIn extends AbstractAdjRIBsIn<Ipv6Prefix, Ipv6Route> {
                 return new Ipv6RouteBuilder().setKey(InstanceIdentifier.keyOf(id)).setAttributes(new AttributesBuilder(attributes).build()).build();
             }
         };
-
+        Preconditions.checkArgument(nlri.getAdvertizedRoutes().getDestinationType() instanceof DestinationIpv6);
         for (final Ipv6Prefix id : ((DestinationIpv6) nlri.getAdvertizedRoutes().getDestinationType()).getIpv6Prefixes()) {
             super.add(trans, peer, id, data);
         }
index a47ac9adf42e00b52e654601fe39410a5cb20629..528605933e80a5cd330cafa5803144fd20287d2d 100644 (file)
@@ -8,6 +8,7 @@
 
 package org.opendaylight.protocol.bgp.rib.impl;
 
+import com.google.common.base.CharMatcher;
 import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Maps;
@@ -41,6 +42,8 @@ public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
 
     private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
 
+    private static final CharMatcher NONDIGIT = CharMatcher.inRange('0', '9').negate();
+
     // TODO remove backwards compatibility
     public static final StrictBGPPeerRegistry GLOBAL = new StrictBGPPeerRegistry();
 
@@ -54,30 +57,30 @@ public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
     @Override
     public synchronized void addPeer(final IpAddress ip, final ReusableBGPPeer peer, final BGPSessionPreferences preferences) {
         Preconditions.checkNotNull(ip);
-        Preconditions.checkArgument(!peers.containsKey(ip), "Peer for %s already present", ip);
-        peers.put(ip, Preconditions.checkNotNull(peer));
-        peerPreferences.put(ip, Preconditions.checkNotNull(preferences));
+        Preconditions.checkArgument(!this.peers.containsKey(ip), "Peer for %s already present", ip);
+        this.peers.put(ip, Preconditions.checkNotNull(peer));
+        this.peerPreferences.put(ip, Preconditions.checkNotNull(preferences));
     }
 
     @Override
     public synchronized void removePeer(final IpAddress ip) {
         Preconditions.checkNotNull(ip);
-        peers.remove(ip);
+        this.peers.remove(ip);
     }
 
     @Override
     public boolean isPeerConfigured(final IpAddress ip) {
         Preconditions.checkNotNull(ip);
-        return peers.containsKey(ip);
+        return this.peers.containsKey(ip);
     }
 
     private void checkPeerConfigured(final IpAddress ip) {
-        Preconditions.checkState(isPeerConfigured(ip), "BGP peer with ip: %s not configured, configured peers are: %s", ip, peers.keySet());
+        Preconditions.checkState(isPeerConfigured(ip), "BGP peer with ip: %s not configured, configured peers are: %s", ip, this.peers.keySet());
     }
 
     @Override
     public synchronized BGPSessionListener getPeer(final IpAddress ip,
-            final Ipv4Address sourceId, final Ipv4Address remoteId)
+        final Ipv4Address sourceId, final Ipv4Address remoteId)
             throws BGPDocumentedException {
         Preconditions.checkNotNull(ip);
         Preconditions.checkNotNull(sourceId);
@@ -87,53 +90,53 @@ public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
 
         final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId);
 
-        if (sessionIds.containsKey(ip)) {
+        if (this.sessionIds.containsKey(ip)) {
             LOG.warn("Duplicate BGP session established with {}", ip);
 
-            final BGPSessionId previousConnection = sessionIds.get(ip);
+            final BGPSessionId previousConnection = this.sessionIds.get(ip);
 
             // Session reestablished with different ids
             if (!previousConnection.equals(currentConnection)) {
                 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip, currentConnection, previousConnection);
                 throw new BGPDocumentedException(
-                        String.format("BGP session with %s %s has to be dropped. Same session already present %s",
-                                ip, currentConnection, previousConnection),
+                    String.format("BGP session with %s %s has to be dropped. Same session already present %s",
+                        ip, currentConnection, previousConnection),
                         BGPError.CEASE);
 
-            // Session reestablished with lower source bgp id, dropping current
+                // Session reestablished with lower source bgp id, dropping current
             } else if (previousConnection.isHigherDirection(currentConnection)) {
                 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present", ip, currentConnection);
                 throw new BGPDocumentedException(
-                        String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
-                                ip, currentConnection),
+                    String.format("BGP session with %s initiated %s has to be dropped. Opposite session already present",
+                        ip, currentConnection),
                         BGPError.CEASE);
 
-            // Session reestablished with higher source bgp id, dropping previous
+                // Session reestablished with higher source bgp id, dropping previous
             } else if (currentConnection.isHigherDirection(previousConnection)) {
                 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
-                peers.get(ip).releaseConnection();
-                return peers.get(ip);
+                this.peers.get(ip).releaseConnection();
+                return this.peers.get(ip);
 
-            // Session reestablished with same source bgp id, dropping current as duplicate
+                // Session reestablished with same source bgp id, dropping current as duplicate
             } else {
                 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present", ip, sourceId, remoteId);
                 throw new BGPDocumentedException(
-                        String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
-                                ip, currentConnection),
+                    String.format("BGP session with %s initiated %s has to be dropped. Same session already present",
+                        ip, currentConnection),
                         BGPError.CEASE);
             }
         }
 
         // Map session id to peer IP address
-        sessionIds.put(ip, currentConnection);
-        return peers.get(ip);
+        this.sessionIds.put(ip, currentConnection);
+        return this.peers.get(ip);
     }
 
     @Override
     public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
         Preconditions.checkNotNull(ip);
         checkPeerConfigured(ip);
-        return peerPreferences.get(ip);
+        return this.peerPreferences.get(ip);
     }
 
     /**
@@ -158,15 +161,15 @@ public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
 
     @Override
     public synchronized void close() {
-        peers.clear();
-        sessionIds.clear();
+        this.peers.clear();
+        this.sessionIds.clear();
     }
 
     @Override
     public String toString() {
         return Objects.toStringHelper(this)
-                .add("peers", peers.keySet())
-                .toString();
+            .add("peers", this.peers.keySet())
+            .toString();
     }
 
     /**
@@ -194,10 +197,10 @@ public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
 
             final BGPSessionId bGPSessionId = (BGPSessionId) o;
 
-            if (!from.equals(bGPSessionId.from) && !from.equals(bGPSessionId.to)) {
+            if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
                 return false;
             }
-            if (!to.equals(bGPSessionId.to) && !to.equals(bGPSessionId.from)) {
+            if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
                 return false;
             }
 
@@ -207,7 +210,7 @@ public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
         @Override
         public int hashCode() {
             final int prime = 31;
-            int result = from.hashCode() + to.hashCode();
+            int result = this.from.hashCode() + this.to.hashCode();
             result = prime * result;
             return result;
         }
@@ -217,11 +220,11 @@ public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
          */
         boolean isHigherDirection(final BGPSessionId other) {
             Preconditions.checkState(!this.isSameDirection(other), "Equal sessions with same direction");
-            return toLong(from) > toLong(other.from);
+            return toLong(this.from) > toLong(other.from);
         }
 
         private long toLong(final Ipv4Address from) {
-            return Long.valueOf(from.getValue().replaceAll("[^0-9]", ""));
+            return Long.parseLong(NONDIGIT.removeFrom(from.getValue()));
         }
 
         /**
@@ -229,15 +232,15 @@ public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
          */
         boolean isSameDirection(final BGPSessionId other) {
             Preconditions.checkState(this.equals(other), "Only equal sessions can be compared");
-            return from.equals(other.from);
+            return this.from.equals(other.from);
         }
 
         @Override
         public String toString() {
             return Objects.toStringHelper(this)
-                    .add("from", from)
-                    .add("to", to)
-                    .toString();
+                .add("from", this.from)
+                .add("to", this.to)
+                .toString();
         }
     }
 }
index 0612dfac8b5478b825fa455c27ee3f6a96871b8b..6104152469d60893dc22c2779b4a546f90d3ee24 100644 (file)
@@ -40,10 +40,10 @@ public final class Main {
     private static final Logger LOG = LoggerFactory.getLogger(Main.class);
 
     private static final String USAGE = "DESCRIPTION:\n"
-            + "\tCreates a server with given parameters. As long as it runs, it accepts connections " + "from PCCs.\n" + "USAGE:\n"
-            + "\t-a, --address\n" + "\t\tthe ip address to which is this server bound.\n"
-            + "\t\tFormat: x.x.x.x:y where y is port number.\n\n"
-            + "\t\tThis IP address will appear in BGP Open message as BGP Identifier of the server.\n" +
+        + "\tCreates a server with given parameters. As long as it runs, it accepts connections " + "from PCCs.\n" + "USAGE:\n"
+        + "\t-a, --address\n" + "\t\tthe ip address to which is this server bound.\n"
+        + "\t\tFormat: x.x.x.x:y where y is port number.\n\n"
+        + "\t\tThis IP address will appear in BGP Open message as BGP Identifier of the server.\n" +
 
             "\t-as\n" + "\t\t value of AS in the initial open message\n\n" +
 
@@ -62,7 +62,7 @@ public final class Main {
     private static final int RECONNECT_MILLIS = 5000;
 
     private Main() throws Exception {
-        BGPActivator bgpActivator = new BGPActivator();
+        final BGPActivator bgpActivator = new BGPActivator();
         bgpActivator.start(ServiceLoaderBGPExtensionProviderContext.getSingletonInstance());
         this.dispatcher = new BGPDispatcherImpl(ServiceLoaderBGPExtensionProviderContext.getSingletonInstance().getMessageRegistry(), new NioEventLoopGroup(), new NioEventLoopGroup());
     }
@@ -81,7 +81,7 @@ public final class Main {
         while (i < args.length) {
             if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("--address")) {
                 final String[] ip = args[i + 1].split(":");
-                address = new InetSocketAddress(InetAddress.getByName(ip[0]), Integer.valueOf(ip[1]));
+                address = new InetSocketAddress(InetAddress.getByName(ip[0]), Integer.parseInt(ip[1]));
                 i++;
             } else if (args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("--holdtimer")) {
                 holdTimerValue = Short.valueOf(args[i + 1]);
@@ -114,6 +114,6 @@ public final class Main {
         strictBGPPeerRegistry.addPeer(StrictBGPPeerRegistry.getIpAddress(address), sessionListener, proposal);
 
         m.dispatcher.createClient(addr, as, strictBGPPeerRegistry,
-                new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, RECONNECT_MILLIS));
+            new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, RECONNECT_MILLIS));
     }
 }
index fa5c2df96cc51169bad130641bdb38f68f2fdaa5..e8c4105bbae8878b8ad3442bf6d61a7794243c64 100644 (file)
@@ -15,14 +15,13 @@ import static org.junit.matchers.JUnitMatchers.containsString;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.List;
-
 import org.junit.Test;
 
 public class BGPHexFileParserTest {
 
     public static final String hexDumpFileName = "bgp_hex.txt";
-    private final String fileNameInvalid = "BgpMessage_Hex_InvalidLength.bin";
-    private final int expectedSize = 25;
+    private static final String fileNameInvalid = "BgpMessage_Hex_InvalidLength.bin";
+    private static final int expectedSize = 25;
 
     @Test
     public void testCleanWhiteSpace() {
@@ -33,14 +32,14 @@ public class BGPHexFileParserTest {
     @Test
     public void testParsing() throws Exception {
         final List<byte[]> result = HexDumpBGPFileParser.parseMessages(getClass().getClassLoader().getResourceAsStream(
-                BGPHexFileParserTest.hexDumpFileName));
-        assertEquals(this.expectedSize, result.size());
+            BGPHexFileParserTest.hexDumpFileName));
+        assertEquals(expectedSize, result.size());
     }
 
     @Test
     public void testParsingInvalidMessage() throws Exception {
         try {
-            HexDumpBGPFileParser.parseMessages(getClass().getClassLoader().getResourceAsStream(this.fileNameInvalid));
+            HexDumpBGPFileParser.parseMessages(getClass().getClassLoader().getResourceAsStream(fileNameInvalid));
             fail("Exception should have occured.");
         } catch (final IllegalArgumentException e) {
             assertThat(e.getMessage(), containsString("Invalid message at index 0, length atribute is lower than 19"));