Initial framework migration to netty. 19/819/3
authorDana Kutenicsova <dkutenic@cisco.com>
Fri, 26 Jul 2013 19:31:12 +0000 (21:31 +0200)
committerGerrit Code Review <gerrit@opendaylight.org>
Fri, 9 Aug 2013 09:10:57 +0000 (09:10 +0000)
Change-Id: Ic8ddba993d83b6535a96953cf41e9549227bc62d
Signed-off-by: Dana Kutenicsova <dkutenic@cisco.com>
75 files changed:
bgp/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/NetworkLinkState.java
bgp/parser-api/src/main/java/org/opendaylight/protocol/bgp/parser/BGPMessageHeader.java [deleted file]
bgp/parser-api/src/main/java/org/opendaylight/protocol/bgp/parser/BGPMessageParser.java [deleted file]
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/BGPMessageFactory.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/update/LinkStateParser.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/BGPUpdateMessageParserTest.java
bgp/parser-impl/src/test/java/org/opendaylight/protocol/bgp/parser/impl/ComplementaryTest.java
bgp/parser-mock/src/main/java/org/opendaylight/protocol/bgp/parser/mock/BGPMessageParserMock.java
bgp/parser-mock/src/test/java/org/opendaylight/protocol/bgp/parser/mock/BGPMessageParserMockTest.java
bgp/rib-impl/pom.xml
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/BGPImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPInputStream.java [deleted file]
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPSessionFactory.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/spi/BGPDispatcher.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/ApiTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/BGPImplTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/FSMTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/InputStreamTest.java [deleted file]
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/MockDispatcher.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/ParserTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SpeakerSessionMock.java
bgp/rib-mock/src/main/java/org/opendaylight/protocol/bgp/rib/mock/BGPMock.java
bgp/testtool/src/main/java/org/opendaylight/protocol/bgp/testtool/Main.java
bgp/testtool/src/main/java/org/opendaylight/protocol/bgp/testtool/TestingListener.java
bgp/testtool/src/test/java/org/opendaylight/protocol/bgp/testtool/BGPSpeakerMock.java
bgp/testtool/src/test/java/org/opendaylight/protocol/bgp/testtool/SpeakerSessionListener.java
concepts/bin/pom.xml
framework/pom.xml
framework/src/main/java/org/opendaylight/protocol/framework/Dispatcher.java
framework/src/main/java/org/opendaylight/protocol/framework/DispatcherImpl.java
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolHandlerFactory.java [new file with mode: 0644]
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolInputStream.java [deleted file]
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolInputStreamFactory.java [deleted file]
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolMessageDecoder.java [new file with mode: 0644]
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolMessageEncoder.java [new file with mode: 0644]
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolMessageFactory.java
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolOutputStream.java [deleted file]
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolServer.java
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSession.java
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSessionFactory.java
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSessionInboundHandler.java [new file with mode: 0644]
framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSessionOutboundHandler.java [new file with mode: 0644]
framework/src/main/java/org/opendaylight/protocol/framework/SSLSelectableChannel.java [deleted file]
framework/src/main/java/org/opendaylight/protocol/framework/SSLSelectionKey.java [deleted file]
framework/src/main/java/org/opendaylight/protocol/framework/SSLSelector.java [deleted file]
framework/src/main/java/org/opendaylight/protocol/framework/SSLServerSocketChannel.java [deleted file]
framework/src/main/java/org/opendaylight/protocol/framework/SSLSocketChannel.java [deleted file]
framework/src/main/java/org/opendaylight/protocol/framework/SessionParent.java
framework/src/main/java/org/opendaylight/protocol/framework/SessionStreams.java [deleted file]
framework/src/test/java/org/opendaylight/protocol/framework/ComplementaryTest.java
framework/src/test/java/org/opendaylight/protocol/framework/MessageFactory.java
framework/src/test/java/org/opendaylight/protocol/framework/SecureServerTest.java [deleted file]
framework/src/test/java/org/opendaylight/protocol/framework/ServerTest.java
framework/src/test/java/org/opendaylight/protocol/framework/Session.java
framework/src/test/java/org/opendaylight/protocol/framework/SimpleInputStream.java [deleted file]
framework/src/test/java/org/opendaylight/protocol/framework/SimpleMessageFactory.java [deleted file]
framework/src/test/java/org/opendaylight/protocol/framework/SimpleSession.java
framework/src/test/java/org/opendaylight/protocol/framework/SimpleSessionFactory.java
pcep/api/src/main/java/org/opendaylight/protocol/pcep/PCEPSessionFactory.java
pcep/impl/pom.xml
pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPDispatcherImpl.java
pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPInputStream.java [deleted file]
pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPMessageFactory.java
pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPSessionFactoryImpl.java
pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPSessionImpl.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/MockDispatcher.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/PCEPValidatorTest.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/ServerSessionMock.java
pcep/testtool/src/main/java/org/opendaylight/protocol/pcep/testtool/Main.java
pcep/testtool/src/test/java/org/opendaylight/protocol/pcep/testtool/PCCMock.java

index 82d490ce38f8ac46d655feea7c7063121dff4912..1f0eab802308375c33c16b36734e30f842f6ee35 100644 (file)
@@ -156,7 +156,7 @@ public final class NetworkLinkState extends NetworkObjectState {
                return this.protectionType;
        }
 
-       public final NetworkObjectState withProtectionType(final LinkProtectionType protectionType) {
+       public final NetworkLinkState withProtectionType(final LinkProtectionType protectionType) {
                final NetworkLinkState ret = newInstance();
                ret.protectionType = protectionType;
                return ret;
diff --git a/bgp/parser-api/src/main/java/org/opendaylight/protocol/bgp/parser/BGPMessageHeader.java b/bgp/parser-api/src/main/java/org/opendaylight/protocol/bgp/parser/BGPMessageHeader.java
deleted file mode 100644 (file)
index c629ea7..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.parser;
-
-import java.util.Arrays;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.opendaylight.protocol.framework.ProtocolMessageHeader;
-import org.opendaylight.protocol.util.ByteArray;
-import com.google.common.primitives.UnsignedBytes;
-
-/**
- * Representation of BGP Message Header. Includes methods for parsing and serializing header.
- * Length field represents the length of the message including the length of its header.
- */
-public class BGPMessageHeader implements ProtocolMessageHeader {
-
-       public static final Logger logger = LoggerFactory.getLogger(BGPMessageHeader.class);
-
-       /**
-        * BGP message header fixed length (in bytes)
-        */
-       public static final int COMMON_HEADER_LENGTH = 19;
-
-       private static final int MARKER_SIZE = 16;
-       private static final int LENGTH_SIZE = 2;
-       private static final int TYPE_OFFSET = MARKER_SIZE + LENGTH_SIZE;
-
-       private int type;
-       private int length;
-       private boolean parsed = false;
-
-       /**
-        * Creates message header.
-        */
-       public BGPMessageHeader() {
-
-       }
-
-       /**
-        * Creates message header with given attributes.
-        * @param type int
-        * @param length int
-        */
-       public BGPMessageHeader(final int type, final int length) {
-               this.type = type;
-               this.length = length;
-       }
-
-       /**
-        * Creates a BGP Message Header from given byte array.
-        *
-        * @param bytes byte array to be parsed
-        * @return BGP Message Header
-        */
-       public BGPMessageHeader fromBytes(final byte[] bytes) {
-               if (bytes == null)
-                       throw new IllegalArgumentException("Array of bytes is mandatory");
-               //FIXME: how to send Notification message from this point?
-               //              final byte[] ones = new byte[MARKER_SIZE];
-               //              Arrays.fill(ones, (byte)0xff);
-               //
-               //              if (Arrays.equals(bytes, ones))
-               //                      throw new BGPDocumentedException("Marker not set to ones.", BGPError.CONNECTION_NOT_SYNC);
-
-               logger.trace("Attempt to parse message header: {}", ByteArray.bytesToHexString(bytes));
-
-               if (bytes.length < COMMON_HEADER_LENGTH)
-                       throw new IllegalArgumentException("Too few bytes in passed array. Passed: " + bytes.length + ". Expected: >= " + COMMON_HEADER_LENGTH + ".");
-
-               this.length = ByteArray.bytesToInt(ByteArray.subByte(bytes, MARKER_SIZE, LENGTH_SIZE));
-
-               this.type = UnsignedBytes.toInt(bytes[TYPE_OFFSET]);
-
-               logger.trace("Message header was parsed. {}", this);
-               this.parsed = true;
-               return this;
-       }
-
-       /**
-        * Serializes this BGP Message header to byte array.
-        *
-        * @return byte array representation of this header
-        */
-       public byte[] toBytes() {
-               final byte[] retBytes = new byte[COMMON_HEADER_LENGTH];
-
-               Arrays.fill(retBytes, 0, MARKER_SIZE, (byte)0xff);
-
-               System.arraycopy(ByteArray.intToBytes(this.length), Integer.SIZE / Byte.SIZE - LENGTH_SIZE, retBytes, MARKER_SIZE, LENGTH_SIZE);
-
-               retBytes[TYPE_OFFSET] = (byte) this.type;
-
-               return retBytes;
-       }
-
-       /**
-        * Returns length presented in Length field of this header.
-        *
-        * @return length of the BGP message
-        */
-       public int getLength() {
-               return this.length;
-       }
-
-       /**
-        * Returns type presented in Type field of this header.
-        *
-        * @return type of the BGP message
-        */
-       public int getType() {
-               return this.type;
-       }
-
-       /**
-        * Return the state of the parsing of this header.
-        *
-        * @return the parsed true if the header was parsed false if the header was not parsed
-        */
-       public boolean isParsed() {
-               return this.parsed;
-       }
-
-       /**
-        * Marks parsing as not finished. There is no need for other classes to mark parsing as done, therefore calling this
-        * method will set parsing to unfinished.
-        */
-       public void setParsed() {
-               this.parsed = false;
-       }
-}
diff --git a/bgp/parser-api/src/main/java/org/opendaylight/protocol/bgp/parser/BGPMessageParser.java b/bgp/parser-api/src/main/java/org/opendaylight/protocol/bgp/parser/BGPMessageParser.java
deleted file mode 100644 (file)
index ced4df8..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.parser;
-
-import java.io.Closeable;
-
-import org.opendaylight.protocol.framework.DeserializerException;
-import org.opendaylight.protocol.framework.DocumentedException;
-import org.opendaylight.protocol.framework.ProtocolMessageFactory;
-import org.opendaylight.protocol.framework.ProtocolMessageHeader;
-
-/**
- * Parser for BGP Messages.
- */
-public interface BGPMessageParser extends ProtocolMessageFactory, Closeable {
-
-       @Override
-       public BGPMessage parse(byte[] bytes, ProtocolMessageHeader msgHeader) throws DeserializerException, DocumentedException;
-}
index a55bb89f4cfc5eddacfb5c00c331b893cd30519c..14abaab8a11754028d00c3aabda17d0beeeb270a 100644 (file)
@@ -7,48 +7,53 @@
  */
 package org.opendaylight.protocol.bgp.parser;
 
-import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNotSame;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
 
 import java.net.UnknownHostException;
 import java.util.Collections;
+import java.util.Map;
 
 import org.junit.Test;
-
-import org.opendaylight.protocol.concepts.IPv4;
-import org.opendaylight.protocol.concepts.IPv4Address;
-import org.opendaylight.protocol.concepts.Metric;
-import org.opendaylight.protocol.concepts.TEMetric;
+import org.opendaylight.protocol.bgp.concepts.BGPAddressFamily;
+import org.opendaylight.protocol.bgp.concepts.BGPOrigin;
+import org.opendaylight.protocol.bgp.concepts.BGPSubsequentAddressFamily;
+import org.opendaylight.protocol.bgp.concepts.BGPTableType;
+import org.opendaylight.protocol.bgp.concepts.BaseBGPObjectState;
+import org.opendaylight.protocol.bgp.concepts.Community;
+import org.opendaylight.protocol.bgp.concepts.ExtendedCommunity;
+import org.opendaylight.protocol.bgp.concepts.IPv4NextHop;
 import org.opendaylight.protocol.bgp.linkstate.ISISAreaIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.LinkProtectionType;
-import org.opendaylight.protocol.bgp.linkstate.RouteTag;
-import org.opendaylight.protocol.bgp.linkstate.RouterIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.TopologyIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.TopologyNodeInformation;
 import org.opendaylight.protocol.bgp.linkstate.NetworkLinkState;
 import org.opendaylight.protocol.bgp.linkstate.NetworkNodeState;
 import org.opendaylight.protocol.bgp.linkstate.NetworkObjectState;
 import org.opendaylight.protocol.bgp.linkstate.NetworkPrefixState;
 import org.opendaylight.protocol.bgp.linkstate.NetworkRouteState;
-
-import org.opendaylight.protocol.bgp.concepts.BGPOrigin;
-import org.opendaylight.protocol.bgp.concepts.BaseBGPObjectState;
-import org.opendaylight.protocol.bgp.concepts.Community;
-import org.opendaylight.protocol.bgp.concepts.ExtendedCommunity;
-import org.opendaylight.protocol.bgp.concepts.IPv4NextHop;
-import org.opendaylight.protocol.bgp.parser.BGPLinkState;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
-import org.opendaylight.protocol.bgp.parser.BGPNodeState;
-import org.opendaylight.protocol.bgp.parser.BGPParsingException;
-import org.opendaylight.protocol.bgp.parser.BGPPrefixState;
-import org.opendaylight.protocol.bgp.parser.BGPRouteState;
+import org.opendaylight.protocol.bgp.linkstate.RouteTag;
+import org.opendaylight.protocol.bgp.linkstate.RouterIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.TopologyIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.TopologyNodeInformation;
+import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
+import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
+import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
+import org.opendaylight.protocol.bgp.parser.parameter.AS4BytesCapability;
+import org.opendaylight.protocol.bgp.parser.parameter.CapabilityParameter;
+import org.opendaylight.protocol.bgp.parser.parameter.GracefulCapability;
+import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
+import org.opendaylight.protocol.concepts.ASNumber;
+import org.opendaylight.protocol.concepts.IPv4;
+import org.opendaylight.protocol.concepts.IPv4Address;
+import org.opendaylight.protocol.concepts.Metric;
+import org.opendaylight.protocol.concepts.TEMetric;
+import org.opendaylight.protocol.framework.DocumentedException;
 import org.opendaylight.protocol.util.DefaultingTypesafeContainer;
+
+import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
 
 public class APITest {
@@ -76,40 +81,6 @@ public class APITest {
                assertTrue(e2.getCause() instanceof IllegalAccessException);
        }
 
-       @Test
-       public void testBGPHeaderParser() {
-               final BGPMessageHeader h = new BGPMessageHeader();
-               try {
-                       h.fromBytes(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) 0, (byte) 0 });
-                       fail("Exception should have occured.");
-               } catch (final IllegalArgumentException e) {
-                       assertEquals("Too few bytes in passed array. Passed: 18. Expected: >= " + BGPMessageHeader.COMMON_HEADER_LENGTH + ".",
-                                       e.getMessage());
-               }
-
-               h.fromBytes(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) 0,
-                               (byte) 27, (byte) 1 });
-
-               assertEquals(h.getType(), 1);
-               assertEquals(h.getLength(), 27);
-               assertTrue(h.isParsed());
-
-               final BGPMessageHeader hh = new BGPMessageHeader(1, 27);
-
-               final byte[] expected = 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) 0, (byte) 27, (byte) 1 };
-
-               assertArrayEquals(expected, hh.toBytes());
-
-               hh.setParsed();
-
-               assertFalse(hh.isParsed());
-       }
-
        @Test
        public void testPrefixes() throws UnknownHostException {
                final NetworkPrefixState state = new NetworkPrefixState(this.netObjState, Sets.<RouteTag> newTreeSet(), null);
@@ -136,4 +107,82 @@ public class APITest {
                assertEquals(l1, l1.newInstance());
                assertEquals(l1, new BGPLinkState(l1));
        }
+
+       @Test
+       public void testBGPParameter() {
+
+               final BGPTableType t = new BGPTableType(BGPAddressFamily.LinkState, BGPSubsequentAddressFamily.Unicast);
+               final BGPTableType t1 = new BGPTableType(BGPAddressFamily.IPv4, BGPSubsequentAddressFamily.Unicast);
+
+               final BGPParameter tlv1 = new MultiprotocolCapability(t);
+
+               final BGPParameter tlv2 = new MultiprotocolCapability(t1);
+
+               final Map<BGPTableType, Boolean> tt = Maps.newHashMap();
+               tt.put(t, true);
+               tt.put(t1, false);
+
+               final BGPParameter tlv3 = new GracefulCapability(false, 0, tt);
+
+               final BGPParameter tlv4 = new AS4BytesCapability(new ASNumber(40));
+
+               assertFalse(((GracefulCapability) tlv3).isRestartFlag());
+
+               assertEquals(0, ((GracefulCapability) tlv3).getRestartTimerValue());
+
+               assertEquals(tlv1.getType(), tlv2.getType());
+
+               assertFalse(tlv1.equals(tlv2));
+
+               assertNotSame(tlv1.hashCode(), tlv3.hashCode());
+
+               assertNotSame(tlv2.toString(), tlv3.toString());
+
+               assertEquals(((GracefulCapability) tlv3).getTableTypes(), tt);
+
+               assertNotSame(((CapabilityParameter) tlv1).getCode(), ((CapabilityParameter) tlv3).getCode());
+
+               assertEquals(((MultiprotocolCapability) tlv1).getSafi(), ((MultiprotocolCapability) tlv2).getSafi());
+
+               assertNotSame(((MultiprotocolCapability) tlv1).getAfi(), ((MultiprotocolCapability) tlv2).getAfi());
+
+               assertEquals(40, ((AS4BytesCapability) tlv4).getASNumber().getAsn());
+
+               assertEquals(new AS4BytesCapability(new ASNumber(40)).toString(), tlv4.toString());
+       }
+
+       @Test
+       public void testDocumentedException() {
+               final DocumentedException de = new BGPDocumentedException("Some message", BGPError.BAD_BGP_ID);
+               assertEquals("Some message", de.getMessage());
+               assertEquals(BGPError.BAD_BGP_ID, ((BGPDocumentedException) de).getError());
+               assertNull(((BGPDocumentedException) de).getData());
+       }
+
+       @Test
+       public void testBGPKeepAliveMessage() {
+               final BGPMessage msg = new BGPKeepAliveMessage();
+               assertTrue(msg instanceof BGPKeepAliveMessage);
+       }
+
+       @Test
+       public void testBGPNotificationMessage() {
+               final BGPMessage msg = new BGPNotificationMessage(BGPError.AS_PATH_MALFORMED);
+               assertTrue(msg instanceof BGPNotificationMessage);
+               assertEquals(BGPError.AS_PATH_MALFORMED, ((BGPNotificationMessage) msg).getError());
+               assertNull(((BGPNotificationMessage) msg).getData());
+       }
+
+       @Test
+       public void testBGPOpenMessage() {
+               final BGPMessage msg = new BGPOpenMessage(new ASNumber(58), (short) 5, null, null);
+               assertNull(((BGPOpenMessage) msg).getOptParams());
+       }
+
+       @Test
+       public void testToString() {
+               final BGPMessage o = new BGPOpenMessage(new ASNumber(58), (short) 5, null, null);
+               final BGPMessage n = new BGPNotificationMessage(BGPError.ATTR_FLAGS_MISSING);
+               assertNotSame(o.toString(), n.toString());
+       }
 }
index 1ad19c7e6e2ade624bbfda681b6bd7dc57f66531..83c12c60b9bde4dfc51a1787af8454cee215f3aa 100644 (file)
  */
 package org.opendaylight.protocol.bgp.parser.impl;
 
-import java.io.IOException;
 import java.util.Arrays;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.opendaylight.protocol.framework.DeserializerException;
-import org.opendaylight.protocol.framework.DocumentedException;
-import org.opendaylight.protocol.framework.ProtocolMessage;
-import org.opendaylight.protocol.framework.ProtocolMessageHeader;
-
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
-import org.opendaylight.protocol.bgp.parser.BGPParsingException;
 import org.opendaylight.protocol.bgp.parser.impl.message.BGPNotificationMessageParser;
 import org.opendaylight.protocol.bgp.parser.impl.message.BGPOpenMessageParser;
 import org.opendaylight.protocol.bgp.parser.impl.message.BGPUpdateMessageParser;
 import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
 import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
+import org.opendaylight.protocol.framework.DeserializerException;
+import org.opendaylight.protocol.framework.DocumentedException;
+import org.opendaylight.protocol.framework.ProtocolMessage;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
 import org.opendaylight.protocol.util.ByteArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.primitives.UnsignedBytes;
 
 /**
- *
+ * The byte array
  */
-public class BGPMessageFactory implements BGPMessageParser {
+public class BGPMessageFactory implements ProtocolMessageFactory {
 
        private final static Logger logger = LoggerFactory.getLogger(BGPMessageFactory.class);
 
+       final static int LENGTH_FIELD_LENGTH = 2; // bytes
+
+       private final static int TYPE_FIELD_LENGTH = 1; // bytes
+
+       final static int MARKER_LENGTH = 16; // bytes
+
+       public final static int COMMON_HEADER_LENGTH = LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH + MARKER_LENGTH;
+
        public BGPMessageFactory() {
        }
 
+       /*
+        * (non-Javadoc)
+        * @see org.opendaylight.protocol.bgp.parser.BGPMessageParser#parse(byte[])
+        */
        @Override
-       public BGPMessage parse(final byte[] bytes, final ProtocolMessageHeader msgH) throws DeserializerException, DocumentedException {
-               final BGPMessageHeader msgHeader = (BGPMessageHeader) msgH;
+       public BGPMessage parse(final byte[] bytes) throws DeserializerException, DocumentedException {
                if (bytes == null)
                        throw new IllegalArgumentException("Array of bytes is mandatory.");
-               if (msgHeader == null)
-                       throw new IllegalArgumentException("BGPMessageHeader is mandatory.");
-               if (msgHeader.getLength() < BGPMessageHeader.COMMON_HEADER_LENGTH)
-                       throw new BGPDocumentedException("Message length field not within valid range.", BGPError.BAD_MSG_LENGTH, ByteArray.intToBytes(msgHeader.getLength()));
-               if (bytes.length != (msgHeader.getLength() - BGPMessageHeader.COMMON_HEADER_LENGTH))
-                       throw new BGPParsingException("Size doesn't match size specified in header. Passed: " + bytes.length + "; Expected: "
-                                       + (msgHeader.getLength() - BGPMessageHeader.COMMON_HEADER_LENGTH) + ". " + msgHeader.getLength());
+               if (bytes.length < (COMMON_HEADER_LENGTH - MARKER_LENGTH)) {
+                       throw new IllegalArgumentException("Too few bytes in passed array. Passed: " + bytes.length + ". Expected: >= "
+                                       + COMMON_HEADER_LENGTH + ".");
+               }
+               /*
+                * byte array starts with message length
+                */
+               // final byte[] ones = new byte[MARKER_LENGTH];
+               // Arrays.fill(ones, (byte)0xff);
+               // if (Arrays.equals(bytes, ones))
+               // throw new BGPDocumentedException("Marker not set to ones.", BGPError.CONNECTION_NOT_SYNC);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(bytes, 0, LENGTH_FIELD_LENGTH));
+               final int messageType = UnsignedBytes.toInt(bytes[LENGTH_FIELD_LENGTH]);
+
+               final byte[] msgBody = ByteArray.cutBytes(bytes, LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH);
+
+               if (messageLength < COMMON_HEADER_LENGTH)
+                       throw new BGPDocumentedException("Message length field not within valid range.", BGPError.BAD_MSG_LENGTH, ByteArray.subByte(
+                                       bytes, 0, LENGTH_FIELD_LENGTH));
+               if (msgBody.length != messageLength - COMMON_HEADER_LENGTH)
+                       throw new DeserializerException("Size doesn't match size specified in header. Passed: " + msgBody.length + "; Expected: "
+                                       + (messageLength - COMMON_HEADER_LENGTH) + ". ");
 
-               logger.debug("Attempt to parse message from bytes: {}", ByteArray.bytesToHexString(bytes));
+               logger.debug("Attempt to parse message from bytes: {}", ByteArray.bytesToHexString(msgBody));
 
                BGPMessage msg = null;
 
-               switch (msgHeader.getType()) {
+               switch (messageType) {
                case 1:
-                       msg = BGPOpenMessageParser.parse(bytes);
+                       msg = BGPOpenMessageParser.parse(msgBody);
                        logger.debug("Received and parsed Open Message: {}", msg);
                        break;
                case 2:
-                       msg = BGPUpdateMessageParser.parse(bytes, msgHeader.getLength());
+                       msg = BGPUpdateMessageParser.parse(msgBody, messageLength);
                        logger.debug("Received and parsed Update Message: {}", msg);
                        break;
                case 3:
-                       msg = BGPNotificationMessageParser.parse(bytes);
+                       msg = BGPNotificationMessageParser.parse(msgBody);
                        logger.debug("Received and parsed Notification Message: {}", msg);
                        break;
                case 4:
                        msg = new BGPKeepAliveMessage();
-                       if (msgHeader.getLength() != BGPMessageHeader.COMMON_HEADER_LENGTH)
-                               throw new BGPDocumentedException("Message length field not within valid range.", BGPError.BAD_MSG_LENGTH, ByteArray.intToBytes(msgHeader.getLength()));
+                       if (messageLength != COMMON_HEADER_LENGTH)
+                               throw new BGPDocumentedException("Message length field not within valid range.", BGPError.BAD_MSG_LENGTH, ByteArray.subByte(
+                                               bytes, 0, LENGTH_FIELD_LENGTH));
                        break;
                default:
-                       throw new BGPDocumentedException("Unhandled message type " + msgHeader.getType(), BGPError.BAD_MSG_TYPE, ByteArray.intToBytes(msgHeader.getType()));
+                       throw new BGPDocumentedException("Unhandled message type " + messageType, BGPError.BAD_MSG_TYPE, new byte[] { bytes[LENGTH_FIELD_LENGTH] });
                }
                return msg;
        }
@@ -110,20 +133,31 @@ public class BGPMessageFactory implements BGPMessageParser {
                        throw new IllegalArgumentException("Unknown instance of BGPMessage. Passed " + bgpMsg.getClass());
                }
 
-               final BGPMessageHeader msgHeader = new BGPMessageHeader(msgType, msgBody.length + BGPMessageHeader.COMMON_HEADER_LENGTH);
-
-               final byte[] headerBytes = msgHeader.toBytes();
+               final byte[] headerBytes = headerToBytes(msgBody.length + COMMON_HEADER_LENGTH, msgType);
                final byte[] retBytes = new byte[headerBytes.length + msgBody.length];
 
                ByteArray.copyWhole(headerBytes, retBytes, 0);
-               ByteArray.copyWhole(msgBody, retBytes, BGPMessageHeader.COMMON_HEADER_LENGTH);
+               ByteArray.copyWhole(msgBody, retBytes, COMMON_HEADER_LENGTH);
 
                logger.trace("Serialized BGP message {}.", Arrays.toString(retBytes));
                return retBytes;
        }
 
-       @Override
-       public void close() throws IOException {
-               // nothing to close
+       /**
+        * Serializes this BGP Message header to byte array.
+        * 
+        * @return byte array representation of this header
+        */
+       public byte[] headerToBytes(final int msgLength, final int msgType) {
+               final byte[] retBytes = new byte[COMMON_HEADER_LENGTH];
+
+               Arrays.fill(retBytes, 0, MARKER_LENGTH, (byte) 0xff);
+
+               System.arraycopy(ByteArray.intToBytes(msgLength), Integer.SIZE / Byte.SIZE - LENGTH_FIELD_LENGTH, retBytes, MARKER_LENGTH,
+                               LENGTH_FIELD_LENGTH);
+
+               retBytes[MARKER_LENGTH + LENGTH_FIELD_LENGTH] = (byte) msgType;
+
+               return retBytes;
        }
 }
index 7d665e94bb4bddfa22476908129192ca88601c2d..9480e00a26d0b48146138cc80ddb55bcb99e5923 100644 (file)
@@ -13,28 +13,27 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
 import org.opendaylight.protocol.bgp.concepts.BGPAddressFamily;
 import org.opendaylight.protocol.bgp.concepts.BGPSubsequentAddressFamily;
 import org.opendaylight.protocol.bgp.concepts.BGPTableType;
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BGPError;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateEvent;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateSynchronized;
+import org.opendaylight.protocol.bgp.parser.impl.BGPMessageFactory;
 import org.opendaylight.protocol.bgp.parser.impl.BGPUpdateEventBuilder;
 import org.opendaylight.protocol.bgp.parser.impl.IPv6MP;
 import org.opendaylight.protocol.bgp.parser.impl.PathAttribute;
 import org.opendaylight.protocol.bgp.parser.impl.PathAttribute.TypeCode;
 import org.opendaylight.protocol.bgp.parser.impl.message.update.PathAttributeParser;
-import org.opendaylight.protocol.util.ByteArray;
 import org.opendaylight.protocol.concepts.IPv4;
 import org.opendaylight.protocol.concepts.IPv4Address;
 import org.opendaylight.protocol.concepts.Prefix;
+import org.opendaylight.protocol.util.ByteArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.collect.Lists;
 
 /**
@@ -91,7 +90,7 @@ public class BGPUpdateMessageParser {
                byteOffset += TOTAL_PATH_ATTR_LENGTH_SIZE;
                eventBuilder.setTotalPathAttrLength(totalPathAttrLength);
 
-               if (withdrawnRoutesLength + totalPathAttrLength + BGPMessageHeader.COMMON_HEADER_LENGTH > msgLength)
+               if (withdrawnRoutesLength + totalPathAttrLength + BGPMessageFactory.COMMON_HEADER_LENGTH > msgLength)
                        throw new BGPDocumentedException("Message length inconsistent with withdrawn router length.", BGPError.MALFORMED_ATTR_LIST);
 
                if (withdrawnRoutesLength == 0 && totalPathAttrLength == 0) {
index 50494837e2a9459ff6f24b7830319551236badb6..3cf87a6462f1ad158dfeeaa7ac00c98304ee403c 100644 (file)
@@ -15,49 +15,35 @@ import java.util.Map.Entry;
 import java.util.Set;
 import java.util.SortedSet;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
 import org.opendaylight.protocol.bgp.concepts.BGPSubsequentAddressFamily;
 import org.opendaylight.protocol.bgp.concepts.NextHop;
-import org.opendaylight.protocol.bgp.parser.BGPParsingException;
-import org.opendaylight.protocol.bgp.parser.impl.BGPLinkMP;
-import org.opendaylight.protocol.bgp.parser.impl.BGPNodeMP;
-import org.opendaylight.protocol.bgp.parser.impl.ByteList;
-import org.opendaylight.protocol.bgp.parser.impl.MPReach;
-import org.opendaylight.protocol.util.ByteArray;
-import org.opendaylight.protocol.concepts.ASNumber;
-import org.opendaylight.protocol.concepts.Bandwidth;
-import org.opendaylight.protocol.concepts.IGPMetric;
-import org.opendaylight.protocol.concepts.IPv4Address;
-import org.opendaylight.protocol.concepts.IPv4Prefix;
-import org.opendaylight.protocol.concepts.IPv6;
-import org.opendaylight.protocol.concepts.IPv6Address;
-import org.opendaylight.protocol.concepts.IPv6Prefix;
-import org.opendaylight.protocol.concepts.ISOSystemIdentifier;
-import org.opendaylight.protocol.concepts.Metric;
-import org.opendaylight.protocol.concepts.Prefix;
-import org.opendaylight.protocol.concepts.SharedRiskLinkGroup;
-import org.opendaylight.protocol.concepts.TEMetric;
 import org.opendaylight.protocol.bgp.linkstate.AdministrativeGroup;
 import org.opendaylight.protocol.bgp.linkstate.AreaIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.DomainIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.ExtendedRouteTag;
 import org.opendaylight.protocol.bgp.linkstate.IPv4InterfaceIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.IPv4PrefixIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.IPv4RouterIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.IPv6InterfaceIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.IPv6PrefixIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.IPv6RouterIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.ISISAreaIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.ISISLANIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.ISISNetworkPrefixState;
 import org.opendaylight.protocol.bgp.linkstate.ISISRouterIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.InterfaceIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.LinkAnchor;
 import org.opendaylight.protocol.bgp.linkstate.LinkIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.LinkProtectionType;
 import org.opendaylight.protocol.bgp.linkstate.MPLSProtocol;
+import org.opendaylight.protocol.bgp.linkstate.NetworkLinkImpl;
+import org.opendaylight.protocol.bgp.linkstate.NetworkLinkState;
+import org.opendaylight.protocol.bgp.linkstate.NetworkNodeImpl;
+import org.opendaylight.protocol.bgp.linkstate.NetworkObjectState;
+import org.opendaylight.protocol.bgp.linkstate.NetworkPrefixState;
 import org.opendaylight.protocol.bgp.linkstate.NodeIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.OSPFInterfaceIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.OSPFNetworkPrefixState;
 import org.opendaylight.protocol.bgp.linkstate.OSPFPrefixIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.OSPFRouteType;
 import org.opendaylight.protocol.bgp.linkstate.OSPFRouterIdentifier;
@@ -69,14 +55,28 @@ import org.opendaylight.protocol.bgp.linkstate.SourceProtocol;
 import org.opendaylight.protocol.bgp.linkstate.TopologyIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.TopologyNodeInformation;
 import org.opendaylight.protocol.bgp.linkstate.UnnumberedLinkIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.ISISNetworkPrefixState;
-import org.opendaylight.protocol.bgp.linkstate.NetworkObjectState;
-import org.opendaylight.protocol.bgp.linkstate.NetworkPrefixState;
-import org.opendaylight.protocol.bgp.linkstate.OSPFNetworkPrefixState;
-import org.opendaylight.protocol.bgp.linkstate.IPv4PrefixIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.IPv6PrefixIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.NetworkLinkImpl;
-import org.opendaylight.protocol.bgp.linkstate.NetworkNodeImpl;
+import org.opendaylight.protocol.bgp.parser.BGPParsingException;
+import org.opendaylight.protocol.bgp.parser.impl.BGPLinkMP;
+import org.opendaylight.protocol.bgp.parser.impl.BGPNodeMP;
+import org.opendaylight.protocol.bgp.parser.impl.ByteList;
+import org.opendaylight.protocol.bgp.parser.impl.MPReach;
+import org.opendaylight.protocol.concepts.ASNumber;
+import org.opendaylight.protocol.concepts.Bandwidth;
+import org.opendaylight.protocol.concepts.IGPMetric;
+import org.opendaylight.protocol.concepts.IPv4Address;
+import org.opendaylight.protocol.concepts.IPv4Prefix;
+import org.opendaylight.protocol.concepts.IPv6;
+import org.opendaylight.protocol.concepts.IPv6Address;
+import org.opendaylight.protocol.concepts.IPv6Prefix;
+import org.opendaylight.protocol.concepts.ISOSystemIdentifier;
+import org.opendaylight.protocol.concepts.Metric;
+import org.opendaylight.protocol.concepts.Prefix;
+import org.opendaylight.protocol.concepts.SharedRiskLinkGroup;
+import org.opendaylight.protocol.concepts.TEMetric;
+import org.opendaylight.protocol.util.ByteArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Charsets;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
@@ -498,7 +498,7 @@ public class LinkStateParser {
 
                final Set<SharedRiskLinkGroup> sharedRiskLinkGroups = Sets.newHashSet();
                final Set<MPLSProtocol> enabledMPLSProtocols = Sets.newHashSet();
-               final NetworkLinkImpl link = new NetworkLinkImpl(linkId);
+               NetworkLinkState state = NetworkLinkState.EMPTY;
 
                // FIXME: we should put these somewhere
                final Set<RouterIdentifier> localIds = Sets.newHashSet();
@@ -532,16 +532,16 @@ public class LinkStateParser {
                                        logger.trace("Parsed IPv6 Router-ID of remote node: {}", ripv6);
                                        break;
                                case 1088:
-                                       link.setAdministrativeGroup(new AdministrativeGroup(ByteArray.bytesToLong(value)));
-                                       logger.trace("Parsed Administrative Group {}", link.currentState().getAdministrativeGroup());
+                                       state = state.withAdministrativeGroup(new AdministrativeGroup(ByteArray.bytesToLong(value)));
+                                       logger.trace("Parsed Administrative Group {}", state.getAdministrativeGroup());
                                        break;
                                case 1089:
-                                       link.setMaximumBandwidth(new Bandwidth(ByteArray.bytesToFloat(value)));
-                                       logger.trace("Parsed Max Bandwidth {}", link.currentState().getMaximumBandwidth());
+                                       state = state.withMaximumBandwidth(new Bandwidth(ByteArray.bytesToFloat(value)));
+                                       logger.trace("Parsed Max Bandwidth {}", state.getMaximumBandwidth());
                                        break;
                                case 1090:
-                                       link.setMaximumReservableBandwidth(new Bandwidth(ByteArray.bytesToFloat(value)));
-                                       logger.trace("Parsed Max Reservable Bandwidth {}", link.currentState().getMaximumReservableBandwidth());
+                                       state = state.withReservableBandwidth(new Bandwidth(ByteArray.bytesToFloat(value)));
+                                       logger.trace("Parsed Max Reservable Bandwidth {}", state.getMaximumReservableBandwidth());
                                        break;
                                case 1091:
                                        int index = 0;
@@ -550,16 +550,16 @@ public class LinkStateParser {
                                                unreservedBandwidth[i] = new Bandwidth(ByteArray.bytesToFloat(ByteArray.subByte(value, index, 4)));
                                                index += 4;
                                        }
-                                       link.setUnreservedBandwidth(unreservedBandwidth);
-                                       logger.trace("Parsed Unreserved Bandwidth {}", Arrays.toString(link.currentState().getUnreservedBandwidth()));
+                                       state = state.withUnreservedBandwidth(unreservedBandwidth);
+                                       logger.trace("Parsed Unreserved Bandwidth {}", Arrays.toString(state.getUnreservedBandwidth()));
                                        break;
                                case 1092:
-                                       link.setMetric(TEMetric.class, new TEMetric(ByteArray.bytesToInt(value)));
-                                       logger.trace("Parsed Metric {}", link.currentState().getMetric(TEMetric.class));
+                                       state = state.withMetric(TEMetric.class, new TEMetric(ByteArray.bytesToInt(value)));
+                                       logger.trace("Parsed Metric {}", state.getMetric(TEMetric.class));
                                        break;
                                case 1093:
-                                       link.setProtectionType(parseLinkProtectionType(UnsignedBytes.toInt(value[0])));
-                                       logger.trace("Parsed Link Protection Type {}", link.currentState().getProtectionType());
+                                       state = state.withProtectionType(parseLinkProtectionType(UnsignedBytes.toInt(value[0])));
+                                       logger.trace("Parsed Link Protection Type {}", state.getProtectionType());
                                        break;
                                case 1094:
                                        final boolean[] bits = ByteArray.parseBits(value[0]);
@@ -572,8 +572,8 @@ public class LinkStateParser {
                                        logger.trace("Parsed MPLS Protocols: {}", Arrays.toString(enabledMPLSProtocols.toArray()));
                                        break;
                                case 1095:
-                                       link.setDefaultMetric(new IGPMetric(ByteArray.bytesToLong(value)));
-                                       logger.trace("Parsed Metric {}", link.currentState().getDefaultMetric());
+                                       state = state.withDefaultMetric(new IGPMetric(ByteArray.bytesToLong(value)));
+                                       logger.trace("Parsed Metric {}", state.getDefaultMetric());
                                        break;
                                case 1096:
                                        int i = 0;
@@ -596,9 +596,10 @@ public class LinkStateParser {
                                }
                        }
                }
-               link.setEnabledMPLSProtocols(enabledMPLSProtocols);
-               link.setSharedRiskLinkGroups(sharedRiskLinkGroups);
-               link.currentState().withSymbolicName(name);
+               state = state.withEnabledMPLSProtocols(enabledMPLSProtocols);
+               state = state.withSharedRiskLinkGroups(sharedRiskLinkGroups);
+               state = state.withSymbolicName(name);
+               final NetworkLinkImpl link = new NetworkLinkImpl(linkId, state);
                logger.debug("Finished parsing Link Attributes.");
                return link;
        }
@@ -630,15 +631,15 @@ public class LinkStateParser {
                                        break;
                                case 1024:
                                        final boolean[] flags = ByteArray.parseBits(value[0]);
-                                       node.setExternal(flags[2]);
-                                       node.setAreaBorderRouter(flags[3]);
+                                       node.currentState().withExternal(flags[2]);
+                                       node.currentState().withAreaBorderRouter(flags[3]);
                                        logger.trace("Parsed External bit {}, area border router {}.", flags[2], flags[3]);
                                        break;
                                case 1025:
                                        logger.debug("Ignoring opaque value: {}.", Arrays.toString(value));
                                        break;
                                case 1026:
-                                       node.setDynamicHostname(new String(value, Charsets.US_ASCII));
+                                       node.currentState().withDynamicHostname(new String(value, Charsets.US_ASCII));
                                        logger.trace("Parsed Node Name {}", node.currentState().getDynamicHostname());
                                        break;
                                case 1027:
@@ -662,9 +663,9 @@ public class LinkStateParser {
                        }
                }
 
-               node.setAreaMembership(areaMembership);
-               node.setAlternativeIdentifiers(ids);
-               node.setTopologyMembership(topologyMembership);
+               node.currentState().withAreaMembership(areaMembership);
+               node.currentState().withIdentifierAlternatives(ids);
+               node.currentState().withTopologyMembership(topologyMembership);
                logger.debug("Finished parsing Node Attributes.");
                return node;
        }
index fd739003535854bdaa84c92700ffe873bc787f99..1181911a93dbf27888432ba69fedac3df7ef5f1f 100644 (file)
@@ -22,9 +22,6 @@ import java.util.Set;
 
 import org.junit.BeforeClass;
 import org.junit.Test;
-
-import org.opendaylight.protocol.concepts.Identifier;
-
 import org.opendaylight.protocol.bgp.concepts.ASPath;
 import org.opendaylight.protocol.bgp.concepts.BGPAddressFamily;
 import org.opendaylight.protocol.bgp.concepts.BGPAggregator;
@@ -38,20 +35,32 @@ import org.opendaylight.protocol.bgp.concepts.ExtendedCommunity;
 import org.opendaylight.protocol.bgp.concepts.IPv4NextHop;
 import org.opendaylight.protocol.bgp.concepts.IPv6NextHop;
 import org.opendaylight.protocol.bgp.concepts.Inet4SpecificExtendedCommunity;
+import org.opendaylight.protocol.bgp.linkstate.AreaIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.DomainIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.IPv4InterfaceIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.ISISAreaIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.LinkAnchor;
+import org.opendaylight.protocol.bgp.linkstate.LinkIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.LinkProtectionType;
+import org.opendaylight.protocol.bgp.linkstate.NetworkLinkState;
+import org.opendaylight.protocol.bgp.linkstate.NetworkNodeState;
+import org.opendaylight.protocol.bgp.linkstate.NetworkObjectState;
+import org.opendaylight.protocol.bgp.linkstate.NetworkRouteState;
+import org.opendaylight.protocol.bgp.linkstate.NodeIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.NodeIdentifierFactory;
+import org.opendaylight.protocol.bgp.linkstate.OSPFInterfaceIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.OSPFRouterIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.OSPFv3LANIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.RouterIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.TopologyIdentifier;
+import org.opendaylight.protocol.bgp.linkstate.TopologyNodeInformation;
 import org.opendaylight.protocol.bgp.parser.BGPLink;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
 import org.opendaylight.protocol.bgp.parser.BGPNode;
 import org.opendaylight.protocol.bgp.parser.BGPParameter;
 import org.opendaylight.protocol.bgp.parser.BGPRoute;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateEvent;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateMessage;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateSynchronized;
-import org.opendaylight.protocol.bgp.parser.impl.BGPAggregatorImpl;
-import org.opendaylight.protocol.bgp.parser.impl.BGPMessageFactory;
-import org.opendaylight.protocol.bgp.parser.impl.BGPUpdateMessageImpl;
-import org.opendaylight.protocol.bgp.parser.impl.IPv4MP;
-import org.opendaylight.protocol.bgp.parser.impl.IPv6MP;
-import org.opendaylight.protocol.bgp.parser.impl.PathAttribute;
 import org.opendaylight.protocol.bgp.parser.impl.PathAttribute.TypeCode;
 import org.opendaylight.protocol.bgp.parser.impl.message.BGPUpdateMessageParser;
 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
@@ -60,8 +69,6 @@ import org.opendaylight.protocol.bgp.util.BGPIPv4RouteImpl;
 import org.opendaylight.protocol.bgp.util.BGPIPv6RouteImpl;
 import org.opendaylight.protocol.bgp.util.BGPLinkImpl;
 import org.opendaylight.protocol.bgp.util.BGPNodeImpl;
-import org.opendaylight.protocol.util.ByteArray;
-import org.opendaylight.protocol.util.DefaultingTypesafeContainer;
 import org.opendaylight.protocol.concepts.ASNumber;
 import org.opendaylight.protocol.concepts.IGPMetric;
 import org.opendaylight.protocol.concepts.IPv4;
@@ -69,26 +76,11 @@ import org.opendaylight.protocol.concepts.IPv4Address;
 import org.opendaylight.protocol.concepts.IPv4Prefix;
 import org.opendaylight.protocol.concepts.IPv6;
 import org.opendaylight.protocol.concepts.IPv6Address;
+import org.opendaylight.protocol.concepts.Identifier;
 import org.opendaylight.protocol.concepts.Metric;
-import org.opendaylight.protocol.bgp.linkstate.AreaIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.DomainIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.IPv4InterfaceIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.ISISAreaIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.LinkAnchor;
-import org.opendaylight.protocol.bgp.linkstate.LinkIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.LinkProtectionType;
-import org.opendaylight.protocol.bgp.linkstate.NodeIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.NodeIdentifierFactory;
-import org.opendaylight.protocol.bgp.linkstate.OSPFInterfaceIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.OSPFRouterIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.OSPFv3LANIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.RouterIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.TopologyIdentifier;
-import org.opendaylight.protocol.bgp.linkstate.TopologyNodeInformation;
-import org.opendaylight.protocol.bgp.linkstate.NetworkLinkState;
-import org.opendaylight.protocol.bgp.linkstate.NetworkNodeState;
-import org.opendaylight.protocol.bgp.linkstate.NetworkObjectState;
-import org.opendaylight.protocol.bgp.linkstate.NetworkRouteState;
+import org.opendaylight.protocol.util.ByteArray;
+import org.opendaylight.protocol.util.DefaultingTypesafeContainer;
+
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 
@@ -173,11 +165,11 @@ public class BGPParserTest {
         */
        @Test
        public void testGetUpdateMessage1() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(0), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
 
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(0), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(0), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(0), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateMessage);
                final BGPUpdateMessage message = (BGPUpdateMessage) ret;
@@ -300,11 +292,10 @@ public class BGPParserTest {
         */
        @Test
        public void testGetUpdateMessage2() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(1), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(1), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(1), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(1), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateMessage);
                final BGPUpdateMessage message = (BGPUpdateMessage) ret;
@@ -410,12 +401,10 @@ public class BGPParserTest {
         */
        @Test
        public void testGetUpdateMessage3() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(2), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(2), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
-
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(2), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(2), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
                assertTrue(ret instanceof BGPUpdateMessage);
                final BGPUpdateMessage message = (BGPUpdateMessage) ret;
 
@@ -516,11 +505,10 @@ public class BGPParserTest {
         */
        @Test
        public void testGetUpdateMessage4() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(3), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(3), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(3), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(3), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateMessage);
                final BGPUpdateMessage message = (BGPUpdateMessage) ret;
@@ -599,11 +587,10 @@ public class BGPParserTest {
         */
        @Test
        public void testGetUpdateMessage5() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(4), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(4), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(4), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(4), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateMessage);
                final BGPUpdateMessage message = (BGPUpdateMessage) ret;
@@ -630,11 +617,10 @@ public class BGPParserTest {
         */
        @Test
        public void testEORIpv4() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(5), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(5), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(5), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(5), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateSynchronized);
                final BGPUpdateSynchronized message = (BGPUpdateSynchronized) ret;
@@ -667,11 +653,10 @@ public class BGPParserTest {
         */
        @Test
        public void testEORIpv6() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(6), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(6), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(6), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(6), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateSynchronized);
                final BGPUpdateSynchronized message = (BGPUpdateSynchronized) ret;
@@ -706,11 +691,10 @@ public class BGPParserTest {
         */
        @Test
        public void testEORLS() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(7), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(7), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(7), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(7), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateSynchronized);
                final BGPUpdateSynchronized message = (BGPUpdateSynchronized) ret;
@@ -881,11 +865,10 @@ public class BGPParserTest {
         */
        @Test
        public void testBGPLink() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(8), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(8), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(8), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(8), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateMessage);
                final BGPUpdateMessage message = (BGPUpdateMessage) ret;
@@ -1014,11 +997,10 @@ public class BGPParserTest {
         */
        @Test
        public void testBGPNode() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(9), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(9), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(inputBytes.get(9), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(inputBytes.get(9), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent ret = BGPUpdateMessageParser.parse(body, messageLength);
 
                assertTrue(ret instanceof BGPUpdateMessage);
                final BGPUpdateMessage message = (BGPUpdateMessage) ret;
@@ -1095,12 +1077,9 @@ public class BGPParserTest {
         */
        @Test
        public void testOpenMessage() throws Exception {
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(inputBytes.get(13), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(inputBytes.get(13), BGPMessageHeader.COMMON_HEADER_LENGTH);
                final BGPMessageFactory msgFactory = new BGPMessageFactory();
-               final BGPOpenMessage open = (BGPOpenMessage) msgFactory.parse(body, header);
+               final BGPOpenMessage open = (BGPOpenMessage) msgFactory.parse(ByteArray.cutBytes(inputBytes.get(13),
+                               BGPMessageFactory.MARKER_LENGTH));
                final Set<BGPTableType> types = Sets.newHashSet();
                for (final BGPParameter param : open.getOptParams()) {
                        if (param instanceof MultiprotocolCapability) {
@@ -1110,7 +1089,6 @@ public class BGPParserTest {
                final Set<BGPTableType> expected = Sets.newHashSet(new BGPTableType(BGPAddressFamily.IPv4, BGPSubsequentAddressFamily.Unicast),
                                new BGPTableType(BGPAddressFamily.IPv6, BGPSubsequentAddressFamily.Unicast),
                                new BGPTableType(BGPAddressFamily.LinkState, BGPSubsequentAddressFamily.Linkstate));
-               msgFactory.close();
                assertEquals(expected, types);
        }
 
index 72d6a4eabf63fdce9b6670e15eb01f01268ff259..41b8623edf949d26d08f1f4c0db2518435c2ed26 100644 (file)
@@ -17,7 +17,6 @@ import java.util.Set;
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.protocol.bgp.concepts.BGPObject;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
 import org.opendaylight.protocol.bgp.parser.BGPNode;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateEvent;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateMessage;
@@ -32,11 +31,10 @@ public class BGPUpdateMessageParserTest {
        public void testNodeParsing() throws Exception {
                final List<byte[]> result = HexDumpBGPFileParser.parseMessages(new File(this.getClass().getResource("/bgp-update-nodes.txt").getFile()));
                assertEquals(1, result.size());
-               final BGPMessageHeader header = new BGPMessageHeader();
-               header.fromBytes(ByteArray.subByte(result.get(0), 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
-
-               final byte[] body = ByteArray.cutBytes(result.get(0), BGPMessageHeader.COMMON_HEADER_LENGTH);
-               final BGPUpdateEvent event = BGPUpdateMessageParser.parse(body, header.getLength());
+               final byte[] body = ByteArray.cutBytes(result.get(0), BGPMessageFactory.COMMON_HEADER_LENGTH);
+               final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(result.get(0), BGPMessageFactory.MARKER_LENGTH,
+                               BGPMessageFactory.LENGTH_FIELD_LENGTH));
+               final BGPUpdateEvent event = BGPUpdateMessageParser.parse(body, messageLength);
                final BGPUpdateMessage updateMessage = (BGPUpdateMessage) event;
                final Set<BGPObject> addedObjects = updateMessage.getAddedObjects();
                assertEquals(14, addedObjects.size());
index 6cb71f4cd7cb493079bba72e917d0905ec446bc8..29d68d6679c3737b2217ce499d83238251554761 100644 (file)
@@ -23,20 +23,6 @@ import org.opendaylight.protocol.bgp.concepts.Inet4SpecificExtendedCommunity;
 import org.opendaylight.protocol.bgp.concepts.OpaqueExtendedCommunity;
 import org.opendaylight.protocol.bgp.concepts.RouteOriginCommunity;
 import org.opendaylight.protocol.bgp.concepts.RouteTargetCommunity;
-import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
-import org.opendaylight.protocol.bgp.parser.BGPParsingException;
-import org.opendaylight.protocol.bgp.parser.impl.BGPAggregatorImpl;
-import org.opendaylight.protocol.bgp.parser.impl.BGPLinkMP;
-import org.opendaylight.protocol.bgp.parser.impl.BGPMessageFactory;
-import org.opendaylight.protocol.bgp.parser.impl.BGPUpdateMessageImpl;
-import org.opendaylight.protocol.bgp.parser.impl.ByteList;
-import org.opendaylight.protocol.bgp.parser.impl.message.update.CommunitiesParser;
-import org.opendaylight.protocol.bgp.parser.impl.message.update.MPReachParser;
-
-import org.opendaylight.protocol.concepts.ASNumber;
-import org.opendaylight.protocol.concepts.IPv4;
-import org.opendaylight.protocol.concepts.IPv4Address;
-import org.opendaylight.protocol.concepts.ISOSystemIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.IPv4InterfaceIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.ISISLANIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.ISISRouterIdentifier;
@@ -46,6 +32,17 @@ import org.opendaylight.protocol.bgp.linkstate.LinkIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.NodeIdentifier;
 import org.opendaylight.protocol.bgp.linkstate.NodeIdentifierFactory;
 import org.opendaylight.protocol.bgp.linkstate.SourceProtocol;
+import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
+import org.opendaylight.protocol.bgp.parser.BGPParsingException;
+import org.opendaylight.protocol.bgp.parser.impl.message.update.CommunitiesParser;
+import org.opendaylight.protocol.bgp.parser.impl.message.update.MPReachParser;
+import org.opendaylight.protocol.concepts.ASNumber;
+import org.opendaylight.protocol.concepts.IPv4;
+import org.opendaylight.protocol.concepts.IPv4Address;
+import org.opendaylight.protocol.concepts.ISOSystemIdentifier;
+import org.opendaylight.protocol.framework.DeserializerException;
+import org.opendaylight.protocol.framework.DocumentedException;
+
 import com.google.common.collect.Sets;
 
 public class ComplementaryTest {
@@ -191,6 +188,21 @@ public class ComplementaryTest {
                assertEquals("Address Family Identifier: '6' not supported.", msg);
        }
 
+       @Test
+       public void testBGPHeaderParser() throws IOException {
+               final BGPMessageFactory h = new BGPMessageFactory();
+               try {
+                       h.parse(new byte[] { (byte) 0, (byte) 0 });
+                       fail("Exception should have occured.");
+               } catch (final IllegalArgumentException e) {
+                       assertEquals("Too few bytes in passed array. Passed: 2. Expected: >= 19.", e.getMessage());
+               } catch (final DeserializerException e) {
+                       fail("Not this exception should have occured:" + e);
+               } catch (final DocumentedException e) {
+                       fail("Not this exception should have occured:" + e);
+               }
+       }
+
        @Test
        public void testByteList() {
                final ByteList b1 = new ByteList();
@@ -214,7 +226,6 @@ public class ComplementaryTest {
                } catch (final IllegalArgumentException e) {
                        ex = e.getMessage();
                }
-               parser.close();
                assertEquals("BGPMessage is mandatory.", ex);
        }
 }
index cbc2b1f3a77894ef27ea0259e70917d291b3599e..14785280c54a67374605cbaa6e75f3384f9d2e66 100644 (file)
@@ -7,23 +7,20 @@
  */
 package org.opendaylight.protocol.bgp.parser.mock;
 
-import java.io.IOException;
 import java.util.Map;
 
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
-
 import org.opendaylight.protocol.framework.DeserializerException;
 import org.opendaylight.protocol.framework.DocumentedException;
 import org.opendaylight.protocol.framework.ProtocolMessage;
-import org.opendaylight.protocol.framework.ProtocolMessageHeader;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
 
 /**
  * Mock implementation of {@link BGPMessageParser}. It implements the required interface by having two internal maps,
  * each used in one of the methods. It looks up the key provided to the method and returns whatever value is stored in
  * the map.
  */
-public class BGPMessageParserMock implements BGPMessageParser {
+public class BGPMessageParserMock implements ProtocolMessageFactory {
        private final Map<byte[], BGPMessage> messages;
 
        /**
@@ -34,12 +31,7 @@ public class BGPMessageParserMock implements BGPMessageParser {
        }
 
        @Override
-       public void close() throws IOException {
-               // nothing
-       }
-
-       @Override
-       public BGPMessage parse(final byte[] bytes, final ProtocolMessageHeader msgHeader) throws DeserializerException, DocumentedException {
+       public BGPMessage parse(final byte[] bytes) throws DeserializerException, DocumentedException {
                final BGPMessage ret = this.messages.get(bytes);
                if (ret == null)
                        throw new IllegalArgumentException("Undefined message encountered");
index 22e056a6796c6c99ff8fb7568581d2c40829b4bf..8ae4abe3734d1682cb19ff55141284ad35cd524c 100644 (file)
@@ -36,26 +36,24 @@ import org.opendaylight.protocol.bgp.concepts.Community;
 import org.opendaylight.protocol.bgp.concepts.ExtendedCommunity;
 import org.opendaylight.protocol.bgp.concepts.IPv6NextHop;
 import org.opendaylight.protocol.bgp.concepts.NextHop;
+import org.opendaylight.protocol.bgp.linkstate.NetworkObjectState;
+import org.opendaylight.protocol.bgp.linkstate.NetworkRouteState;
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
 import org.opendaylight.protocol.bgp.parser.BGPParameter;
 import org.opendaylight.protocol.bgp.parser.BGPRoute;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateMessage;
 import org.opendaylight.protocol.bgp.parser.impl.BGPUpdateMessageImpl;
 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
-import org.opendaylight.protocol.bgp.parser.mock.BGPMessageParserMock;
 import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
 import org.opendaylight.protocol.bgp.util.BGPIPv6RouteImpl;
-
-import org.opendaylight.protocol.concepts.Identifier;
-import org.opendaylight.protocol.framework.DeserializerException;
-import org.opendaylight.protocol.framework.DocumentedException;
 import org.opendaylight.protocol.concepts.ASNumber;
 import org.opendaylight.protocol.concepts.IPv6Address;
 import org.opendaylight.protocol.concepts.IPv6Prefix;
+import org.opendaylight.protocol.concepts.Identifier;
 import org.opendaylight.protocol.concepts.Prefix;
-import org.opendaylight.protocol.bgp.linkstate.NetworkObjectState;
-import org.opendaylight.protocol.bgp.linkstate.NetworkRouteState;
+import org.opendaylight.protocol.framework.DeserializerException;
+import org.opendaylight.protocol.framework.DocumentedException;
+
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
@@ -91,11 +89,9 @@ public class BGPMessageParserMockTest {
                final BGPMessageParserMock mockParser = new BGPMessageParserMock(updateMap);
 
                for (int i = 0; i < this.inputBytes.length; i++) {
-                       assertEquals(this.messages.get(i), mockParser.parse(this.inputBytes[i], null));
+                       assertEquals(this.messages.get(i), mockParser.parse(this.inputBytes[i]));
                }
-               assertThat(this.messages.get(3), not(mockParser.parse(this.inputBytes[8], null)));
-
-               mockParser.close();
+               assertThat(this.messages.get(3), not(mockParser.parse(this.inputBytes[8])));
        }
 
        /**
@@ -113,9 +109,7 @@ public class BGPMessageParserMockTest {
                }
 
                final BGPMessageParserMock mockParser = new BGPMessageParserMock(updateMap);
-               mockParser.parse(new byte[] { 7, 4, 6 }, new BGPMessageHeader());
-
-               mockParser.close();
+               mockParser.parse(new byte[] { 7, 4, 6 });
        }
 
        /**
@@ -185,14 +179,12 @@ public class BGPMessageParserMockTest {
                final BGPMessageParserMock mockParser = new BGPMessageParserMock(openMap);
 
                final Set<BGPTableType> result = Sets.newHashSet();
-               for (final BGPParameter p : ((BGPOpenMessage) mockParser.parse(input, null)).getOptParams()) {
+               for (final BGPParameter p : ((BGPOpenMessage) mockParser.parse(input)).getOptParams()) {
                        if (p instanceof MultiprotocolCapability) {
                                result.add(((MultiprotocolCapability) p).getTableType());
                        }
                }
 
                assertEquals(type, result);
-
-               mockParser.close();
        }
 }
index 097435b3002538945e2079417de7262947158728..8b7f244374b3c2b305099d222efd59e9a2bf0bb9 100644 (file)
                             org.opendaylight.protocol.bgp.util,
                             org.opendaylight.protocol.util,
                                                        org.slf4j,
+                                                       io.netty.channel, 
+                                                       io.netty.util.concurrent,
                                                </Import-Package>
                                                <Export-Package>
                                                        org.opendaylight.protocol.bgp.rib.impl
index 492e75808644137592f9ceaeef56ac810caacf00..a48a36219a2c199bb2d4d855c4fde50d947dd14d 100644 (file)
@@ -10,12 +10,11 @@ package org.opendaylight.protocol.bgp.rib.impl;
 import java.io.Closeable;
 import java.io.IOException;
 
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.BGPSession;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPConnection;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
-
 import org.opendaylight.protocol.framework.Dispatcher;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
 
 /**
  * Implementation of BGPDispatcher.
@@ -29,8 +28,8 @@ public final class BGPDispatcherImpl implements BGPDispatcher, Closeable {
        }
 
        @Override
-       public BGPSession createClient(final BGPConnection connection, final BGPMessageParser parser) throws IOException {
-               return (BGPSession) this.dispatcher.createClient(connection, new BGPSessionFactory(parser), BGPInputStream.FACTORY);
+       public BGPSession createClient(final BGPConnection connection, final ProtocolMessageFactory parser) throws IOException {
+               return (BGPSession) this.dispatcher.createClient(connection, new BGPSessionFactory(parser));
        }
 
        public Dispatcher getDispatcher() {
index a60224827ab72ef03e514e67fe6f03182bda4385..db32b0d614e4d7118636303d591052d15f9c0cbc 100644 (file)
@@ -11,14 +11,13 @@ import java.io.Closeable;
 import java.io.IOException;
 import java.net.InetSocketAddress;
 
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.BGPSession;
 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionProposal;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionProposalChecker;
-
 import org.opendaylight.protocol.concepts.ListenerRegistration;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
 
 /**
  * Implementation of {@link BGP}.
@@ -51,7 +50,7 @@ public class BGPImpl implements BGP, Closeable {
 
        private final BGPDispatcher dispatcher;
 
-       private final BGPMessageParser parser;
+       private final ProtocolMessageFactory parser;
 
        private final InetSocketAddress address;
 
@@ -59,7 +58,7 @@ public class BGPImpl implements BGP, Closeable {
 
        private final BGPSessionProposalChecker checker;
 
-       public BGPImpl(final BGPDispatcher dispatcher, final BGPMessageParser parser, final InetSocketAddress address,
+       public BGPImpl(final BGPDispatcher dispatcher, final ProtocolMessageFactory parser, final InetSocketAddress address,
                        final BGPSessionProposal proposal, final BGPSessionProposalChecker checker) throws IOException {
                this.dispatcher = dispatcher;
                this.parser = parser;
diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPInputStream.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPInputStream.java
deleted file mode 100644 (file)
index fd5f25a..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.rib.impl;
-
-import java.io.IOException;
-import java.io.PipedInputStream;
-
-import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
-import org.opendaylight.protocol.util.ByteArray;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.opendaylight.protocol.framework.DeserializerException;
-import org.opendaylight.protocol.framework.DocumentedException;
-import org.opendaylight.protocol.framework.ProtocolInputStream;
-import org.opendaylight.protocol.framework.ProtocolInputStreamFactory;
-import org.opendaylight.protocol.framework.ProtocolMessageFactory;
-import org.opendaylight.protocol.framework.ProtocolMessageHeader;
-import com.google.common.annotations.VisibleForTesting;
-
-/**
- * Input stream for BGP.
- */
-public class BGPInputStream implements ProtocolInputStream {
-
-       private final static Logger logger = LoggerFactory.getLogger(BGPInputStream.class);
-
-       /**
-        * BGP implementation for protocol input stream factory.
-        */
-       public static final ProtocolInputStreamFactory FACTORY = new ProtocolInputStreamFactory() {
-               @Override
-               public ProtocolInputStream getProtocolInputStream(final PipedInputStream pis, final ProtocolMessageFactory factory) {
-                       return new BGPInputStream(pis, factory);
-               }
-       };
-
-       private final ProtocolMessageFactory factory;
-
-       private final PipedInputStream inputStream;
-
-       @VisibleForTesting
-       protected BGPMessageHeader header;
-
-       private BGPInputStream(final PipedInputStream inputStream, final ProtocolMessageFactory factory) {
-               this.factory = factory;
-               this.inputStream = inputStream;
-               this.header = new BGPMessageHeader();
-       }
-
-       /**
-        * Check availability of a message in underlying input stream. A message is available when there are more or the
-        * same amount of bytes in the stream as the message length is specified in message header. If there are not enough
-        * bytes for the message or even to read a message header, return false.
-        * 
-        * @return true if there are enough bytes to read a message false if there are not enough bytes to read a message or
-        *         a message header.
-        * @throws IOException
-        */
-       @Override
-       public synchronized boolean isMessageAvailable() throws IOException {
-               if (!this.header.isParsed()) {
-                       // No header, try to parse it
-                       this.header = (BGPMessageHeader) parseHeaderIfAvailable();
-
-                       if (!this.header.isParsed()) {
-                               // No luck, we do not have a message
-                               return false;
-                       }
-               }
-               // message length contains the size of the header too
-               if (this.inputStream.available() < (this.header.getLength() - BGPMessageHeader.COMMON_HEADER_LENGTH)) {
-                       return false;
-               }
-               return true;
-       }
-
-       /**
-        * If there are enough bytes in the underlying stream, parse the message. Blocking, till there are enough bytes to
-        * read, therefore the call of method isMessageAvailable() is suggested first.
-        * 
-        * @return protocol specific message
-        * @throws DeserializerException
-        * @throws IOException
-        * @throws DocumentedException
-        */
-       @Override
-       public synchronized BGPMessage getMessage() throws DeserializerException, IOException, DocumentedException {
-               // isMessageAvailable wasn't called, or there were not enough bytes to form message header
-               // blocking till the header is available
-               while (!this.header.isParsed()) {
-                       this.header = (BGPMessageHeader) parseHeaderIfAvailable();
-               }
-               final byte[] bytes = new byte[this.header.getLength() - BGPMessageHeader.COMMON_HEADER_LENGTH]; // message
-                                                                                                                                                                                                               // length
-                                                                                                                                                                                                               // contains the
-                                                                                                                                                                                                               // size of the
-                                                                                                                                                                                                               // header too
-               // blocking till the whole message is available
-               if (this.inputStream.read(bytes) == -1) {
-                       throw new IOException("PipedInputStream was closed, before data could be read from it.");
-               }
-
-               final BGPMessage msg = (BGPMessage) this.factory.parse(bytes, this.header);
-               this.header.setParsed(); // if we have all the bytes to send the message for parsing, clear the header, to let
-                                                                       // know,
-
-               return msg;
-       }
-
-       /**
-        * Checks if there are enough bytes to parse a header and parses it. Non-blocking: if there are not enough bytes to
-        * parse a message header, returns false.
-        * 
-        * @return cleared header if no header is available
-        * @return header object when enough data is available
-        */
-       private ProtocolMessageHeader parseHeaderIfAvailable() throws IOException {
-               final byte[] messageHeader = new byte[BGPMessageHeader.COMMON_HEADER_LENGTH];
-               if (this.inputStream.available() < BGPMessageHeader.COMMON_HEADER_LENGTH || this.inputStream.read(messageHeader) == -1) {
-                       this.header.setParsed();
-                       return this.header;
-               }
-               logger.debug("Attempt to parse BGP message header from bytes: {}", ByteArray.bytesToHexString(messageHeader));
-               return this.header.fromBytes(messageHeader);
-       }
-}
index 56fb0336338f15cd58a4d728419c58e547ac99c1..e3f3fa9ccaa1eb067313456a5318a9231a759f9f 100644 (file)
@@ -7,12 +7,13 @@
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
+import io.netty.channel.ChannelHandlerContext;
+
 import java.util.Timer;
 
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPConnection;
-
 import org.opendaylight.protocol.framework.ProtocolConnection;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
 import org.opendaylight.protocol.framework.ProtocolSession;
 import org.opendaylight.protocol.framework.ProtocolSessionFactory;
 import org.opendaylight.protocol.framework.SessionParent;
@@ -22,15 +23,15 @@ import org.opendaylight.protocol.framework.SessionParent;
  */
 public final class BGPSessionFactory implements ProtocolSessionFactory {
 
-       private final BGPMessageParser parser;
+       private final ProtocolMessageFactory parser;
 
-       public BGPSessionFactory(final BGPMessageParser parser) {
+       public BGPSessionFactory(final ProtocolMessageFactory parser) {
                this.parser = parser;
        }
 
        @Override
        public ProtocolSession getProtocolSession(final SessionParent parent, final Timer timer, final ProtocolConnection connection,
-                       final int sessionId) {
-               return new BGPSessionImpl(parent, timer, (BGPConnection) connection, sessionId, this.parser);
+                       final int sessionId, final ChannelHandlerContext ctx) {
+               return new BGPSessionImpl(parent, timer, (BGPConnection) connection, sessionId, this.parser, ctx);
        }
 }
index e1ce972440498b6d641483711ff1ca48bd79b9d6..d45f3f0bb29f56eea386b71b41b2ab7fe85ab17a 100644 (file)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
+import io.netty.channel.ChannelHandlerContext;
+
 import java.io.IOException;
 import java.util.Date;
 import java.util.Set;
@@ -17,7 +19,6 @@ import org.opendaylight.protocol.bgp.concepts.BGPTableType;
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.BGPParameter;
 import org.opendaylight.protocol.bgp.parser.BGPSession;
 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
@@ -28,16 +29,16 @@ import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPConnection;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionProposalChecker;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.opendaylight.protocol.framework.DeserializerException;
 import org.opendaylight.protocol.framework.DocumentedException;
 import org.opendaylight.protocol.framework.ProtocolMessage;
 import org.opendaylight.protocol.framework.ProtocolMessageFactory;
-import org.opendaylight.protocol.framework.ProtocolOutputStream;
 import org.opendaylight.protocol.framework.ProtocolSession;
+import org.opendaylight.protocol.framework.ProtocolSessionOutboundHandler;
 import org.opendaylight.protocol.framework.SessionParent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.collect.Sets;
 
 class BGPSessionImpl implements BGPSession, ProtocolSession {
@@ -118,8 +119,6 @@ class BGPSessionImpl implements BGPSession, ProtocolSession {
         */
        private BGPSessionPreferences remoteOpen = null;
 
-       private final ProtocolOutputStream outputStream;
-
        /**
         * Timer object grouping FSM Timers
         */
@@ -127,26 +126,31 @@ class BGPSessionImpl implements BGPSession, ProtocolSession {
 
        private final SessionParent parent;
 
-       private final BGPMessageParser parser;
+       private final ProtocolMessageFactory parser;
 
        private final BGPSessionProposalChecker checker;
 
        private final BGPSynchronization sync;
 
+       private final ProtocolSessionOutboundHandler handler;
+
        private int kaCounter = 0;
 
+       private final ChannelHandlerContext ctx;
+
        BGPSessionImpl(final SessionParent parent, final Timer timer, final BGPConnection connection, final int sessionId,
-                       final BGPMessageParser parser) {
+                       final ProtocolMessageFactory parser, final ChannelHandlerContext ctx) {
                this.state = State.IDLE;
                this.listener = connection.getListener();
                this.sessionId = sessionId;
                this.localOpen = connection.getProposal();
-               this.outputStream = new ProtocolOutputStream();
                this.stateTimer = timer;
                this.parent = parent;
                this.parser = parser;
+               this.ctx = ctx;
                this.checker = connection.getProposalChecker();
                this.sync = new BGPSynchronization(this.listener);
+               this.handler = new ProtocolSessionOutboundHandler(this);
        }
 
        @Override
@@ -167,11 +171,6 @@ class BGPSessionImpl implements BGPSession, ProtocolSession {
                this.changeState(State.OPEN_SENT);
        }
 
-       @Override
-       public ProtocolOutputStream getStream() {
-               return this.outputStream;
-       }
-
        /**
         * Handles incoming message based on their type.
         * 
@@ -237,10 +236,13 @@ class BGPSessionImpl implements BGPSession, ProtocolSession {
        }
 
        void sendMessage(final BGPMessage msg) {
-               this.outputStream.putMessage(msg, this.parser);
-               this.lastMessageSentAt = System.nanoTime();
-               logger.debug("Sent message: " + msg);
-               this.parent.checkOutputBuffer(this);
+               try {
+                       this.handler.writeDown(this.ctx, msg);
+                       this.lastMessageSentAt = System.nanoTime();
+                       logger.debug("Sent message: " + msg);
+               } catch (final Exception e) {
+                       logger.warn("Message {} was not sent.", msg, e);
+               }
        }
 
        private void closeWithoutMessage() {
@@ -414,8 +416,6 @@ class BGPSessionImpl implements BGPSession, ProtocolSession {
                builder.append(this.localOpen);
                builder.append(", remoteOpen=");
                builder.append(this.remoteOpen);
-               builder.append(", outputStream=");
-               builder.append(this.outputStream);
                builder.append("]");
                return builder.toString();
        }
index 92b2768db48f98e077bc540ecad74c77b97ecc55..325fb892cc42ee619af8bc51872728cab4fa6b2d 100644 (file)
@@ -9,9 +9,8 @@ package org.opendaylight.protocol.bgp.rib.impl.spi;
 
 import java.io.IOException;
 
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.BGPSession;
-
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
 
 /**
  * Dispatcher class for creating BGP clients.
@@ -26,5 +25,5 @@ public interface BGPDispatcher {
         * @return client session
         * @throws IOException
         */
-       BGPSession createClient(BGPConnection connection, BGPMessageParser parser) throws IOException;
+       BGPSession createClient(BGPConnection connection, ProtocolMessageFactory parser) throws IOException;
 }
index 4a336f19d8ebf40861be72d5999a941c8d3d37c2..a465f672aab21ab1b6361ecb366695ba78bc8342 100644 (file)
 package org.opendaylight.protocol.bgp.rib.impl;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
 import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Map;
 
 import org.junit.Test;
 import org.opendaylight.protocol.bgp.concepts.BGPAddressFamily;
 import org.opendaylight.protocol.bgp.concepts.BGPSubsequentAddressFamily;
 import org.opendaylight.protocol.bgp.concepts.BGPTableType;
-import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
-import org.opendaylight.protocol.bgp.parser.BGPError;
-import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPParameter;
 import org.opendaylight.protocol.bgp.parser.BGPUpdateSynchronized;
-import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
-import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
-import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
-import org.opendaylight.protocol.bgp.parser.parameter.AS4BytesCapability;
-import org.opendaylight.protocol.bgp.parser.parameter.CapabilityParameter;
-import org.opendaylight.protocol.bgp.parser.parameter.GracefulCapability;
-import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
-import org.opendaylight.protocol.bgp.rib.impl.BGPUpdateSynchronizedImpl;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
-
-import org.opendaylight.protocol.framework.DocumentedException;
-import org.opendaylight.protocol.framework.SessionPreferences;
 import org.opendaylight.protocol.concepts.ASNumber;
-import com.google.common.collect.Maps;
+import org.opendaylight.protocol.framework.SessionPreferences;
 
 public class ApiTest {
 
-       @Test
-       public void testDocumentedException() {
-               final DocumentedException de = new BGPDocumentedException("Some message", BGPError.BAD_BGP_ID);
-               assertEquals("Some message", de.getMessage());
-               assertEquals(BGPError.BAD_BGP_ID, ((BGPDocumentedException) de).getError());
-               assertNull(((BGPDocumentedException) de).getData());
-       }
-
-       @Test
-       public void testBGPKeepAliveMessage() {
-               final BGPMessage msg = new BGPKeepAliveMessage();
-               assertTrue(msg instanceof BGPKeepAliveMessage);
-       }
-
-       @Test
-       public void testBGPNotificationMessage() {
-               final BGPMessage msg = new BGPNotificationMessage(BGPError.AS_PATH_MALFORMED);
-               assertTrue(msg instanceof BGPNotificationMessage);
-               assertEquals(BGPError.AS_PATH_MALFORMED, ((BGPNotificationMessage) msg).getError());
-               assertNull(((BGPNotificationMessage) msg).getData());
-       }
-
-       @Test
-       public void testBGPOpenMessage() {
-               final BGPMessage msg = new BGPOpenMessage(new ASNumber(58), (short) 5, null, null);
-               assertNull(((BGPOpenMessage) msg).getOptParams());
-       }
-
-       @Test
-       public void testBGPParameter() {
-
-               final BGPTableType t = new BGPTableType(BGPAddressFamily.LinkState, BGPSubsequentAddressFamily.Unicast);
-               final BGPTableType t1 = new BGPTableType(BGPAddressFamily.IPv4, BGPSubsequentAddressFamily.Unicast);
-
-               final BGPParameter tlv1 = new MultiprotocolCapability(t);
-
-               final BGPParameter tlv2 = new MultiprotocolCapability(t1);
-
-               final Map<BGPTableType, Boolean> tt = Maps.newHashMap();
-               tt.put(t, true);
-               tt.put(t1, false);
-
-               final BGPParameter tlv3 = new GracefulCapability(false, 0, tt);
-
-               final BGPParameter tlv4 = new AS4BytesCapability(new ASNumber(40));
-
-               assertFalse(((GracefulCapability) tlv3).isRestartFlag());
-
-               assertEquals(0, ((GracefulCapability) tlv3).getRestartTimerValue());
-
-               assertEquals(tlv1.getType(), tlv2.getType());
-
-               assertFalse(tlv1.equals(tlv2));
-
-               assertNotSame(tlv1.hashCode(), tlv3.hashCode());
-
-               assertNotSame(tlv2.toString(), tlv3.toString());
-
-               assertEquals(((GracefulCapability) tlv3).getTableTypes(), tt);
-
-               assertNotSame(((CapabilityParameter) tlv1).getCode(), ((CapabilityParameter) tlv3).getCode());
-
-               assertEquals(((MultiprotocolCapability) tlv1).getSafi(), ((MultiprotocolCapability) tlv2).getSafi());
-
-               assertNotSame(((MultiprotocolCapability) tlv1).getAfi(), ((MultiprotocolCapability) tlv2).getAfi());
-
-               assertEquals(40, ((AS4BytesCapability) tlv4).getASNumber().getAsn());
-
-               assertEquals(new AS4BytesCapability(new ASNumber(40)).toString(), tlv4.toString());
-       }
-
-       @Test
-       public void testToString() {
-               final BGPMessage o = new BGPOpenMessage(new ASNumber(58), (short) 5, null, null);
-               final BGPMessage n = new BGPNotificationMessage(BGPError.ATTR_FLAGS_MISSING);
-               assertNotSame(o.toString(), n.toString());
-       }
-
        @Test
        public void testBGPSessionPreferences() {
                final SessionPreferences sp = new BGPSessionPreferences(new ASNumber(58), (short) 5, null, null);
index 2d72c1e7c9e1100126888ff923296aad5d89a712..37b7504098a2bee522d2d4ea9fb971ed4e129023 100644 (file)
@@ -19,15 +19,13 @@ import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.BGPParameter;
-import org.opendaylight.protocol.bgp.rib.impl.BGPImpl;
 import org.opendaylight.protocol.bgp.rib.impl.BGPImpl.BGPListenerRegistration;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPConnection;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionProposal;
-
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
 
 public class BGPImplTest {
 
@@ -38,7 +36,7 @@ public class BGPImplTest {
        private BGPSessionProposal prop;
 
        @Mock
-       private BGPMessageParser parser;
+       private ProtocolMessageFactory parser;
 
        private BGPImpl bgp;
 
@@ -46,7 +44,7 @@ public class BGPImplTest {
        public void setUp() throws IOException {
                MockitoAnnotations.initMocks(this);
                doReturn("").when(this.parser).toString();
-               doReturn(null).when(this.disp).createClient(any(BGPConnection.class), any(BGPMessageParser.class));
+               doReturn(null).when(this.disp).createClient(any(BGPConnection.class), any(ProtocolMessageFactory.class));
        }
 
        @Test
index 71dd47172555fd9567ce1d7b2ba4adb8f7e2480e..a34242e25e767b15166c8fdf76f65db95965ea48 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.protocol.bgp.rib.impl;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -29,9 +28,8 @@ import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
 import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
 import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
-import org.opendaylight.protocol.bgp.rib.impl.BGPSessionImpl;
-
 import org.opendaylight.protocol.concepts.ASNumber;
+
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 
@@ -133,8 +131,6 @@ public class FSMTest {
        @Test
        public void complementaryTests() {
                assertEquals(4096, this.speaker.maximumMessageSize());
-
-               assertNotNull(this.speaker.getStream());
        }
 
        @After
diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/InputStreamTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/InputStreamTest.java
deleted file mode 100644 (file)
index cc95d0e..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.rib.impl;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import java.io.IOException;
-import java.io.PipedInputStream;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
-import org.opendaylight.protocol.bgp.parser.impl.BGPMessageFactory;
-import org.opendaylight.protocol.bgp.rib.impl.BGPInputStream;
-
-import org.opendaylight.protocol.framework.DeserializerException;
-import org.opendaylight.protocol.framework.DocumentedException;
-
-public class InputStreamTest {
-
-       @Mock
-       PipedInputStream pis;
-
-       @Mock
-       BGPMessageFactory mf;
-
-       @Mock
-       BGPMessageHeader h;
-
-       BGPInputStream is;
-
-       @Before
-       public void setUp() throws IOException {
-               MockitoAnnotations.initMocks(this);
-               this.is = (BGPInputStream) BGPInputStream.FACTORY.getProtocolInputStream(this.pis, this.mf);
-       }
-
-       @Test
-       public void testHeaderNotAvailable() throws IOException {
-               doReturn(BGPMessageHeader.COMMON_HEADER_LENGTH - 4).when(this.pis).available();
-               doReturn(-1).when(this.pis).read((byte[]) any());
-               assertFalse(this.is.isMessageAvailable());
-               assertFalse(this.is.header.isParsed());
-       }
-
-       @Test
-       public void testHeaderAvailable() throws IOException {
-               doReturn(BGPMessageHeader.COMMON_HEADER_LENGTH).when(this.pis).available();
-               doReturn(5).when(this.pis).read((byte[]) any());
-               assertTrue(this.is.isMessageAvailable());
-               assertTrue(this.is.header.isParsed());
-       }
-
-       @Test
-       public void testGetMessage() throws IOException, DeserializerException, DocumentedException {
-               doReturn(BGPMessageHeader.COMMON_HEADER_LENGTH).when(this.pis).available();
-               doReturn(5).when(this.pis).read((byte[]) any());
-               doReturn("").when(this.h).toString();
-               this.is.header = this.h;
-               doNothing().when(this.h).setParsed();
-               doReturn(true).when(this.h).isParsed();
-               doReturn(100).when(this.h).getLength();
-               doReturn(mock(BGPMessage.class)).when(this.mf).parse((byte[]) any(), any(BGPMessageHeader.class));
-               assertTrue(this.is.getMessage() instanceof BGPMessage);
-       }
-}
index e50da39b8d9beb2c3aa0647b4f6ef919b3ae9bea..e4cd93ca89819cc7b9e248623271b4b7d1c07b92 100644 (file)
@@ -19,11 +19,6 @@ public class MockDispatcher implements SessionParent {
 
        }
 
-       @Override
-       public void checkOutputBuffer(final ProtocolSession session) {
-
-       }
-
        @Override
        public void close() throws IOException {
        }
index 7b270970e28d99fa10488a85bbfdb2a608c3cab1..acfad07f3980716745daa4431b512b5a008286fd 100644 (file)
@@ -27,8 +27,6 @@ import org.opendaylight.protocol.bgp.concepts.BGPTableType;
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.BGPParameter;
 import org.opendaylight.protocol.bgp.parser.impl.BGPMessageFactory;
 import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
@@ -36,12 +34,13 @@ import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
 import org.opendaylight.protocol.bgp.parser.parameter.GracefulCapability;
 import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
-import org.opendaylight.protocol.util.ByteArray;
-
-import org.opendaylight.protocol.framework.DeserializerException;
-import org.opendaylight.protocol.framework.DocumentedException;
 import org.opendaylight.protocol.concepts.ASNumber;
 import org.opendaylight.protocol.concepts.IPv4Address;
+import org.opendaylight.protocol.framework.DeserializerException;
+import org.opendaylight.protocol.framework.DocumentedException;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
+import org.opendaylight.protocol.util.ByteArray;
+
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 
@@ -60,21 +59,19 @@ public class ParserTest {
                        (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 };
 
-       final BGPMessageHeader header = new BGPMessageHeader();
-
-       final BGPMessageParser factory = new BGPMessageFactory();
+       final ProtocolMessageFactory factory = new BGPMessageFactory();
 
        @Test
-       public void testHeaderErrors() {
-               final byte[] wrong = 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 };
+       public void testHeaderErrors() throws DeserializerException, DocumentedException {
+               byte[] wrong = 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 };
+               wrong = ByteArray.cutBytes(wrong, 16);
                try {
-                       this.header.fromBytes(wrong);
+                       this.factory.parse(wrong);
                        fail("Exception should have occcured.");
                } catch (final IllegalArgumentException e) {
                        assertEquals("Too few bytes in passed array. Passed: " + wrong.length + ". Expected: >= "
-                                       + BGPMessageHeader.COMMON_HEADER_LENGTH + ".", e.getMessage());
+                                       + BGPMessageFactory.COMMON_HEADER_LENGTH + ".", e.getMessage());
                        return;
                }
                fail();
@@ -85,13 +82,11 @@ public class ParserTest {
                byte[] bytes = 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) 0x08 };
-               final BGPMessageHeader h = this.header.fromBytes(bytes);
-               bytes = ByteArray.cutBytes(bytes, 19);
+               bytes = ByteArray.cutBytes(bytes, 16);
                try {
-                       this.factory.parse(bytes, h);
+                       this.factory.parse(bytes);
                        fail("Exception should have occured.");
                } catch (final DocumentedException e) {
-                       assertEquals("Unhandled message type " + h.getType(), e.getMessage());
                        assertEquals(BGPError.BAD_MSG_TYPE, ((BGPDocumentedException) e).getError());
                        return;
                }
@@ -104,9 +99,8 @@ public class ParserTest {
                byte[] bytes = this.factory.put(keepAlive);
                assertArrayEquals(keepAliveBMsg, bytes);
 
-               final BGPMessageHeader h = this.header.fromBytes(keepAliveBMsg);
-               bytes = ByteArray.cutBytes(bytes, 19);
-               final BGPMessage m = this.factory.parse(bytes, h);
+               bytes = ByteArray.cutBytes(bytes, 16);
+               final BGPMessage m = (BGPMessage) this.factory.parse(bytes);
 
                assertTrue(m instanceof BGPKeepAliveMessage);
        }
@@ -117,10 +111,9 @@ public class ParserTest {
                                (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00,
                                (byte) 0x14, (byte) 0x04, (byte) 0x05 };
 
-               final BGPMessageHeader h = this.header.fromBytes(bytes);
-               bytes = ByteArray.cutBytes(bytes, 19);
+               bytes = ByteArray.cutBytes(bytes, 16);
                try {
-                       this.factory.parse(bytes, h);
+                       this.factory.parse(bytes);
                        fail("Exception should have occured.");
                } catch (final DocumentedException e) {
                        assertThat(e.getMessage(), containsString("Message length field not within valid range."));
@@ -136,9 +129,8 @@ public class ParserTest {
                byte[] bytes = this.factory.put(open);
                assertArrayEquals(openBMsg, bytes);
 
-               final BGPMessageHeader h = this.header.fromBytes(openBMsg);
-               bytes = ByteArray.cutBytes(bytes, 19);
-               final BGPMessage m = this.factory.parse(bytes, h);
+               bytes = ByteArray.cutBytes(bytes, 16);
+               final BGPMessage m = (BGPMessage) this.factory.parse(bytes);
 
                assertTrue(m instanceof BGPOpenMessage);
                assertEquals(new ASNumber(100), ((BGPOpenMessage) m).getMyAS());
@@ -154,10 +146,9 @@ public class ParserTest {
                                (byte) 0x1d, (byte) 0x01, (byte) 0x04, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0x01, (byte) 0x14, (byte) 0x14,
                                (byte) 0x14, (byte) 0x14, (byte) 0x00 };
 
-               final BGPMessageHeader h = this.header.fromBytes(bMsg);
-               bMsg = ByteArray.cutBytes(bMsg, 19);
+               bMsg = ByteArray.cutBytes(bMsg, 16);
                try {
-                       this.factory.parse(bMsg, h);
+                       this.factory.parse(bMsg);
                        fail("Exception should have occured.");
                } catch (final DocumentedException e) {
                        assertEquals("Hold time value not acceptable.", e.getMessage());
@@ -174,10 +165,9 @@ public class ParserTest {
                                (byte) 0x1b, (byte) 0x01, (byte) 0x04, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0xb4, (byte) 0xff, (byte) 0xff,
                                (byte) 0xff };
 
-               final BGPMessageHeader h = this.header.fromBytes(bMsg);
-               bMsg = ByteArray.cutBytes(bMsg, 19);
+               bMsg = ByteArray.cutBytes(bMsg, 16);
                try {
-                       this.factory.parse(bMsg, h);
+                       this.factory.parse(bMsg);
                        fail("Exception should have occured.");
                } catch (final DocumentedException e) {
                        assertEquals("Open message too small.", e.getMessage());
@@ -192,10 +182,9 @@ public class ParserTest {
                                (byte) 0x1d, (byte) 0x01, (byte) 0x08, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0xb4, (byte) 0x14, (byte) 0x14,
                                (byte) 0x14, (byte) 0x14, (byte) 0x00 };
 
-               final BGPMessageHeader h = this.header.fromBytes(bMsg);
-               bMsg = ByteArray.cutBytes(bMsg, 19);
+               bMsg = ByteArray.cutBytes(bMsg, 16);
                try {
-                       this.factory.parse(bMsg, h);
+                       this.factory.parse(bMsg);
                        fail("Exception should have occured.");
                } catch (final DocumentedException e) {
                        assertEquals("BGP Protocol version 8 not supported.", e.getMessage());
@@ -211,9 +200,8 @@ public class ParserTest {
                byte[] bytes = this.factory.put(notMsg);
                assertArrayEquals(notificationBMsg, bytes);
 
-               BGPMessageHeader h = this.header.fromBytes(notificationBMsg);
-               bytes = ByteArray.cutBytes(bytes, 19);
-               BGPMessage m = this.factory.parse(bytes, h);
+               bytes = ByteArray.cutBytes(bytes, 16);
+               BGPMessage m = (BGPMessage) this.factory.parse(bytes);
 
                assertTrue(m instanceof BGPNotificationMessage);
                assertEquals(BGPError.OPT_PARAM_NOT_SUPPORTED, ((BGPNotificationMessage) m).getError());
@@ -222,9 +210,8 @@ public class ParserTest {
                notMsg = new BGPNotificationMessage(BGPError.CONNECTION_NOT_SYNC);
                bytes = this.factory.put(notMsg);
 
-               h = this.header.fromBytes(bytes);
-               bytes = ByteArray.cutBytes(bytes, 19);
-               m = this.factory.parse(bytes, h);
+               bytes = ByteArray.cutBytes(bytes, 16);
+               m = (BGPMessage) this.factory.parse(bytes);
 
                assertTrue(m instanceof BGPNotificationMessage);
                assertEquals(BGPError.CONNECTION_NOT_SYNC, ((BGPNotificationMessage) m).getError());
@@ -237,10 +224,9 @@ public class ParserTest {
                                (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00,
                                (byte) 0x14, (byte) 0x03, (byte) 0x02 };
 
-               final BGPMessageHeader h = this.header.fromBytes(bMsg);
-               bMsg = ByteArray.cutBytes(bMsg, 19);
+               bMsg = ByteArray.cutBytes(bMsg, 16);
                try {
-                       this.factory.parse(bMsg, h);
+                       this.factory.parse(bMsg);
                        fail("Exception should have occured.");
                } catch (final DocumentedException e) {
                        assertEquals("Notification message too small.", e.getMessage());
@@ -256,10 +242,9 @@ public class ParserTest {
                                (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00,
                                (byte) 0x15, (byte) 0x03, (byte) 0x02, (byte) 0xaa };
 
-               final BGPMessageHeader h = this.header.fromBytes(bMsg);
-               bMsg = ByteArray.cutBytes(bMsg, 19);
+               bMsg = ByteArray.cutBytes(bMsg, 16);
                try {
-                       this.factory.parse(bMsg, h);
+                       this.factory.parse(bMsg);
                        fail("Exception should have occured.");
                } catch (final IllegalArgumentException e) {
                        assertEquals("BGP Error code 2 and subcode 170 not recognized.", e.getMessage());
index b322d5c281e4ea45c4ae5084217b9bb58c0d70b4..c3dc615579abd7b2f6a4283189f320f31a3d893c 100644 (file)
@@ -11,11 +11,7 @@ import java.util.Timer;
 
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
-import org.opendaylight.protocol.bgp.rib.impl.BGPConnectionImpl;
-import org.opendaylight.protocol.bgp.rib.impl.BGPSessionImpl;
-import org.opendaylight.protocol.bgp.rib.impl.BGPSessionProposalCheckerImpl;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
-
 import org.opendaylight.protocol.concepts.ASNumber;
 
 /**
@@ -26,7 +22,7 @@ public class SpeakerSessionMock extends BGPSessionImpl {
        private final BGPSessionListener client;
 
        SpeakerSessionMock(final BGPSessionListener listener, final BGPSessionListener client) {
-               super(new MockDispatcher(), new Timer(), new BGPConnectionImpl(null, listener, new BGPSessionPreferences(new ASNumber(30), (short) 15, null, null), new BGPSessionProposalCheckerImpl()), 3, null);
+               super(new MockDispatcher(), new Timer(), new BGPConnectionImpl(null, listener, new BGPSessionPreferences(new ASNumber(30), (short) 15, null, null), new BGPSessionProposalCheckerImpl()), 3, null, null);
                this.client = client;
        }
 
index 7b2aaeaf5ba0cb918ea6183de47c679414c8b694..886b4cbdc440dd8dd8c1c9dc4fc7266cf1a293dd 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.protocol.bgp.rib.mock;
 
 import java.io.Closeable;
-import java.io.IOException;
 import java.util.Arrays;
 import java.util.Iterator;
 import java.util.List;
@@ -18,17 +17,16 @@ import javax.annotation.concurrent.ThreadSafe;
 
 import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
-import org.opendaylight.protocol.bgp.parser.BGPMessageHeader;
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
 import org.opendaylight.protocol.bgp.parser.impl.BGPMessageFactory;
 import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
 import org.opendaylight.protocol.bgp.rib.impl.BGP;
-import org.opendaylight.protocol.util.ByteArray;
-
 import org.opendaylight.protocol.concepts.ListenerRegistration;
 import org.opendaylight.protocol.framework.DeserializerException;
 import org.opendaylight.protocol.framework.DocumentedException;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
+import org.opendaylight.protocol.util.ByteArray;
+
 import com.google.common.collect.Lists;
 import com.google.common.eventbus.EventBus;
 
@@ -56,19 +54,14 @@ public final class BGPMock implements BGP, Closeable {
 
        private List<BGPMessage> parsePrevious(final List<byte[]> msgs) {
                final List<BGPMessage> messages = Lists.newArrayList();
-               final BGPMessageParser parser = new BGPMessageFactory();
+               final ProtocolMessageFactory parser = new BGPMessageFactory();
                try {
                        for (final byte[] b : msgs) {
-                               final BGPMessageHeader header = new BGPMessageHeader();
-                               header.fromBytes(ByteArray.subByte(b, 0, BGPMessageHeader.COMMON_HEADER_LENGTH));
 
-                               final byte[] body = ByteArray.cutBytes(b, BGPMessageHeader.COMMON_HEADER_LENGTH);
+                               final byte[] body = ByteArray.cutBytes(b, 1);
 
-                               messages.add(parser.parse(body, header));
+                               messages.add((BGPMessage) parser.parse(body));
                        }
-                       parser.close();
-               } catch (final IOException e) {
-                       e.printStackTrace();
                } catch (final DeserializerException e) {
                        e.printStackTrace();
                } catch (final DocumentedException e) {
index fd7b8ece4125d3faa7a4f13981a0d8db1d08b269..96135204f54a92a411f6f1b59ca825f56fd9d855 100644 (file)
@@ -10,9 +10,7 @@ package org.opendaylight.protocol.bgp.testtool;
 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.util.concurrent.Executors;
 
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
 import org.opendaylight.protocol.bgp.parser.impl.BGPMessageFactory;
 import org.opendaylight.protocol.bgp.rib.impl.BGPConnectionImpl;
@@ -21,12 +19,12 @@ import org.opendaylight.protocol.bgp.rib.impl.BGPSessionProposalCheckerImpl;
 import org.opendaylight.protocol.bgp.rib.impl.BGPSessionProposalImpl;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionProposalChecker;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.opendaylight.protocol.framework.DispatcherImpl;
 import org.opendaylight.protocol.concepts.ASNumber;
 import org.opendaylight.protocol.concepts.IPv4Address;
+import org.opendaylight.protocol.framework.DispatcherImpl;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Starter class for testing.
@@ -53,7 +51,7 @@ public class Main {
        BGPDispatcherImpl dispatcher;
 
        public Main() throws IOException {
-               this.dispatcher = new BGPDispatcherImpl(new DispatcherImpl(Executors.defaultThreadFactory()));
+               this.dispatcher = new BGPDispatcherImpl(new DispatcherImpl(new BGPMessageFactory()));
        }
 
        public static void main(final String[] args) throws NumberFormatException, IOException {
@@ -96,7 +94,7 @@ public class Main {
 
                final BGPSessionProposalChecker checker = new BGPSessionProposalCheckerImpl();
 
-               final BGPMessageParser parser = new BGPMessageFactory();
+               final ProtocolMessageFactory parser = new BGPMessageFactory();
 
                logger.debug(address + " " + sessionListener + " " + proposal + " " + checker);
 
index 47da82bb0a5d0c3cbf08d672611e1c3db048af1a..20e2ed71a158e596b0102950681cf1f95616277c 100644 (file)
@@ -14,11 +14,10 @@ import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
 import org.opendaylight.protocol.bgp.parser.BGPSession;
 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
+import org.opendaylight.protocol.framework.DispatcherImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.opendaylight.protocol.framework.DispatcherImpl;
-
 /**
  * Testing BGP Listener.
  */
@@ -45,12 +44,12 @@ public class TestingListener extends BGPSessionListener {
        public void onSessionDown(final BGPSession session, final Exception e) {
                logger.info("Client Listener: Connection lost.");
                session.close();
-               this.d.stop();
+               // this.d.stop();
        }
 
        @Override
        public void onSessionTerminated(final BGPError cause) {
                logger.info("Client Listener: Connection lost: {}.", cause);
-               this.d.stop();
+               // this.d.stop();
        }
 }
index b6c11a19896dfb14cae82c1d5ef1902e387ae64f..48d97e20131070ff588982e17d2a15ae7433536a 100644 (file)
@@ -9,36 +9,33 @@ package org.opendaylight.protocol.bgp.testtool;
 
 import java.io.IOException;
 import java.net.InetSocketAddress;
-import java.util.concurrent.Executors;
 
-import org.opendaylight.protocol.bgp.parser.BGPMessageParser;
 import org.opendaylight.protocol.bgp.parser.impl.BGPMessageFactory;
 import org.opendaylight.protocol.bgp.rib.impl.BGPConnectionImpl;
-import org.opendaylight.protocol.bgp.rib.impl.BGPInputStream;
 import org.opendaylight.protocol.bgp.rib.impl.BGPSessionFactory;
 import org.opendaylight.protocol.bgp.rib.impl.BGPSessionProposalCheckerImpl;
 import org.opendaylight.protocol.bgp.rib.impl.BGPSessionProposalImpl;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPConnection;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPConnectionFactory;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
-
-import org.opendaylight.protocol.framework.DispatcherImpl;
 import org.opendaylight.protocol.concepts.ASNumber;
 import org.opendaylight.protocol.concepts.IPv4;
+import org.opendaylight.protocol.framework.DispatcherImpl;
+import org.opendaylight.protocol.framework.ProtocolMessageFactory;
 
 public class BGPSpeakerMock {
 
        DispatcherImpl dispatcher;
 
        BGPSpeakerMock() throws IOException {
-               this.dispatcher = new DispatcherImpl(Executors.defaultThreadFactory());
+               this.dispatcher = new DispatcherImpl(new BGPMessageFactory());
        }
 
        public static void main(final String[] args) throws IOException {
 
                final BGPSpeakerMock m = new BGPSpeakerMock();
 
-               final BGPMessageParser parser = new BGPMessageFactory();
+               final ProtocolMessageFactory parser = new BGPMessageFactory();
 
                m.dispatcher.createServer(new InetSocketAddress("127.0.0.2", 12345), new BGPConnectionFactory() {
                        @Override
@@ -52,6 +49,6 @@ public class BGPSpeakerMock {
                                }
                                return new BGPConnectionImpl(address, new SpeakerSessionListener(m.dispatcher), prefs, new BGPSessionProposalCheckerImpl());
                        }
-               }, new BGPSessionFactory(parser), BGPInputStream.FACTORY);
+               }, new BGPSessionFactory(parser));
        }
 }
index 391b299725e81e1bc86a3aeb565d68fefc472cc7..42048f173a9ea81040fbd55af374fb8a5c5658f4 100644 (file)
@@ -14,11 +14,10 @@ import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.parser.BGPMessage;
 import org.opendaylight.protocol.bgp.parser.BGPSession;
 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
+import org.opendaylight.protocol.framework.DispatcherImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.opendaylight.protocol.framework.DispatcherImpl;
-
 public class SpeakerSessionListener extends BGPSessionListener {
        private static final Logger logger = LoggerFactory.getLogger(SpeakerSessionListener.class);
 
@@ -42,12 +41,12 @@ public class SpeakerSessionListener extends BGPSessionListener {
        public void onSessionDown(final BGPSession session, final Exception e) {
                logger.info("Server: Session down.");
                session.close();
-               this.d.stop();
+               // this.d.stop();
        }
 
        @Override
        public void onMessage(final BGPMessage message) {
                logger.info("Server: Message received: {}", message);
-               this.d.stop();
+               // this.d.stop();
        }
 }
index 8cd5e788d1e4203308295db7325e1871cd375800..8c69ef4fe5bfe9cf48e3461019e292bb689dfeaf 100644 (file)
@@ -50,6 +50,9 @@
                             com.google.common.net,
                             com.google.common.primitives,
                             com.google.guava;
+                                                       javax.management,
+                                                       org.slf4j.*,
+                                                       io.netty.channel,
                                                </Import-Package>
                                                <Export-Package>
                             org.opendaylight.protocol.concepts,
index e0ec4ff68db13d0014eaefb68c36d87fad591031..d49792f0f5a30245973cdcd72707d73a2736ec04 100644 (file)
                        <groupId>org.opendaylight.bgpcep</groupId>
                        <artifactId>util</artifactId>
             <version>${project.version}</version>
+        </dependency>
+        <dependency>
+                       <groupId>io.netty</groupId>
+                       <artifactId>netty-all</artifactId>
+                       <version>4.0.0.CR9</version>
                </dependency>
                <dependency>
                        <groupId>com.google.guava</groupId>
@@ -61,6 +66,7 @@
                             org.opendaylight.protocol.util,
                                                        javax.annotation,
                                                        javax.management,
+                                                       io.netty.*,
                                                </Import-Package>
                                                <Export-Package>
                                                        org.opendaylight.protocol.framework,
index 45ac09642c664626abdb9933f18dca348cd7a368..4dbd80daedd5f4d7307d85adacc88a5f6c719360 100644 (file)
@@ -7,65 +7,36 @@
  */
 package org.opendaylight.protocol.framework;
 
+import io.netty.util.concurrent.Future;
+
 import java.io.IOException;
 import java.net.InetSocketAddress;
 
-import javax.net.ssl.SSLContext;
-
 /**
- * Dispatcher class for creating protocol servers and clients. The idea is to first create servers and clients and the run the start method
- * that will handle sockets in different thread.
+ * Dispatcher class for creating protocol servers and clients.
  */
 public interface Dispatcher {
        /**
         * Creates server. Each server needs factories to pass their instances to client sessions.
-        * @param address to be bound with the server
-        * @param connectionFactory factory for connection specific attributes
-        * @param sfactory to create specific session
-        * @param isFactory protocol specific input stream factory
-        *
-        * @return instance of ProtocolServer
-        * @throws IOException if some IO error occurred
-        */
-       public ProtocolServer createServer(final InetSocketAddress address, final ProtocolConnectionFactory connectionFactory,
-                       final ProtocolSessionFactory sfactory, final ProtocolInputStreamFactory isFactory) throws IOException;
-
-       /**
-        * Creates secure server. Each server needs factories to pass their instances to client sessions.
-        * @param address to be bound with the server
+        * 
         * @param connectionFactory factory for connection specific attributes
         * @param sfactory to create specific session
-        * @param isFactory protocol-specific input stream factory
-        * @param context SSLContext to use in secure communications
-        *
+        * @param handlerFactory protocol specific channel handlers factory
+        * 
         * @return instance of ProtocolServer
-        * @throws IOException if some IO error occurred
         */
        public ProtocolServer createServer(final InetSocketAddress address, final ProtocolConnectionFactory connectionFactory,
-                       final ProtocolSessionFactory sfactory, final ProtocolInputStreamFactory isFactory, final SSLContext context) throws IOException;
+                       final ProtocolSessionFactory sfactory) throws IOException;
 
        /**
         * Creates a client.
+        * 
         * @param connection connection specific attributes
-        * @param sfactory protocol message factory to be passed to session
-        * @param isFactory protocol-specific input stream factory
-        *
-        * @return session associated with this client
-        * @throws IOException if some IO error occurred
-        */
-       public ProtocolSession createClient(final ProtocolConnection connection, final ProtocolSessionFactory sfactory,
-                       final ProtocolInputStreamFactory isFactory) throws IOException;
-
-       /**
-        * Creates secure client.
-        * @param connection connection specific attributes
-        * @param sfactory protocol message factory to be passed to session
-        * @param isFactory protocol-specific input stream factory
-        * @param context SSLContext to use in secure communications
-        *
+        * @param sfactory protocol session factory to create a specific session
+        * @param handlerFactory protocol-specific channel handlers factory
+        * 
         * @return session associated with this client
-        * @throws IOException if some IO error occurred
         */
-       public ProtocolSession createClient(final ProtocolConnection connection, final ProtocolSessionFactory sfactory,
-                       final ProtocolInputStreamFactory isFactory, final SSLContext context) throws IOException;
+       public Future<ProtocolSession> createClient(final ProtocolConnection connection, final ProtocolSessionFactory sfactory)
+                       throws IOException;
 }
index ed5168d047f2dfca23679857f9cf0e9dd620a2a9..e05c9e378376340f9d950be3e7488e498397fef5 100644 (file)
  */
 package org.opendaylight.protocol.framework;
 
+import io.netty.bootstrap.Bootstrap;
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.channel.socket.nio.NioSocketChannel;
+import io.netty.util.concurrent.DefaultPromise;
+import io.netty.util.concurrent.Future;
+
 import java.io.IOException;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
 import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.spi.SelectorProvider;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Queue;
-import java.util.Set;
 import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-
-import javax.net.ssl.SSLContext;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.BiMap;
-import com.google.common.collect.HashBiMap;
-
 /**
  * Dispatcher class for creating servers and clients. The idea is to first create servers and clients and the run the
  * start method that will handle sockets in different thread.
  */
 public final class DispatcherImpl implements Dispatcher, SessionParent {
 
-       private static final Logger logger = LoggerFactory.getLogger(Dispatcher.class);
-
-       public static final int DEFAULT_MAX_RECONNECT_COUNT = 30;
-
-       public static final int DEFAULT_RECONNECT_MILLIS = 30000;
-       public static final int DEFAULT_SERVICE_MILLIS = 1000;
-
-       private static final int BUFFER_SIZE = 16384;
-
-       private static final boolean SSL_ENABLED = true;
-
-       private int serviceMillis = DEFAULT_SERVICE_MILLIS;
-       private int reconnectMillis = 5000;
-
-       private int maxConnectCount = 0;
-
-       /**
-        * List of servers created by this dispatcher. Servers are identified as a pair Server and the InetSocketAddress to
-        * which the server is bound.
-        */
-       private final Map<InetSocketAddress, ProtocolServer> servers = new HashMap<InetSocketAddress, ProtocolServer>();
-
-       /**
-        * Mapping of client Sessions to keys (Either clients created by the dispatcher directly or clients connected to one
-        * of the dispatchers server).
-        */
-       private final Map<ProtocolSession, SelectionKey> sessionKeys = new HashMap<ProtocolSession, SelectionKey>();
-
-       /**
-        * List of clients created by this dispatcher. Each client has its own Session. They are identified as a pair of
-        * Session and the InetSocketAddress to which they are connected.
-        */
-       private final BiMap<InetSocketAddress, ProtocolSession> clients;
-
-       /**
-        * Timer object grouping FSM Timers
-        */
-       private final Timer stateTimer;
-
-       /**
-        * Variable indicating that there was a request for stopping this dispatcher.
-        */
-       private volatile boolean requestStop = false;
-
-       private final Thread innerThread;
-
-       private final ExecutorService executorService;
-
-       private final InnerRun innerRun;
-
-       /**
-        * Configuration dependency used for testing of reusability.
-        */
-       private final ThreadFactory threadFactory;
-
-       private final class InnerRun implements Runnable {
-
-               /**
-                * Common selector for client/server parts.
-                */
-               public final Selector selector;
-
-               private final DispatcherImpl parent;
+       final class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
 
-               protected InnerRun(final DispatcherImpl parent) throws IOException {
-                       final Selector s = SelectorProvider.provider().openSelector();
+               private final ProtocolServer server;
 
-                       if (SSL_ENABLED)
-                               this.selector = new SSLSelector(s);
-                       else
-                               this.selector = s;
-
-                       this.parent = parent;
+               public ServerChannelInitializer(final ProtocolServer server) {
+                       this.server = server;
                }
 
                @Override
-               public void run() {
-                       // this method finishes only when stop() method was called
-                       while (!this.parent.requestStop) {
-                               try {
-                                       this.selector.select();
-                               } catch (final IOException e) {
-                                       logger.warn("Selection operation failed", e);
-                                       break;
-                               }
-
-                               /*
-                                * This block runs under lock. The idea is that
-                                * selection key notifiers will first acquire the
-                                * lock, then wake up the selector, then do their
-                                * modifications.
-                                *
-                                * This means that there are two possibilities:
-                                *
-                                * 1) we arrive here as a result of a selector wake
-                                *    up, at which point the modifier already holds
-                                *    the lock, and we'll wait for it.
-                                *
-                                * 2) we arrive here as a result of an event, in which
-                                *    case we will prevent modifiers from starting
-                                *    by holding the lock.
-                                */
-                               // logger.debug("Acquiring lock");
-                               synchronized (this) {
-                                       final Set<SelectionKey> keys = this.selector.selectedKeys();
-                                       if (keys.isEmpty())
-                                               continue;
-
-                                       /*
-                                        * Calculate maximum nanoseconds we can spend on read
-                                        * or write. Each key can do a pair of operations in one
-                                        * iteration.
-                                        */
-                                       final long serviceTime = serviceMillis * 500000 / keys.size();
-
-                                       final Iterator<SelectionKey> selectedKeys = keys.iterator();
-                                       while (selectedKeys.hasNext()) {
-                                               final SelectionKey key = selectedKeys.next();
-                                               selectedKeys.remove();
-
-                                               if (!key.isValid()) {
-                                                       continue;
-                                               }
-
-                                               try {
-                                                       if (key.isAcceptable()) {
-                                                               this.parent.accept(key);
-                                                       }
-                                                       if (key.isConnectable()) {
-                                                               if (!this.parent.finishConnection(key)) {
-                                                                       continue;
-                                                               }
-                                                       }
-
-                                                       /*
-                                                        * Split read/write fairness. If this key is only
-                                                        * readable or only writable, double the time
-                                                        */
-                                                       final long keyTime = key.isReadable() == key.isWritable() ? serviceTime : 2 * serviceTime;
-
-                                                       /*
-                                                        * If this key is readable, read it. That operation may
-                                                        * detect end-of-stream, which it will report internally,
-                                                        * and inform us by returning true.
-                                                        *
-                                                        * If that is the case, we do not want to proceed with the
-                                                        * write case, because the key may no longer be valid.
-                                                        */
-                                                       if (key.isReadable() && this.parent.read(key, System.nanoTime() + keyTime)) {
-                                                               continue;
-                                                       }
-
-                                                       /*
-                                                        * If this key is writable, write it. This may completely
-                                                        * drain the output queue, in which case write returns true.
-                                                        *
-                                                        * If that is the case, we need to suspend selecting for
-                                                        * writability -- it will be re-enabled once the queue goes
-                                                        * non-empty.
-                                                        */
-                                                       if (key.isWritable() && this.parent.write(key, System.nanoTime() + keyTime) && key.isValid()) {
-                                                               key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
-                                                       }
-
-                                               } catch (final IOException e) {
-                                                       logger.debug("Channel {} incurred unexpected error, closing it", key.channel(), e);
-                                                       key.cancel();
-                                                       try {
-                                                               key.channel().close(); // close the channel that caused problems
-                                                       } catch (final IOException e1) {
-                                                               logger.error("Channel: {} could not be closed, because {}", key.channel(), e1.getMessage(), e1);
-                                                       }
-                                               }
-                                       }
-                               }
-                       }
-
-                       logger.trace("Ended run of dispatcher.");
-                       try {
-                               this.selector.close();
-                       } catch (final IOException e) {
-                               throw new RuntimeException("Failed to close selector", e);
-                       }
-               }
-       }
-
-       /**
-        * Creates an instance of Dispatcher, gets the default selector and opens it.
-        *
-        * @param tfactory default Thread Factory
-        * @throws IOException if some error occurred during opening the selector
-        */
-       public DispatcherImpl(final ThreadFactory tfactory) throws IOException {
-               this.threadFactory = tfactory;
-               this.executorService = Executors.newSingleThreadExecutor(tfactory);
-               this.stateTimer = new Timer();
-               this.clients = HashBiMap.create();
-               this.innerRun = new InnerRun(this);
-               this.innerThread = tfactory.newThread(this.innerRun);
-               this.innerThread.start();
-       }
-
-       protected synchronized ProtocolServer startServer(final ServerSocketChannel serverChannel, final InetSocketAddress address,
-                       final ProtocolConnectionFactory connectionFactory, final ProtocolSessionFactory sfactory,
-                       final ProtocolInputStreamFactory isFactory) throws IOException {
-
-               // Notify the thread to update its selection keys
-               this.innerRun.selector.wakeup();
-
-               // logger.debug("Selector notified.");
-               serverChannel.configureBlocking(false);
-               serverChannel.bind(address);
-
-               final SelectionKey key = serverChannel.register(this.innerRun.selector, SelectionKey.OP_ACCEPT);
-               final ProtocolServer server = new ProtocolServer(this, address, serverChannel, connectionFactory, sfactory, isFactory);
-               key.attach(server);
-               this.servers.put(address, server);
-
-               logger.info("Server created.");
-               return server;
-       }
-
-       @Override
-       public ProtocolServer createServer(final InetSocketAddress address, final ProtocolConnectionFactory connectionFactory,
-                       final ProtocolSessionFactory sfactory, final ProtocolInputStreamFactory isFactory) throws IOException {
-               synchronized (this.innerRun) {
-                       if (this.servers.get(address) != null) {
-                               logger.warn("Server with this address: {} was already created.", address);
-                               throw new IllegalStateException("Server with this address: " + address + " was already created.");
-                       }
-
-                       return this.startServer(ServerSocketChannel.open(), address, connectionFactory, sfactory, isFactory);
-               }
-       }
-
-       @Override
-       public ProtocolServer createServer(final InetSocketAddress address, final ProtocolConnectionFactory connectionFactory,
-                       final ProtocolSessionFactory sfactory, final ProtocolInputStreamFactory isFactory, final SSLContext context) throws IOException {
-
-               if (!SSL_ENABLED)
-                       throw new UnsupportedOperationException("SSL has not been enabled");
-
-               synchronized (this.innerRun) {
-                       if (this.servers.get(address) != null) {
-                               logger.warn("Server with this address: {} was already created.", address);
-                               throw new IllegalStateException("Server with this address: " + address + " was already created.");
-                       }
-
-                       return this.startServer(SSLServerSocketChannel.open(this.innerRun.selector, context, this.executorService), address,
-                                       connectionFactory, sfactory, isFactory);
-               }
-       }
-
-       private void connectChannel(final SelectionKey key) {
-               final SessionStreams state = (SessionStreams) key.attachment();
-               state.timer = null;
-
-               state.connectCount++;
-               logger.debug("Connecting to {} attempt {}", state.connection.getPeerAddress(), state.connectCount);
-
-               final SocketChannel channel = (SocketChannel) key.channel();
-               try {
-                       channel.connect(state.connection.getPeerAddress());
-               } catch (final IOException e) {
-                       this.connectFailed(key, e);
-                       return;
-               }
-
-               if (channel.isConnected()) {
-                       logger.trace("Connected, update interestops");
-                       key.interestOps(SelectionKey.OP_READ);
-                       state.getSession().startSession();
-               } else
-                       key.interestOps(SelectionKey.OP_CONNECT);
-       }
-
-       private void connectFailed(final SelectionKey key, final IOException e) {
-               final SessionStreams state = (SessionStreams) key.attachment();
-
-               key.interestOps(0);
-
-               if (this.maxConnectCount >= 0 && state.connectCount >= this.maxConnectCount) {
-                       logger.debug("Connection to {} failed", state.connection.getPeerAddress().getAddress(), e);
-                       this.clients.inverse().remove(state.getSession());
-                       state.getSession().onConnectionFailed(e);
-                       return;
+               protected void initChannel(final SocketChannel ch) throws Exception {
+                       final ProtocolSession session = this.server.createSession(DispatcherImpl.this.stateTimer, ch);
+                       ch.pipeline().addLast(DispatcherImpl.this.handlerFactory.getHandlers(session));
                }
 
-               logger.trace("Connect to {} failed, will retry in {} milliseconds", state.connection.getPeerAddress().getAddress(),
-                               this.reconnectMillis, e);
-               state.timer = new TimerTask() {
-                       @Override
-                       public void run() {
-                               DispatcherImpl.this.connectChannel(key);
-                       }
-               };
-               this.stateTimer.schedule(state.timer, this.reconnectMillis);
        }
 
-       private ProtocolSession startClient(final SocketChannel channel, final ProtocolConnection connection,
-                       final ProtocolSessionFactory sfactory, final ProtocolInputStreamFactory isFactory) throws IOException {
+       final class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
 
-               // Notify the thread to update its selection keys
-               this.innerRun.selector.wakeup();
+               private final ProtocolSessionFactory sfactory;
 
-               channel.configureBlocking(false);
+               private final ProtocolConnection connection;
 
-               final ProtocolSession session;
-               final SelectionKey key;
-               synchronized (this) {
-                       session = sfactory.getProtocolSession(this, this.stateTimer, connection, 0);
+               private ProtocolSession session;
 
-                       final PipedOutputStream pos = new PipedOutputStream();
-                       final PipedInputStream pis = new PipedInputStream(pos, session.maximumMessageSize());
-
-                       key = channel.register(this.innerRun.selector, SelectionKey.OP_CONNECT);
-                       key.attach(new SessionStreams(pos, pis, isFactory.getProtocolInputStream(pis, session.getMessageFactory()), session, connection));
-
-                       this.sessionKeys.put(session, key);
-                       this.clients.put(connection.getPeerAddress(), session);
-                       logger.info("Client created.");
-               }
-
-               this.connectChannel(key);
-               return session;
-       }
-
-       @Override
-       public ProtocolSession createClient(final ProtocolConnection connection, final ProtocolSessionFactory sfactory,
-                       final ProtocolInputStreamFactory isFactory) throws IOException {
-               synchronized (this.innerRun) {
-                       if (this.clients.containsKey(connection.getPeerAddress())) {
-                               logger.warn("Attempt to create duplicate client session to the same address: {}", connection.getPeerAddress());
-                               throw new IllegalStateException("Attempt to create duplicate client session to the same address: "
-                                               + connection.getPeerAddress());
-                       }
-
-                       return this.startClient(SocketChannel.open(), connection, sfactory, isFactory);
+               public ClientChannelInitializer(final ProtocolConnection connection, final ProtocolSessionFactory sfactory) {
+                       this.connection = connection;
+                       this.sfactory = sfactory;
                }
-       }
 
-       @Override
-       public ProtocolSession createClient(final ProtocolConnection connection, final ProtocolSessionFactory sfactory,
-                       final ProtocolInputStreamFactory isFactory, final SSLContext context) throws IOException {
-
-               if (!SSL_ENABLED)
-                       throw new UnsupportedOperationException("SSL has not been enabled");
-
-               synchronized (this.innerRun) {
-                       if (this.clients.containsKey(connection.getPeerAddress())) {
-                               logger.warn("Attempt to create duplicate client session to the same address: {}", connection.getPeerAddress());
-                               throw new IllegalStateException("Attempt to create duplicate client session to the same address: "
-                                               + connection.getPeerAddress());
-                       }
-
-                       final SocketChannel sock = SSLSocketChannel.open(SocketChannel.open(), context, this.executorService, null);
-                       return this.startClient(sock, connection, sfactory, isFactory);
+               @Override
+               protected void initChannel(final SocketChannel ch) throws Exception {
+                       this.session = this.sfactory.getProtocolSession(DispatcherImpl.this, DispatcherImpl.this.stateTimer, this.connection, 0,
+                                       ch.pipeline().context(ProtocolSessionOutboundHandler.class));
+                       ch.pipeline().addLast(DispatcherImpl.this.handlerFactory.getHandlers(this.session));
                }
-       }
 
-       /**
-        * Requests to stop dispatchers run() method. This method wakes up the selector, even if there are no selectedKeys
-        * to stop blocking the thread.
-        */
-       public void stop() {
-               logger.debug("Requested stop of the Dispatcher.");
-               this.requestStop = true;
-               this.innerRun.selector.wakeup();
-               try {
-                       this.innerThread.join();
-               } catch (final InterruptedException e) {
-                       logger.error("Stopping interrupted.", e);
+               public ProtocolSession getSession() {
+                       return this.session;
                }
 
-               this.executorService.shutdown();
-       }
-
-       /**
-        * Removes given server from list of servers created by this dispatcher.
-        *
-        * @param server to be removed
-        */
-       void removeServer(final ProtocolServer server) {
-               this.servers.remove(server.getAddress());
-               logger.trace("Server removed.");
        }
 
-       /**
-        * Reads from socket and sends data to session through Piped Streams.
-        *
-        * @param key selection key that was marked as ready to read from
-        * @return true if the read has encountered end of channel (so no data will ever come) false if the method did read
-        *         all of its input
-        * @throws IOException if there was some error with IO streams
-        */
-       private boolean read(final SelectionKey key, final long deadline) throws IOException {
-               logger.trace("Started reading.");
-               final SocketChannel chan = (SocketChannel) key.channel();
-               final SessionStreams streams = (SessionStreams) key.attachment();
-               final ProtocolInputStream pcepis = streams.getProtocolInputStream();
-               final PipedOutputStream pos = streams.getPipedOutputStream();
-               final PipedInputStream pis = streams.getPipedInputStream();
-               final ProtocolSession session = streams.getSession();
-
-               try {
-                       final ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
-                       int r = chan.read(byteBuffer);
-
-                       while (r != 0) {
-                               byteBuffer.flip();
-
-                               // if we have some unread data in the buffer
-                               while (byteBuffer.hasRemaining()) {
-                                       final int pisFree = session.maximumMessageSize() - pis.available();
-                                       if (pisFree == 0)
-                                               throw new IOException("Protocol failed to detect no-progress situation");
-
-                                       int toMove = byteBuffer.remaining();
-
-                                       // Do not try to write more than the input stream can accept
-                                       if (toMove > pisFree)
-                                               toMove = pisFree;
-
-                                       // Write to the output stream and adjust buffer position
-                                       pos.write(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), toMove);
-                                       byteBuffer.position(byteBuffer.position() + toMove);
-
-                                       // Notify input stream that it can read more stuff
-                                       pos.flush();
-
-                                       // process any messages which became available
-                                       while (pcepis.isMessageAvailable()) {
-                                               // read and parse message
-                                               final ProtocolMessage msg = pcepis.getMessage();
-                                               // send it to session for handling
-                                               session.handleMessage(msg);
-                                       }
-                               }
-                               byteBuffer.clear();
-
-                               /*
-                                * We reached end-of-input stream. Notify close the output stream
-                                * and notify the user. He is then supposed to close the session,
-                                * releasing the write-end of things.
-                                */
-                               if (r == -1) {
-                                       logger.warn("End of input stream reached.");
-                                       /*
-                                        * The input stream has some bytes, but no others are coming
-                                        * in. This means it should have been a complete message,
-                                        * but is not -> that's a malformed message.
-                                        */
-                                       if (pis.available() != 0) {
-                                               logger.warn("Received incomplete message.");
-                                               throw new DeserializerException("Incomplete message at the end of input stream");
-                                       }
-                                       key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
-                                       session.endOfInput();
-                                       return true;
-                               }
-
-                               if (!chan.isOpen())
-                                       return true;
-
-                               final long now = System.nanoTime();
-                               if (deadline <= now) {
-                                       logger.trace("Read service time exceeded by {} nanoseconds.", now - deadline);
-                                       break;
-                               }
-
-                               r = chan.read(byteBuffer);
-                       }
-               } catch (final DeserializerException e) {
-                       // An unrecoverable malformed message has been received. Notify
-                       // session to take care of the fallout.
-                       logger.warn("Malformed message {}", e.getMessage(), e);
-                       session.handleMalformedMessage(e);
-               } catch (final DocumentedException e) {
-                       // A potentially recoverable malformed message has been received.
-                       // Push it to the session, it will take care of the details.
-                       logger.warn("Malformed message {}", e.getMessage(), e);
-                       session.handleMalformedMessage(e);
-               } catch (final RuntimeException e) {
-                       logger.error("Unrecoverable internal session error: {}", e.getMessage(), e);
-                       throw new IOException("Unrecoverable internal session error", e);
-               }
-               return false;
-       }
+       final class ProtocolSessionPromise extends DefaultPromise<ProtocolSession> {
+               private final ChannelFuture cf;
 
-       /**
-        * Writes data from ProtocolOutputStream to socket.
-        *
-        * @param key selection key that was marked as ready to write from
-        * @return false if the writing was not successful true if the queue of messages became empty
-        * @throws IOException if there was some error with the IO streams
-        */
-       private boolean write(final SelectionKey key, final long deadline) throws IOException {
-               logger.trace("Started writing.");
-
-               // TODO: promote to hard error?
-               final SocketChannel socketChannel = (SocketChannel) key.channel();
-               if (!socketChannel.isConnected()) {
-                       logger.warn("Channel is not connected yet.");
-                       return false;
+               ProtocolSessionPromise(final ChannelFuture cf) {
+                       super();
+                       this.cf = cf;
                }
 
-               final SessionStreams streams = (SessionStreams) key.attachment();
-               final Queue<ByteBuffer> queue = streams.getSession().getStream().getBuffers();
-
-               synchronized (queue) {
-                       logger.trace("Synchronized writing started.");
-                       // Write until there's not more data
-                       while (!queue.isEmpty()) {
-                               final ByteBuffer buf = queue.element();
-                               socketChannel.write(buf);
-                               if (buf.remaining() > 0) {
-                                       /*
-                                        * If there is not enough space in the socket to write all the data
-                                        * stay in writing mode and attempt to write after the next select()
-                                        * call
-                                        */
-                                       logger.trace("Socket queue full.");
-                                       return false;
-                               }
-                               queue.remove();
-
-                               final long now = System.nanoTime();
-                               if (deadline <= now) {
-                                       logger.trace("Write service time exceeded by {} nanoseconds.", now - deadline);
-                                       return false;
-                               }
-                       }
-                       logger.trace("Write queue empty.");
-                       return true;
+               @Override
+               public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
+                       this.cf.cancel(mayInterruptIfRunning);
+                       return super.cancel(mayInterruptIfRunning);
                }
        }
 
-       private void acceptChannel(final ProtocolServer server, final SocketChannel socketChannel, final InetSocketAddress clientAddress)
-                       throws IOException {
-               socketChannel.configureBlocking(false);
+       private static final Logger logger = LoggerFactory.getLogger(DispatcherImpl.class);
 
-               final ProtocolSession s = server.createSession(this.stateTimer, clientAddress);
-               final PipedOutputStream pos = new PipedOutputStream();
-               final PipedInputStream pis = new PipedInputStream(pos, s.maximumMessageSize());
-               final ProtocolInputStream inputStream = server.createInputStream(pis, s.getMessageFactory());
+       private final EventLoopGroup bossGroup;
 
-               final SelectionKey skey = socketChannel.register(this.innerRun.selector, SelectionKey.OP_READ);
-               skey.attach(new SessionStreams(pos, pis, inputStream, s, null));
-               this.sessionKeys.put(s, skey);
-
-               // FIXME: catch RuntimeExceptions here, undo the put/attach above?
-               // or can we move the .put() after this call?
-               s.startSession();
-       }
+       private final EventLoopGroup workerGroup;
 
        /**
-        * Accepts incoming connection from a client to one of the running servers.
-        *
-        * @param key selection key that was marked as ready to accept connections
-        * @throws IOException if there was some error with IO streams
+        * Timer object grouping FSM Timers
         */
-       private void accept(final SelectionKey key) throws IOException {
-               final ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
-               final SocketChannel socketChannel = serverSocketChannel.accept();
-               if (socketChannel == null)
-                       return;
-
-               final InetSocketAddress clientAddress = (InetSocketAddress) socketChannel.getRemoteAddress();
-               logger.info("Requested connection for: {}", clientAddress.getAddress().getHostAddress());
-
-               try {
-                       this.acceptChannel((ProtocolServer) key.attachment(), socketChannel, clientAddress);
-               } catch (final Exception e) {
-                       logger.warn("Failed to start protocol session", e);
-                       socketChannel.close();
-               }
-       }
+       private final Timer stateTimer;
 
-       /**
-        * Finishes connection of the client to the server. Starts session.
-        *
-        * @param key selection key that was marked as ready to finish connection
-        */
-       private boolean finishConnection(final SelectionKey key) {
-               final SocketChannel socketChannel = (SocketChannel) key.channel();
-               final SessionStreams streams = (SessionStreams) key.attachment();
-               logger.trace("Finishing connection for key {}", key);
-               try {
-                       if (socketChannel.finishConnect()) {
-                               key.interestOps(SelectionKey.OP_READ);
-                               streams.getSession().startSession();
-                       }
-               } catch (final IOException e) {
-                       this.connectFailed(key, e);
-                       return false;
-               }
-               return true;
-       }
+       private final ProtocolHandlerFactory handlerFactory;
 
-       /**
-        * Closes channel and cancels key assigned to given session.
-        *
-        * @param session session that was closed
-        */
-       void closeSessionSockets(final ProtocolSession session) {
-               synchronized (this.innerRun) {
-                       logger.debug("Trying to close sesion.");
-                       final SelectionKey key = this.sessionKeys.get(session);
-                       if (key != null) {
-
-                               try {
-                                       key.channel().close();
-                               } catch (final IOException e) {
-                                       logger.error("Session channel could not be closed.");
-                               } finally {
-                                       final SessionStreams streams = (SessionStreams) key.attachment();
-                                       if (streams.timer != null) {
-                                               streams.timer.cancel();
-                                               streams.timer = null;
-                                       }
-
-                                       logger.trace("Cancelling key.");
-                                       key.cancel();
-
-                                       final PipedOutputStream pos = streams.getPipedOutputStream();
-                                       try {
-                                               pos.close();
-                                       } catch (final IOException e) {
-                                               logger.error("Session-internal output stream could not be closed.");
-                                       } finally {
-                                               final PipedInputStream pis = streams.getPipedInputStream();
-                                               try {
-                                                       pis.close();
-                                               } catch (final IOException e) {
-                                                       logger.error("Session-internal input stream could not be closed.");
-                                               }
-                                       }
-                               }
-                       }
-                       this.sessionKeys.remove(key);
-                       logger.debug("Session sockets closed.");
-               }
+       public DispatcherImpl(final ProtocolMessageFactory factory) {
+               this.bossGroup = new NioEventLoopGroup();
+               this.workerGroup = new NioEventLoopGroup();
+               this.stateTimer = new Timer();
+               this.handlerFactory = new ProtocolHandlerFactory(factory);
        }
 
        @Override
-       public void onSessionClosed(final ProtocolSession session) {
-               synchronized (this.innerRun) {
-                       this.innerRun.selector.wakeup();
-                       this.closeSessionSockets(session);
-                       this.clients.inverse().remove(session);
-                       logger.debug("Session {} removed.", session);
-               }
+       public ProtocolServer createServer(final InetSocketAddress address, final ProtocolConnectionFactory connectionFactory,
+                       final ProtocolSessionFactory sessionFactory) {
+               final ProtocolServer server = new ProtocolServer(address, connectionFactory, sessionFactory);
+               final ServerBootstrap b = new ServerBootstrap();
+               b.group(this.bossGroup, this.workerGroup);
+               b.channel(NioServerSocketChannel.class);
+               b.option(ChannelOption.SO_BACKLOG, 128);
+               b.childHandler(new ServerChannelInitializer(server));
+               b.childOption(ChannelOption.SO_KEEPALIVE, true);
+
+               // Bind and start to accept incoming connections.
+               final ChannelFuture f = b.bind(address);
+               // b.localAddress(address);
+               logger.debug("Server {} created.", server);
+               return server;
        }
 
        @Override
-       public void checkOutputBuffer(final ProtocolSession session) {
-               final SelectionKey key = this.sessionKeys.get(session);
-               key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
-               key.selector().wakeup();
+       public Future<ProtocolSession> createClient(final ProtocolConnection connection, final ProtocolSessionFactory sfactory) {
+               final Bootstrap b = new Bootstrap();
+               b.group(this.workerGroup);
+               b.channel(NioSocketChannel.class);
+               b.option(ChannelOption.SO_KEEPALIVE, true);
+               final ClientChannelInitializer init = new ClientChannelInitializer(connection, sfactory);
+               b.handler(init);
+               final ChannelFuture f = b.connect(connection.getPeerAddress());
+               final ProtocolSessionPromise p = new ProtocolSessionPromise(f);
+
+               f.addListener(new ChannelFutureListener() {
+                       @Override
+                       public void operationComplete(final ChannelFuture cf) {
+                               if (cf.isSuccess()) {
+                                       p.setSuccess(init.getSession());
+                                       return;
+                               } else if (cf.isCancelled()) {
+                                       p.cancel(false);
+                               } else
+                                       p.setFailure(cf.cause());
+                       }
+               });
+               logger.debug("Client created.");
+               return p;
        }
 
        @Override
        public void close() throws IOException {
-               for (final Entry<InetSocketAddress, ProtocolServer> s : this.servers.entrySet()) {
-                       s.getValue().close();
-               }
-               for (final Entry<InetSocketAddress, ProtocolSession> s : this.clients.entrySet()) {
-                       s.getValue().close();
-               }
-       }
-
-       /**
-        * Gets milliseconds between reconnects.
-        * @return time in milliseconds between reconnects
-        */
-       public synchronized int getReconnectMillis() {
-               return this.reconnectMillis;
+               this.workerGroup.shutdownGracefully();
+               this.bossGroup.shutdownGracefully();
        }
 
-       /**
-        * Sets milliseconds between reconnects.
-        * @param reconnectMillis new value
-        */
-       public synchronized void setReconnectMillis(final int reconnectMillis) {
-               Preconditions.checkArgument(reconnectMillis > 0, "Reconnect milliseconds value has to be positive");
-               this.reconnectMillis = reconnectMillis;
-               // FIXME: readjust all pending timers
-       }
-
-       /**
-        * Gets maximum tries for connection.
-        * @return max connection count
-        */
-       public synchronized int getMaxConnectCount() {
-               return this.maxConnectCount;
-       }
-
-       /**
-        * Sets maximum tries for connection.
-        * @param maxConnectCount new value
-        */
-       public synchronized void setMaxConnectCount(final int maxConnectCount) {
-               this.maxConnectCount = maxConnectCount;
-               // FIXME: purge all sessions which already exceed the limit
-       }
-
-       public synchronized int getServiceMillis() {
-               return this.serviceMillis;
-       }
-
-       public synchronized void setServiceMillis(final int serviceMillis) {
-               Preconditions.checkArgument(serviceMillis > 0);
-               this.serviceMillis = serviceMillis;
-       }
-
-       /**
-        * Gets thread factory.
-        * @return thread factory
-        */
-       public ThreadFactory getThreadFactory() {
-               return this.threadFactory;
+       @Override
+       public void onSessionClosed(final ProtocolSession session) {
+               // TODO Auto-generated method stub
        }
 }
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolHandlerFactory.java b/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolHandlerFactory.java
new file mode 100644 (file)
index 0000000..1c3674d
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.protocol.framework;
+
+import io.netty.channel.ChannelHandler;
+
+public class ProtocolHandlerFactory {
+
+       private final ProtocolMessageEncoder encoder;
+
+       private final ProtocolMessageDecoder decoder;
+
+       public ProtocolHandlerFactory(final ProtocolMessageFactory msgFactory) {
+               super();
+               this.encoder = new ProtocolMessageEncoder(msgFactory);
+               this.decoder = new ProtocolMessageDecoder(msgFactory);
+       }
+
+       public ChannelHandler[] getHandlers(final ProtocolSession session) {
+               return new ChannelHandler[] { this.encoder, new ProtocolSessionInboundHandler(session),
+                               new ProtocolSessionOutboundHandler(session), this.decoder };
+       }
+}
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolInputStream.java b/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolInputStream.java
deleted file mode 100644 (file)
index 060eb38..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.io.IOException;
-
-/**
- * Data stream interface between Protocol Message and byte array, that represents this message as Java object. Used by
- * the Dispatcher.
- */
-public interface ProtocolInputStream {
-
-       /**
-        * Check availability of a message in underlying input stream. A message is available when there are more or the
-        * same amount of bytes in the stream as the message length is specified in message header. If there are not enough
-        * bytes for the message or even to read a message header, return false. Needs to be synchronized.
-        *
-        * @return true if there are enough bytes to read a message false if there are not enough bytes to read a message or
-        *         a message header.
-        *
-        * @throws IOException this exception may be thrown when "impossible" protocol buffering conditions occur.
-        *         Examples include: we are attempting to wait for more data than is theoretically possible (e.g. framing
-        *         error), peer is attempting to make us buffer more data than possible to accomodate (2G chunk), etc.
-        */
-       public boolean isMessageAvailable() throws IOException;
-
-       /**
-        * If there are enough bytes in the underlying stream, parse the message. Blocking, till there are enough bytes to
-        * read, therefore the call of method isMessageAvailable() is suggested first. Needs to be synchronized.
-        *
-        * @return protocol specific message
-        *
-        * @throws DeserializerException if the parsing was not successful due to syntax error
-        * @throws IOException if there was problem with extracting bytes from the stream
-        * @throws DocumentedException if the parsing was not successful
-        */
-       public ProtocolMessage getMessage() throws DeserializerException, IOException, DocumentedException;
-}
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolInputStreamFactory.java b/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolInputStreamFactory.java
deleted file mode 100644 (file)
index 8ee37d6..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.io.PipedInputStream;
-
-/**
- * Factory for creating Protocol input streams. Should be implemented to return protocol
- * specific input stream.
- */
-public interface ProtocolInputStreamFactory {
-
-       /**
-        * Creates and returns protocol input stream.
-        * @param pis underlying piped input stream
-        * @param pmf protocol message factory
-        * @return protocol specific input stream
-        */
-       ProtocolInputStream getProtocolInputStream(PipedInputStream pis, ProtocolMessageFactory pmf);
-}
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolMessageDecoder.java b/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolMessageDecoder.java
new file mode 100644 (file)
index 0000000..f3be094
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.protocol.framework;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.MessageList;
+import io.netty.handler.codec.ByteToMessageDecoder;
+
+final class ProtocolMessageDecoder extends ByteToMessageDecoder {
+
+       private final ProtocolMessageFactory factory;
+
+       public ProtocolMessageDecoder(final ProtocolMessageFactory factory) {
+               this.factory = factory;
+       }
+
+       @Override
+       public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final MessageList<Object> out) throws Exception {
+               ProtocolMessage msg = null;
+               try {
+                       msg = this.factory.parse(in.array());
+               } catch (DeserializerException | DocumentedException e) {
+                       this.exceptionCaught(ctx, e);
+               }
+               out.add(msg);
+       }
+
+       @Override
+       public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
+               // TODO:
+               ctx.close();
+       }
+}
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolMessageEncoder.java b/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolMessageEncoder.java
new file mode 100644 (file)
index 0000000..7b31737
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.protocol.framework;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandler.Sharable;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.MessageToByteEncoder;
+
+@Sharable
+final class ProtocolMessageEncoder extends MessageToByteEncoder<ProtocolMessage> {
+
+       private final ProtocolMessageFactory factory;
+
+       public ProtocolMessageEncoder(final ProtocolMessageFactory factory) {
+               this.factory = factory;
+       }
+
+       @Override
+       protected void encode(final ChannelHandlerContext ctx, final ProtocolMessage msg, final ByteBuf out) throws Exception {
+               out.writeBytes(this.factory.put(msg));
+       }
+}
index df8a0628083919784aa42ceb357a1d115abe1275..ea2e2c42cf0cfbe3644bbe85fd630dee72d62715 100644 (file)
@@ -8,26 +8,26 @@
 package org.opendaylight.protocol.framework;
 
 /**
- * Interface for factory for parsing and serializing protocol specific
- * messages. Needs to be implemented by a protocol specific message
- * factory. The methods put/parse should delegate parsing to specific
- * message parsers, e.g. OpenMessageParser etc.
+ * Interface for factory for parsing and serializing protocol specific messages. Needs to be implemented by a protocol
+ * specific message factory. The methods put/parse should delegate parsing to specific message parsers, e.g.
+ * OpenMessageParser etc.
  */
 public interface ProtocolMessageFactory {
 
        /**
-        * Parses message from byte array. Requires specific protocol message
-        * header object to parse the header.
+        * Parses message from byte array. Requires specific protocol message header object to parse the header.
+        * 
         * @param bytes byte array from which the message will be parsed
         * @param msgHeader protocol specific message header to parse the header
         * @return specific protocol message
         * @throws DeserializerException if some parsing error occurs
         * @throws DocumentedException if some documented error occurs
         */
-       public ProtocolMessage parse(final byte[] bytes, final ProtocolMessageHeader msgHeader) throws DeserializerException, DocumentedException;
+       public ProtocolMessage parse(final byte[] bytes) throws DeserializerException, DocumentedException;
 
        /**
         * Serializes protocol specific message to byte array.
+        * 
         * @param msg message to be serialized.
         * @return byte array resulting message
         */
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolOutputStream.java b/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolOutputStream.java
deleted file mode 100644 (file)
index 7b6f1c6..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayDeque;
-import java.util.Queue;
-
-/**
- * Data stream interface between ProtocolMessage and byte array,
- * that represents this message in serialized form. Its instance
- * needs to be present in protocol specific session, to allow
- * sending messages from the session via the put() method.
- */
-public final class ProtocolOutputStream {
-
-       /**
-        * List of Buffers whose content needs to be written to socket.
-        */
-       private final Queue<ByteBuffer> pendingData = new ArrayDeque<ByteBuffer>();
-
-       /**
-        * Assumes that the message is valid (that you cannot create an invalid
-        * message from API). Serializes given messages to byte array, converts this
-        * byte array to byteBuffer and adds it to List.
-        * @param message message to be written
-        * @param factory protocol specific message factory
-        */
-       public void putMessage(final ProtocolMessage message, final ProtocolMessageFactory factory) {
-               final byte[] bytes = factory.put(message);
-               if (bytes == null) {
-                       throw new IllegalArgumentException("Message parsed to null.");
-               }
-               synchronized (this.pendingData) {
-                       this.pendingData.add(ByteBuffer.wrap(bytes));
-               }
-       }
-
-       /**
-        * Used by PCEPDispatcher to retrieve the data that needs to be written to
-        * socket.
-        *
-        * @return data that needs to be written to socket
-        */
-       Queue<ByteBuffer> getBuffers() {
-               return this.pendingData;
-       }
-}
index d7860f0b912c09186e6bd3d7e36239648d9d0d7c..903fb83918a664945286235c2b8880f3284d83af 100644 (file)
@@ -7,16 +7,15 @@
  */
 package org.opendaylight.protocol.framework;
 
+import io.netty.channel.Channel;
+
 import java.io.IOException;
-import java.io.PipedInputStream;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.nio.channels.ServerSocketChannel;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.Map.Entry;
 import java.util.Timer;
 
 import org.slf4j.Logger;
@@ -37,11 +36,8 @@ public class ProtocolServer implements SessionParent {
 
        private final InetSocketAddress serverAddress;
 
-       private final ServerSocketChannel channel;
-
        private final ProtocolConnectionFactory connectionFactory;
        private final ProtocolSessionFactory sessionFactory;
-       private final ProtocolInputStreamFactory inputStreamFactory;
 
        /**
         * Maps clients of this server to their address. The client is represented as PCEP session. Used BiMap for
@@ -51,11 +47,9 @@ public class ProtocolServer implements SessionParent {
 
        private final Map<InetSocketAddress, Integer> sessionIds;
 
-       private final DispatcherImpl dispatcher;
-
        /**
         * Creates a Protocol server.
-        *
+        * 
         * @param dispatcher Dispatcher
         * @param address address to which this server is bound
         * @param connectionFactory factory for connection specific properties
@@ -63,16 +57,12 @@ public class ProtocolServer implements SessionParent {
         * @param sessionFactory factory for sessions
         * @param inputStreamFactory factory for input streams
         */
-       public ProtocolServer(final DispatcherImpl dispatcher, final InetSocketAddress address, final ServerSocketChannel channel,
-                       final ProtocolConnectionFactory connectionFactory, final ProtocolSessionFactory sessionFactory,
-                       final ProtocolInputStreamFactory inputStreamFactory) {
-               this.dispatcher = dispatcher;
+       public ProtocolServer(final InetSocketAddress address, final ProtocolConnectionFactory connectionFactory,
+                       final ProtocolSessionFactory sessionFactory) {
                this.serverAddress = address;
-               this.channel = channel;
                this.sessions = HashBiMap.create();
                this.connectionFactory = connectionFactory;
                this.sessionFactory = sessionFactory;
-               this.inputStreamFactory = inputStreamFactory;
                this.sessionIds = new HashMap<InetSocketAddress, Integer>();
        }
 
@@ -80,14 +70,15 @@ public class ProtocolServer implements SessionParent {
         * Creates a session. This method is called after the server accepts incoming client connection. A session is
         * created for each client. If a session for a client (represented by the address) was already created, return this,
         * else create a new one.
-        *
+        * 
         * @param clientAddress IP address of the client
         * @param timer Timer common for all sessions
         * @return new or existing PCEPSession
         * @see <a href="http://tools.ietf.org/html/rfc5440#appendix-A">RFC</a>
         */
-       public ProtocolSession createSession(final Timer timer, final InetSocketAddress clientAddress) {
+       public ProtocolSession createSession(final Timer timer, final Channel channel) {
                ProtocolSession session = null;
+               final InetSocketAddress clientAddress = (InetSocketAddress) channel.remoteAddress();
                if (this.sessions.containsKey(clientAddress)) { // when the session is created, the key is the InetSocketAddress
                        session = this.sessions.get(clientAddress);
                        if (compareTo(this.serverAddress.getAddress(), clientAddress.getAddress()) > 0) {
@@ -100,20 +91,16 @@ public class ProtocolServer implements SessionParent {
                } else {
                        final int sessionId = getNextId(this.sessionIds.get(clientAddress), SESSIONS_LIMIT - 1);
                        session = this.sessionFactory.getProtocolSession(this, timer, this.connectionFactory.createProtocolConnection(clientAddress),
-                                       sessionId);
+                                       sessionId, channel.pipeline().context(ProtocolSessionOutboundHandler.class));
                        this.sessionIds.put(clientAddress, sessionId);
                }
                this.sessions.put(clientAddress, session);
                return session;
        }
 
-       ProtocolInputStream createInputStream(final PipedInputStream pis, final ProtocolMessageFactory pmf) {
-               return this.inputStreamFactory.getProtocolInputStream(pis, pmf);
-       }
-
        /**
         * Returns server address.
-        *
+        * 
         * @return server address
         */
        public InetSocketAddress getAddress() {
@@ -122,24 +109,13 @@ public class ProtocolServer implements SessionParent {
 
        @Override
        public synchronized void close() throws IOException {
-               for (final Entry<InetSocketAddress, ProtocolSession> s : this.sessions.entrySet()) {
-                       s.getValue().close();
-               }
-               this.sessions.clear();
-               this.dispatcher.removeServer(this);
-               this.channel.close();
+               // TODO:
                logger.debug("Server {} closed.", this);
        }
 
        @Override
        public synchronized void onSessionClosed(final ProtocolSession session) {
                this.sessions.inverse().remove(session); // when the session is closed, the key is the instance of the session
-               this.dispatcher.closeSessionSockets(session);
-       }
-
-       @Override
-       public void checkOutputBuffer(final ProtocolSession session) {
-               this.dispatcher.checkOutputBuffer(session);
        }
 
        private static int getNextId(Integer lastId, final int maxId) {
@@ -148,7 +124,7 @@ public class ProtocolServer implements SessionParent {
 
        /**
         * Compares byte array representations of two InetAddresses.
-        *
+        * 
         * @param addrOne
         * @param addrTwo
         * @throws IllegalArgumentException if InetAddresses don't belong to the same subclass of InetAddress.
@@ -169,4 +145,9 @@ public class ProtocolServer implements SessionParent {
                }
                return 0;
        }
+
+       @Override
+       public String toString() {
+               return "ProtocolServer [serverAddress=" + this.serverAddress + ", hashCode()=" + hashCode() + "]";
+       }
 }
index 3646a79eff9c2ad277a2bc6af33ed7f16d4e8c00..857169305a0269478ef3809c1ac31c7519b0f11a 100644 (file)
@@ -11,49 +11,39 @@ import java.io.Closeable;
 import java.io.IOException;
 
 /**
- * Protocol Session represents the finite state machine in underlying
- * protocol, including timers and its purpose is to create a connection
- * between server and client. Session is automatically started, when TCP
- * connection is created, but can be stopped manually.
- * If the session is up, it has to redirect messages to/from user.
- * Handles also malformed messages and unknown requests.
- *
- * This interface should be implemented by a final class representing
- * a protocol specific session.
+ * Protocol Session represents the finite state machine in underlying protocol, including timers and its purpose is to
+ * create a connection between server and client. Session is automatically started, when TCP connection is created, but
+ * can be stopped manually. If the session is up, it has to redirect messages to/from user. Handles also malformed
+ * messages and unknown requests.
+ * 
+ * This interface should be implemented by a final class representing a protocol specific session.
  */
 public interface ProtocolSession extends Closeable {
 
        /**
-        * Starts the session. This method should be used only internally by
-        * the Dispatcher.
+        * Starts the session. This method should be used only internally by the Dispatcher.
         */
        public void startSession();
 
-       /**
-        * Returns underlying output stream to provide writable stream to the
-        * Dispatcher.
-        * @return underlying protocol specific output stream
-        */
-       public ProtocolOutputStream getStream();
-
        /**
         * Handles incoming message (parsing, reacting if necessary).
+        * 
         * @param msg incoming message
         */
        public void handleMessage(final ProtocolMessage msg);
 
        /**
-        * Handles malformed message when a deserializer exception occurred.
-        * The handling might be different from when a documented exception
-        * is thrown.
+        * Handles malformed message when a deserializer exception occurred. The handling might be different from when a
+        * documented exception is thrown.
+        * 
         * @param e deserializer exception that occurred
         */
        public void handleMalformedMessage(final DeserializerException e);
 
        /**
-        * Handles malformed message when a documented exception occurred.
-        * The handling might be different from when a deserializer exception
-        * is thrown.
+        * Handles malformed message when a documented exception occurred. The handling might be different from when a
+        * deserializer exception is thrown.
+        * 
         * @param e documented exception that occurred
         */
        public void handleMalformedMessage(final DocumentedException e);
@@ -65,24 +55,21 @@ public interface ProtocolSession extends Closeable {
 
        /**
         * Getter for message factory
+        * 
         * @return protocol specific message factory
         */
        public ProtocolMessageFactory getMessageFactory();
 
        /**
-        * Session is notified about the connection not being
-        * established successfully.
-        *
-        * @param e IOException that was the cause of
-        * failed connection.
+        * Session is notified about the connection not being established successfully.
+        * 
+        * @param e IOException that was the cause of failed connection.
         */
        public void onConnectionFailed(final IOException e);
 
        /**
-        * Returns the maximum message size (in bytes) for purposes of dispatcher
-        * buffering -- the dispatcher allocates a buffer this big, and if it gets
-        * full without making decoding progress, the dispatcher terminates the
-        * session.
+        * Returns the maximum message size (in bytes) for purposes of dispatcher buffering -- the dispatcher allocates a
+        * buffer this big, and if it gets full without making decoding progress, the dispatcher terminates the session.
         * 
         * @return maximum message size
         */
index 36d46501f4cdd66f0dcc23ed3c24b4186930039f..c5dcbc3f4d418abd1393cf6ca1fc4adf3167800b 100644 (file)
@@ -7,21 +7,24 @@
  */
 package org.opendaylight.protocol.framework;
 
+import io.netty.channel.ChannelHandlerContext;
+
 import java.util.Timer;
 
 /**
- * Factory for generating Protocol Sessions. This class should be extended to
- * return protocol specific session.
+ * Factory for generating Protocol Sessions. This class should be extended to return protocol specific session.
  */
 public interface ProtocolSessionFactory {
 
        /**
         * Creates and returns protocol specific session.
+        * 
         * @param parent SessionParent
         * @param timer Timer
         * @param connection connection attributes
         * @param sessionId session identifier
         * @return new session
         */
-       public ProtocolSession getProtocolSession(SessionParent parent, Timer timer, ProtocolConnection connection, int sessionId);
+       public ProtocolSession getProtocolSession(SessionParent dispatcher, Timer timer, ProtocolConnection connection, int sessionId,
+                       ChannelHandlerContext ctx);
 }
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSessionInboundHandler.java b/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSessionInboundHandler.java
new file mode 100644 (file)
index 0000000..070aa4f
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.protocol.framework;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.MessageList;
+
+final class ProtocolSessionInboundHandler extends ChannelInboundHandlerAdapter {
+
+       private final ProtocolSession session;
+
+       public ProtocolSessionInboundHandler(final ProtocolSession session) {
+               this.session = session;
+       }
+
+       @Override
+       public void messageReceived(final ChannelHandlerContext ctx, final MessageList<Object> msgs) {
+               final MessageList<ProtocolMessage> pmsgs = msgs.cast();
+               for (final ProtocolMessage msg : pmsgs) {
+                       this.session.handleMessage(msg);
+               }
+       }
+}
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSessionOutboundHandler.java b/framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSessionOutboundHandler.java
new file mode 100644 (file)
index 0000000..c919f2f
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.protocol.framework;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelOutboundHandlerAdapter;
+import io.netty.channel.MessageList;
+
+public final class ProtocolSessionOutboundHandler extends ChannelOutboundHandlerAdapter {
+
+       private final ProtocolSession session;
+
+       public ProtocolSessionOutboundHandler(final ProtocolSession session) {
+               this.session = session;
+       }
+
+       @Override
+       public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
+               this.session.startSession();
+       }
+
+       @Override
+       public void handlerRemoved(final ChannelHandlerContext ctx) throws Exception {
+               this.session.close();
+       }
+
+       @Override
+       public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
+               // TODO:
+               cause.printStackTrace();
+               ctx.close();
+       }
+
+       public void writeDown(final ChannelHandlerContext ctx, final ProtocolMessage msg) throws Exception {
+               this.write(ctx, MessageList.<Object> newInstance(msg), ctx.newPromise());
+       }
+}
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/SSLSelectableChannel.java b/framework/src/main/java/org/opendaylight/protocol/framework/SSLSelectableChannel.java
deleted file mode 100644 (file)
index 85e9a99..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-/**
- * As in order to work with SSLSelectionKey, a channel needs to implement
- * this interface. It is used to determine SSL progress and update interestOps
- * of underlying channel.
- */
-interface SSLSelectableChannel {
-       /**
-        * Return the events which the underlying channel should be selected for,
-        * based on what the user would like to see from us.
-        * 
-        * @param ops user's interest ops
-        * @return Calculated interest ops, including internal needs
-        */
-       public int computeInterestOps(final int ops);
-
-       /**
-        * Return a freshly-calculated operations which the channel is ready to
-        * make progress on.
-        * 
-        * @return Calculated ready ops
-        */
-       public int computeReadyOps();
-}
-
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/SSLSelectionKey.java b/framework/src/main/java/org/opendaylight/protocol/framework/SSLSelectionKey.java
deleted file mode 100644 (file)
index 12fb474..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.io.IOException;
-import java.nio.channels.CancelledKeyException;
-import java.nio.channels.SelectableChannel;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.spi.AbstractSelectionKey;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class SSLSelectionKey extends AbstractSelectionKey {
-       private static final Logger logger = LoggerFactory.getLogger(SSLSelectionKey.class);
-       private final SelectableChannel channel;
-       private final Selector selector;
-       private final SelectionKey key;
-       private int ops = 0, readyOps = 0;
-
-       SSLSelectionKey(final Selector selector, final SelectionKey key, final SelectableChannel channel) {
-               this.selector = selector;
-               this.channel = channel;
-               this.key = key;
-       }
-
-       @Override
-       public SelectableChannel channel() {
-               return channel;
-       }
-
-       @Override
-       public int interestOps() {
-               return ops;
-       }
-
-       @Override
-       public SelectionKey interestOps(final int ops) {
-               this.ops = ops;
-               return this;
-       }
-
-       @Override
-       public int readyOps() {
-               return readyOps;
-       }
-
-       @Override
-       public Selector selector() {
-               return selector;
-       }
-
-       void cancelSlave() {
-               key.cancel();
-       }
-
-       void updateInterestOps() {
-               int newOps = ops;
-
-               if (channel instanceof SSLSocketChannel) {
-                       newOps = ((SSLSocketChannel)channel).computeInterestOps(ops);
-               } else if (channel instanceof SSLServerSocketChannel) {
-                       newOps = ((SSLServerSocketChannel)channel).computeInterestOps(ops);
-               }
-
-               logger.trace("Updating interestOps to {} (before SSL={})", newOps, ops);
-
-               // FIXME: is this check sufficient?
-               if (key.isValid())
-                       key.interestOps(newOps);
-       }
-
-       boolean preselectReady() {
-               final int newReadyOps;
-
-               // FIXME: abstract out interface
-               if (channel instanceof SSLSocketChannel) {
-                       final SSLSocketChannel sc = (SSLSocketChannel)channel;
-                       newReadyOps = sc.computeReadyOps();
-
-                       if (sc.hasParent()) {
-                               logger.trace("Child key, ready {}", newReadyOps);
-                               if ((newReadyOps & SelectionKey.OP_CONNECT) != 0) {
-                                       try {
-                                               if (sc.finishConnect()) {
-                                                       this.cancel();
-                                                       return true;
-                                               } else
-                                                       logger.trace("finishConnect indicated non-connect after poll. Possible leak.");
-                                       } catch (IOException e) {
-                                               logger.trace("Failed to establish child socket", e);
-                                               this.cancel();
-                                       }
-                               }
-                               return false;
-                       }
-               } else if (channel instanceof SSLServerSocketChannel) {
-                       newReadyOps = ((SSLServerSocketChannel)channel).computeReadyOps();
-               } else
-                       newReadyOps = 0;
-
-               logger.trace("Preselect: ready {} interest {} (A: {} R: {} W: {})",
-                               newReadyOps, ops, SelectionKey.OP_CONNECT, SelectionKey.OP_READ, SelectionKey.OP_WRITE);
-               return (newReadyOps & ops) != 0;
-       }
-
-       boolean updateReadyOps() {
-               int newReadyOps = 0;
-               if (channel instanceof SSLServerSocketChannel) {
-                       newReadyOps = ((SSLServerSocketChannel)channel).computeReadyOps();
-               } else if (channel instanceof SSLSocketChannel) {
-                       final SSLSocketChannel sc = (SSLSocketChannel)channel;
-
-                       // Do not report events for internal channels
-                       if (!sc.hasParent())
-                               newReadyOps = sc.computeReadyOps();
-               } else {
-                       try {
-                               newReadyOps = key.readyOps();
-                       } catch (CancelledKeyException e) {
-                               logger.trace("Encountered cancelled key, ignoring", e);
-                       }
-               }
-
-               if (readyOps == newReadyOps)
-                       return false;
-
-               logger.trace("Updating readyOps from {} to {}", readyOps, newReadyOps);
-               readyOps = newReadyOps;
-               return true;
-       }
-}
-
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/SSLSelector.java b/framework/src/main/java/org/opendaylight/protocol/framework/SSLSelector.java
deleted file mode 100644 (file)
index 68e4bc1..0000000
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.io.IOException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.ClosedSelectorException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.spi.AbstractSelectableChannel;
-import java.nio.channels.spi.AbstractSelector;
-import java.util.Collections;
-import java.util.Set;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.opendaylight.protocol.util.RemoveOnlySet;
-import com.google.common.collect.Sets;
-
-class SSLSelector extends AbstractSelector {
-       private static final Logger logger = LoggerFactory.getLogger(SSLSelector.class);
-       private final Set<SelectionKey> selectedKeys = Sets.newHashSet();
-       private final Set<SelectionKey> keys = Sets.newCopyOnWriteArraySet();
-
-       private final Set<SelectionKey> guardedSelectedKeys = RemoveOnlySet.wrap(selectedKeys);
-       private final Set<SelectionKey> guardedKeys = Collections.unmodifiableSet(keys);
-       private final Selector selector;
-       private boolean closed = false;
-
-       SSLSelector(final Selector selector) throws IOException {
-               super(selector.provider());
-               this.selector = selector;
-       }
-
-       @Override
-       protected void implCloseSelector() throws IOException {
-               // Make sure selection won't block
-               selector.wakeup();
-
-               synchronized (this) {
-                       if (!closed) {
-                               closed = true;
-                               for (SelectionKey k : keys)
-                                       k.cancel();
-
-                               keys.clear();
-                               selector.close();
-                       }
-               }
-       }
-
-       @Override
-       protected synchronized SelectionKey register(final AbstractSelectableChannel ch, final int ops, final Object att) {
-               ensureOpen();
-
-               final AbstractSelectableChannel slave;
-               if (ch instanceof SSLServerSocketChannel)
-                       slave = ((SSLServerSocketChannel)ch).channel;
-               else if (ch instanceof SSLSocketChannel)
-                       slave = ((SSLSocketChannel)ch).channel;
-               else
-                       slave = ch;
-
-               logger.trace("Register channel {} slave {} with ops {}", ch, slave, ops);
-
-               final SelectionKey key;
-               try {
-                       key = new SSLSelectionKey(this, slave.register(selector, 0, null), ch);
-               } catch (ClosedChannelException e) {
-                       throw new IllegalStateException("Slave selector found the channel closed", e);
-               }
-               key.interestOps(ops);
-               key.attach(att);
-               keys.add(key);
-               return key;
-       }
-
-       @Override
-       public synchronized Set<SelectionKey> keys() {
-               ensureOpen();
-               return guardedKeys;
-       }
-
-       private void ensureOpen() {
-               if (closed)
-                       throw new ClosedSelectorException();
-       }
-
-       private int afterSelect() {
-               logger.trace("Running afterSelect");
-               int ret = 0;
-
-               final Set<SelectionKey> ck = cancelledKeys();
-               synchronized (ck) {
-                       selectedKeys.removeAll(ck);
-
-                       for (final SelectionKey k : keys) {
-                               final boolean updated = ((SSLSelectionKey)k).updateReadyOps();
-                               if ((k.readyOps() & k.interestOps()) != 0) {
-                                       selectedKeys.add(k);
-                                       if (updated)
-                                               ++ret;
-                               } else
-                                       selectedKeys.remove(k);
-                       }
-               }
-
-               return ret;
-       }
-
-       private boolean beforeSelect() {
-               logger.trace("Running beforeSelect");
-
-               final Set<SelectionKey> ck = cancelledKeys();
-               synchronized (ck) {
-                       for (final SelectionKey k : ck)
-                               ((SSLSelectionKey)k).cancelSlave();
-                       selectedKeys.removeAll(ck);
-                       keys.removeAll(ck);
-                       ck.clear();
-
-                       for (final SelectionKey k : keys) {
-                               final SSLSelectionKey sk = (SSLSelectionKey)k;
-                               if (sk.preselectReady()) {
-                                       logger.trace("Key {} ready in preselect", k);
-                                       return true;
-                               } else
-                                       sk.updateInterestOps();
-                       }
-               }
-
-               return false;
-       }
-
-       @Override
-       public synchronized int select() throws IOException {
-               return select(0);
-       }
-
-       @Override
-       public synchronized int select(final long timeout) throws IOException {
-               ensureOpen();
-
-               if (!beforeSelect()) {
-                       try {
-                               begin();
-                               selector.select(timeout);
-                       } finally {
-                               end();
-                       }
-               }
-               return afterSelect();
-       }
-
-       @Override
-       public synchronized int selectNow() throws IOException {
-               ensureOpen();
-
-               if (!beforeSelect())
-                       selector.selectNow();
-               return afterSelect();
-       }
-
-       @Override
-       public synchronized Set<SelectionKey> selectedKeys() {
-               ensureOpen();
-               return guardedSelectedKeys;
-       }
-
-       @Override
-       public Selector wakeup() {
-               logger.trace("Running wakeup");
-               selector.wakeup();
-               return this;
-       }
-}
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/SSLServerSocketChannel.java b/framework/src/main/java/org/opendaylight/protocol/framework/SSLServerSocketChannel.java
deleted file mode 100644 (file)
index cfccf08..0000000
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.io.IOException;
-import java.net.ServerSocket;
-import java.net.SocketAddress;
-import java.net.SocketOption;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.util.Queue;
-import java.util.Set;
-import java.util.concurrent.Executor;
-
-import javax.net.ssl.SSLContext;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Queues;
-
-/**
- * SSL-enabled equivalent of ServerSocketChannel. This class uses a backend
- * ServerSocketChannel to implement network functionality. Each instance is
- * bound to a SSLContext, which is used to create a per-connection SSLEngine,
- * which is encapsulated into the returned SSLSocketChannel.
- */
-final class SSLServerSocketChannel extends ServerSocketChannel implements SSLSelectableChannel {
-       private static final Logger logger = LoggerFactory.getLogger(SSLServerSocketChannel.class);
-       private final Queue<SocketChannel> newChannels = Queues.newArrayDeque();
-       private final SSLContext context;
-       private final Executor executor;
-       private final Selector selector;
-       private boolean closed = false;
-
-       protected final ServerSocketChannel channel;
-
-       private SSLServerSocketChannel(final Selector selector, final ServerSocketChannel channel, final SSLContext context, final Executor executor) {
-               super(channel.provider());
-               this.selector = selector;
-               this.executor = executor;
-               this.channel = channel;
-               this.context = context;
-       }
-
-       public static SSLServerSocketChannel open(final Selector selector, final SSLContext context, final Executor executor) throws IOException {
-               return new SSLServerSocketChannel(selector, ServerSocketChannel.open(), context, executor);
-       }
-
-       @Override
-       public final synchronized SocketChannel accept() {
-               return newChannels.poll();
-       }
-
-       @Override
-       public ServerSocket socket() {
-               // We do not support this operation, everyone should use Java 7 interfaces
-               throw new UnsupportedOperationException("SSLSocketChannel does not provide a fake Socket implementation");
-       }
-
-       @Override
-       protected synchronized void implCloseSelectableChannel() throws IOException {
-               closed = true;
-               while (!newChannels.isEmpty()) {
-                       final SocketChannel c = newChannels.poll();
-                       try {
-                               c.close();
-                       } catch (IOException e) {
-                               logger.trace("Failed to close a queued channel", e);
-                       }
-               }
-               channel.close();
-       }
-
-       @Override
-       protected void implConfigureBlocking(final boolean block) throws IOException {
-               channel.configureBlocking(block);
-       }
-
-       @Override
-       public final synchronized int computeInterestOps(final int ops) {
-               // We are always interested in accepting stuff
-               return SelectionKey.OP_ACCEPT;
-       }
-
-       private void performIO() {
-               while (true) {
-                       final SocketChannel newchan;
-                       try {
-                               newchan = channel.accept();
-                               if (newchan == null)
-                                       break;
-                       } catch (IOException e) {
-                               logger.trace("Underlying accept() failed", e);
-                               return;
-                       }
-
-                       try {
-                               final SocketChannel sc;
-                               try {
-                                       sc = SSLSocketChannel.open(newchan, context, executor, this);
-                               } catch (IOException e) {
-                                       logger.trace("Failed to create SSL channel", e);
-                                       newchan.close();
-                                       continue;
-                               }
-
-                               try {
-                                       sc.configureBlocking(false);
-                                       sc.register(selector, SelectionKey.OP_CONNECT, null);
-                               } catch (IOException e) {
-                                       logger.trace("Failed to register SSL channel", e);
-                                       sc.close();
-                                       continue;
-                               }
-
-                               logger.trace("Accepted new connection, channel is {} backend {}", sc, newchan);
-                       } catch (IOException e1) {
-                               logger.trace("Failed to close failed channel", e1);
-                       }
-               }
-       }
-
-       @Override
-       public final synchronized int computeReadyOps() {
-               if (closed)
-                       return 0;
-
-               performIO();
-
-               // We need to be non-closed and have enqueue channels to be ready
-               if (!closed && !newChannels.isEmpty())
-                       return SelectionKey.OP_ACCEPT;
-               return 0;
-       }
-
-       /**
-        * Enqueue a freshly-established child channel for reporting as
-        * a ready-to-accept connection.
-        *
-        * @param channel Fresh channel, expected to be in connected state
-        */
-       final synchronized void addNewChannel(final SocketChannel channel) {
-               if (closed) {
-                       try {
-                               channel.close();
-                       } catch (IOException e) {
-                               logger.trace("Failed to close a queued channel", e);
-                       }
-               } else
-                       newChannels.add(channel);
-       }
-
-       @Override
-       public SocketAddress getLocalAddress() throws IOException {
-               return channel.getLocalAddress();
-       }
-
-       @Override
-       public <T> T getOption(SocketOption<T> name) throws IOException {
-               return channel.getOption(name);
-       }
-
-       @Override
-       public Set<SocketOption<?>> supportedOptions() {
-               return channel.supportedOptions();
-       }
-
-       @Override
-       public ServerSocketChannel bind(SocketAddress local, int backlog) throws IOException {
-               channel.bind(local, backlog);
-               return this;
-       }
-
-       @Override
-       public <T> ServerSocketChannel setOption(SocketOption<T> name, T value) throws IOException {
-               channel.setOption(name, value);
-               return this;
-       }
-}
-
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/SSLSocketChannel.java b/framework/src/main/java/org/opendaylight/protocol/framework/SSLSocketChannel.java
deleted file mode 100644 (file)
index bdf7eb4..0000000
+++ /dev/null
@@ -1,677 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.io.EOFException;
-import java.io.IOException;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketOption;
-import java.nio.ByteBuffer;
-import java.nio.channels.AlreadyConnectedException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.ConnectionPendingException;
-import java.nio.channels.NoConnectionPendingException;
-import java.nio.channels.NotYetConnectedException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.SocketChannel;
-import java.util.Set;
-import java.util.concurrent.Executor;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/*
- * Base class for an SSL-enabled socket channel. It is completed as
- * SSLSocketChannel in one of the two Java version-specific files.
- */
-final class SSLSocketChannel extends SocketChannel implements SSLSelectableChannel {
-       private enum InternalState {
-               /**
-                * Freshly created socket. Must be connected.
-                */
-               IDLE,
-               /**
-                * Underlying TCP connection is being established.
-                */
-               CONNECTING,
-               /**
-                * Underlying TCP connection is established, we are currently
-                * negotiating SSL session parameters.
-                */
-               NEGOTIATING,
-               /**
-                * Connection attempt has been resolved, we need the user
-                * to call finishConnect().
-                */
-               CONNECT_RESOLVED,
-               /**
-                * We have notified the user that the connection has failed,
-                * all we need to do is cleanup resources.
-                */
-               CONNECT_FAILED,
-               /**
-                * We have notified user that the connection has been
-                * established and the channel is fully operational.
-                */
-               CONNECTED,
-               /**
-                * We are closing down the channel. From user's perspective
-                * it is already dead, we just need to cleanup.
-                */
-               CLOSING,
-               /**
-                * The channel has been closed and all resources released.
-                */
-               CLOSED,
-       }
-
-       private static final Logger logger = LoggerFactory.getLogger(SSLSocketChannel.class);
-       private SSLServerSocketChannel parent;
-       final SocketChannel channel;
-       final SSLEngine engine;
-
-       private final ByteBuffer fromNetwork, toNetwork, toUser;
-       private final ByteBuffer empty = ByteBuffer.allocate(0);
-       private final Executor executor;
-       private IOException connectResult = null;
-       private IOException writeFailed = null, closeFailed = null;
-       private boolean readDone = false;
-       private boolean closedInput = false, closedOutput = false;
-       private InternalState state;
-
-       private SSLSocketChannel(final SocketChannel channel, final SSLEngine engine,
-                       final Executor executor, final SSLServerSocketChannel parent) throws SSLException {
-               super(channel.provider());
-               this.executor = executor;
-               this.channel = channel;
-               this.parent = parent;
-               this.engine = engine;
-
-               final SSLSession session = engine.getSession();
-               fromNetwork = ByteBuffer.allocate(session.getPacketBufferSize());
-               fromNetwork.limit(0);
-               toNetwork = ByteBuffer.allocate(session.getPacketBufferSize());
-               toNetwork.limit(0);
-               toUser = ByteBuffer.allocate(session.getApplicationBufferSize());
-
-               if (parent != null) {
-                       engine.setUseClientMode(false);
-                       engine.setWantClientAuth(true);
-                       engine.setNeedClientAuth(false);
-                       engine.beginHandshake();
-                       state = InternalState.NEGOTIATING;
-               } else
-                       state = InternalState.IDLE;
-       }
-
-       public static SSLSocketChannel open(final SocketChannel channel, final SSLContext context,
-                       final Executor executor, final SSLServerSocketChannel parent) throws IOException {
-
-               return new SSLSocketChannel(channel, context.createSSLEngine(), executor, parent);
-       }
-
-       @Override
-       public synchronized boolean connect(final SocketAddress remote) throws IOException {
-               switch (state) {
-               case CLOSED:
-               case CLOSING:
-               case CONNECT_FAILED:
-                       throw new ClosedChannelException();
-               case CONNECTED:
-                       throw new AlreadyConnectedException();
-               case CONNECTING:
-               case CONNECT_RESOLVED:
-               case NEGOTIATING:
-                       throw new ConnectionPendingException();
-               case IDLE:
-                       if (channel.connect(remote)) {
-                               engine.setUseClientMode(true);
-                               engine.beginHandshake();
-                               state = InternalState.NEGOTIATING;
-                       } else
-                               state = InternalState.CONNECTING;
-                       return false;
-               }
-
-               throw new IllegalStateException("Unhandled state " + state);
-       }
-
-       @Override
-       public synchronized boolean finishConnect() throws IOException {
-               logger.trace("Attempting to finish connection in state {}", state);
-
-               switch (state) {
-               case CLOSED:
-               case CLOSING:
-               case CONNECT_FAILED:
-                       throw new ClosedChannelException();
-               case CONNECTED:
-                       return true;
-               case CONNECT_RESOLVED:
-                       if (connectResult != null) {
-                               state = InternalState.CONNECT_FAILED;
-                               try {
-                                       logger.trace("Internal close after failed connect");
-                                       close();
-                               } catch (IOException e) {
-                                       logger.trace("Failed to invoked internal close", e);
-                               }
-                               throw connectResult;
-                       }
-
-                       state = InternalState.CONNECTED;
-                       if (parent != null) {
-                               parent.addNewChannel(this);
-                               parent = null;
-                       }
-                       return true;
-               case CONNECTING:
-               case NEGOTIATING:
-                       return false;
-               case IDLE:
-                       throw new NoConnectionPendingException();
-               }
-
-               throw new IllegalStateException("Unhandled state " + state);
-       }
-
-       @Override
-       public synchronized boolean isConnected() {
-               return state == InternalState.CONNECTED;
-       }
-
-       @Override
-       public synchronized boolean isConnectionPending() {
-               switch (state) {
-               case CONNECTING:
-               case CONNECT_RESOLVED:
-               case NEGOTIATING:
-                       return true;
-               default:
-                       return false;
-               }
-       }
-
-       private int readNetwork() throws IOException {
-               fromNetwork.compact();
-
-               final int ret;
-               try {
-                       ret = channel.read(fromNetwork);
-               } finally {
-                       fromNetwork.flip();
-               }
-
-               logger.trace("Channel {} has input {} after {}", this, fromNetwork.remaining(), ret);
-               return ret;
-       }
-
-       private int writeNetwork() throws IOException {
-               toNetwork.flip();
-
-               final int ret;
-               try {
-                       ret = channel.write(toNetwork);
-               } finally {
-                       toNetwork.compact();
-               }
-
-               logger.trace("Channel {} has output {} after {}", this, toNetwork.remaining(), ret);
-               return ret;
-       }
-
-       private void checkChannelState() throws IOException {
-               switch (state) {
-               case CLOSED:
-               case CLOSING:
-               case CONNECT_FAILED:
-                       throw new ClosedChannelException();
-               case CONNECTED:
-                       break;
-               case CONNECT_RESOLVED:
-               case CONNECTING:
-               case IDLE:
-               case NEGOTIATING:
-                       throw new NotYetConnectedException();
-               }
-       }
-
-       private boolean checkReadState() throws IOException {
-               checkChannelState();
-               return closedInput;
-       }
-
-       @Override
-       public synchronized int read(final ByteBuffer dst) throws IOException {
-               if (checkReadState())
-                       return -1;
-
-               /*
-                * If we have some data overflowed from negotiation, flush that
-                * first.
-                */
-               if (toUser.position() != 0) {
-                       logger.trace("toUser has {}", toUser.position());
-                       toUser.flip();
-
-                       final int xfer = Math.min(toUser.remaining(), dst.remaining());
-                       dst.put(toUser.array(), toUser.arrayOffset() + toUser.position(), xfer);
-                       toUser.position(toUser.position() + xfer);
-                       toUser.compact();
-                       return xfer;
-               }
-
-               // We have input data, unwrap it
-               if (fromNetwork.hasRemaining()) {
-                       final SSLEngineResult res = engine.unwrap(fromNetwork, dst);
-                       return res.bytesProduced();
-               }
-
-               // EOF on underlying stream, inform the engine
-               if (readDone)
-                       engine.closeInbound();
-
-               // SSL engine says there may be some more input
-               if (!engine.isInboundDone())
-                       return 0;
-
-               logger.trace("SSL engine indicates clean shutdown");
-               return -1;
-       }
-
-       @Override
-       public synchronized long read(final ByteBuffer[] dsts, final int offset, final int length) throws IOException {
-               if (checkReadState())
-                       return -1;
-
-               /*
-                * Search for the first buffer with available data and perform
-                * a single-buffer read into it. Not completely efficient, but
-                * does the work required.
-                */
-               for (int i = offset; i < length; ++i)
-                       if (dsts[i].remaining() != 0)
-                               return read(dsts[i]);
-
-               return 0;
-       }
-
-       @Override
-       public Socket socket() {
-               // We do not support this operation, everyone should use Java 7 interfaces
-               throw new UnsupportedOperationException("SSLSocketChannel does not provide a fake Socket implementation");
-       }
-
-       private void checkWriteState() throws IOException {
-               checkChannelState();
-
-               if (closedOutput)
-                       throw new ClosedChannelException();
-
-               if (writeFailed != null)
-                       throw writeFailed;
-       }
-
-       @Override
-       public synchronized int write(final ByteBuffer src) throws IOException {
-               checkWriteState();
-
-               final SSLEngineResult res = engine.wrap(src, toNetwork);
-               return res.bytesConsumed();
-       }
-
-       @Override
-       public synchronized long write(final ByteBuffer[] srcs, final int offset, final int length) throws IOException {
-               checkWriteState();
-
-               final SSLEngineResult res = engine.wrap(srcs, offset, length, toNetwork);
-               return res.bytesConsumed();
-       }
-
-       @Override
-       protected synchronized void implCloseSelectableChannel() throws IOException {
-               logger.trace("Closing channel in state {}", state);
-
-               switch (state) {
-               case CONNECTED:
-                       state = InternalState.CLOSING;
-                       engine.closeOutbound();
-                       break;
-               case CLOSED:
-               case CLOSING:
-                       // Nothing to do
-                       break;
-               case CONNECT_FAILED:
-               case CONNECT_RESOLVED:
-               case CONNECTING:
-               case IDLE:
-               case NEGOTIATING:
-                       state = InternalState.CLOSED;
-                       channel.close();
-                       break;
-               }
-       }
-
-       @Override
-       protected void implConfigureBlocking(final boolean block) throws IOException {
-               channel.configureBlocking(block);
-       }
-
-       @Override
-       public synchronized int computeInterestOps(int userOps) {
-               logger.trace("Interestops in state {} userOps {}", state, userOps);
-
-               int ret = 0;
-
-               switch (state) {
-               case CLOSED:
-               case CONNECT_FAILED:
-               case CONNECT_RESOLVED:
-               case IDLE:
-                       return 0;
-               case CLOSING:
-                       if (engine.isOutboundDone() && toNetwork.position() == 0)
-                               throw new IllegalStateException("Network flush completed, but still in CLOSING state");
-                       return SelectionKey.OP_WRITE;
-               case CONNECTING:
-                       return SelectionKey.OP_CONNECT;
-               case NEGOTIATING:
-                       userOps = 0;
-
-                       final HandshakeStatus st = engine.getHandshakeStatus();
-
-                       logger.trace("SSL Engine status {}", st);
-
-                       switch (st) {
-                       case NEED_UNWRAP:
-                               userOps = SelectionKey.OP_READ;
-                               break;
-                       case NEED_WRAP:
-                               userOps = SelectionKey.OP_WRITE;
-                               break;
-                       default:
-                               logger.trace("Unexpected SSLEngine handshake status {}", st);
-                               connectResult = new IOException("Unexpected SSLEngine handshake status " + st);
-                               connectResult.fillInStackTrace();
-                               state = InternalState.CONNECT_RESOLVED;
-                               return 0;
-                       }
-
-                       // Intentional fall through
-               case CONNECTED:
-                       if ((userOps & SelectionKey.OP_READ) != 0 && !fromNetwork.hasRemaining())
-                               ret |= SelectionKey.OP_READ;
-                       if ((userOps & SelectionKey.OP_WRITE) != 0 && !toNetwork.hasRemaining())
-                               ret |= SelectionKey.OP_WRITE;
-
-                       logger.trace("userOps {} fromNetwork {} toNetwork {} ret {}", userOps, fromNetwork.remaining(), toNetwork.remaining(), ret);
-                       return ret;
-               }
-
-               throw new IllegalStateException("Unhandled state " + state);
-       }
-
-       private void performIO() {
-               logger.trace("IO operations in state {}", state);
-
-               switch (state) {
-               case CLOSED:
-               case CONNECT_RESOLVED:
-               case IDLE:
-                       // Nothing to do
-                       break;
-               case CLOSING:
-                       boolean forceClose = false;
-                       if (!engine.isOutboundDone()) {
-                               try {
-                                       engine.wrap(empty, toNetwork);
-                               } catch (SSLException e) {
-                                       logger.trace("Failed to close down SSL engine outbound", e);
-                               }
-                       }
-
-                       if (toNetwork.position() != 0) {
-                               try {
-                                       writeNetwork();
-                               } catch (IOException e) {
-                                       logger.trace("Failed to flush outstanding buffers, forcing close", e);
-                                       forceClose = true;
-                               }
-                       }
-
-                       if (forceClose || (engine.isOutboundDone() && toNetwork.position() == 0)) {
-                               logger.trace("Completed state flush");
-                               state = InternalState.CLOSED;
-                               try {
-                                       channel.close();
-                               } catch (IOException e) {
-                                       logger.trace("Failed to close slave channel", e);
-                               }
-                       }
-                       break;
-               case CONNECT_FAILED:
-                       try {
-                               logger.trace("Invoking internal close after failure");
-                               close();
-                       } catch (IOException e) {
-                               logger.trace("Internal fail closed", e);
-                       }
-                       break;
-               case CONNECTED:
-                       try {
-                               if (!readDone && readNetwork() < 0) {
-                                       readDone = true;
-                                       try {
-                                               engine.closeInbound();
-                                       } catch (IOException e) {
-                                               logger.trace("TLS reported close error", e);
-                                               closeFailed = e;
-                                       }
-                               }
-                       } catch (IOException e) {
-                               logger.trace("Background read failed", e);
-                               readDone = true;
-                       }
-
-                       try {
-                               if (toNetwork.position() != 0)
-                                       writeNetwork();
-                       } catch (IOException e) {
-                               logger.trace("Background write failed", e);
-                               writeFailed = e;
-                               toNetwork.clear();
-                       }
-                       break;
-               case CONNECTING:
-                       try {
-                               if (channel.finishConnect()) {
-                                       engine.setUseClientMode(true);
-                                       engine.beginHandshake();
-                                       state = InternalState.NEGOTIATING;
-                               }
-                       } catch (IOException e) {
-                               logger.trace("Finished connection with error", e);
-                               connectResult = e;
-                               state = InternalState.CONNECT_RESOLVED;
-                       }
-                       break;
-               case NEGOTIATING:
-                       boolean needMore = true;
-
-                       do {
-                               final HandshakeStatus st = engine.getHandshakeStatus();
-                               if (st == HandshakeStatus.NEED_TASK) {
-                                       // Dispatch any blocking tasks that SSLEngine has for us.
-                                       while (true) {
-                                               final Runnable r = engine.getDelegatedTask();
-                                               if (r == null)
-                                                       break;
-
-                                               executor.execute(r);
-                                       }
-                                       continue;
-                               }
-
-                               try {
-                                       if (readNetwork() < 0) {
-                                               logger.trace("Unexpected end of stream during negotiation");
-                                               connectResult = new EOFException("Unexpected end-of-channel during SSL negotiation");
-                                               connectResult.fillInStackTrace();
-                                               state = InternalState.CONNECT_RESOLVED;
-                                               break;
-                                       }
-                                       writeNetwork();
-                               } catch (IOException e) {
-                                       logger.trace("IO error during SSL negotiation", e);
-                                       connectResult = e;
-                                       state = InternalState.CONNECT_RESOLVED;
-                                       break;
-                               }
-
-                               final SSLEngineResult res;
-                               try {
-                                       logger.trace("Status {} fromNetwork {} toNetwork {} toUser {}", st, fromNetwork.remaining(), toNetwork.remaining(), toUser.remaining());
-
-                                       if (st == HandshakeStatus.NEED_UNWRAP) {
-                                               // SSLEngine needs to read some data from the network
-                                               res = engine.unwrap(fromNetwork, toUser);
-                                               if (res.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW)
-                                                       needMore = false;
-                                       } else if (st == HandshakeStatus.NEED_WRAP) {
-                                               // SSLEngine needs to write some data to the network
-                                               res = engine.wrap(empty, toNetwork);
-                                               if (res.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW)
-                                                       needMore = false;
-                                       } else {
-                                               logger.trace("Unexpected state {} in SSL negotiation", engine.getHandshakeStatus());
-                                               connectResult = new IOException("Unexpected SSL negotiation state");
-                                               connectResult.fillInStackTrace();
-                                               state = InternalState.CONNECT_RESOLVED;
-                                               break;
-                                       }
-                               } catch (SSLException e) {
-                                       logger.trace("SSL negotiation failed", e);
-                                       connectResult = e;
-                                       state = InternalState.CONNECT_RESOLVED;
-                                       break;
-                               }
-
-                               logger.trace("SSL needMore {} result {}", needMore, res);
-
-                               if (res.getHandshakeStatus() == HandshakeStatus.FINISHED) {
-                                       final SSLSession s = engine.getSession();
-                                       logger.trace("SSL session established: {}", s);
-                                       state = InternalState.CONNECT_RESOLVED;
-                                       break;
-                               }
-                       } while (needMore);
-               }
-       }
-
-       @Override
-       public synchronized int computeReadyOps() {
-               performIO();
-
-               logger.trace("Readyops in state {}", state);
-
-               switch (state) {
-               case CLOSED:
-               case CLOSING:
-               case CONNECT_FAILED:
-               case CONNECTING:
-               case IDLE:
-               case NEGOTIATING:
-                       return 0;
-               case CONNECT_RESOLVED:
-                       return SelectionKey.OP_CONNECT;
-               case CONNECTED:
-                       int ret = 0;
-
-                       if (toNetwork.hasRemaining() || writeFailed != null)
-                               ret |= SelectionKey.OP_WRITE;
-                       if (fromNetwork.hasRemaining() || toUser.position() != 0)
-                               ret |= SelectionKey.OP_READ;
-
-                       return ret;
-               }
-
-               throw new IllegalStateException("Unhandled state " + state);
-       }
-
-       @Override
-       public SocketChannel bind(final SocketAddress local) throws IOException {
-               channel.bind(local);
-               return this;
-       }
-
-       @Override
-       public SocketAddress getLocalAddress() throws IOException {
-               return channel.getLocalAddress();
-       }
-
-       @Override
-       public SocketAddress getRemoteAddress() throws IOException {
-               return channel.getRemoteAddress();
-       }
-
-       @Override
-       public synchronized SocketChannel shutdownInput() throws IOException {
-               checkChannelState();
-
-               if (!closedInput) {
-                       closedInput = true;
-                       if (closeFailed != null)
-                               throw closeFailed;
-                       logger.debug("Socket {} input shut down", this);
-               }
-
-               return this;
-       }
-
-       @Override
-       public synchronized SocketChannel shutdownOutput() throws IOException {
-               checkChannelState();
-
-               if (!closedOutput) {
-                       closedOutput = true;
-                       engine.closeOutbound();
-                       logger.debug("Socket {} output shut down", this);
-               }
-
-               return this;
-       }
-
-       @Override
-       public <T> T getOption(SocketOption<T> name) throws IOException {
-               return channel.getOption(name);
-       }
-
-       @Override
-       public <T> SocketChannel setOption(SocketOption<T> name, T value) throws IOException {
-               channel.setOption(name, value);
-               return this;
-       }
-
-       @Override
-       public Set<SocketOption<?>> supportedOptions() {
-               return channel.supportedOptions();
-       }
-
-       synchronized boolean hasParent() {
-               return parent != null;
-       }
-}
-
index 0088b236bb9644dc590e9cba1887ea24c124caeb..123713655e8d85eaa38a9f96902307a865ec0f51 100644 (file)
@@ -10,23 +10,18 @@ package org.opendaylight.protocol.framework;
 import java.io.Closeable;
 
 /**
- * Interface that groups together the classes that can create a session (Dispatcher and Server). When a session
- * is closing, it has to notify its parent about closing. Each parent keeps a Map of its sessions. When some session closes,
- * it fires onSessionClosed event with its own instance as parameter and the parent of this session will remove it from his map.
+ * Interface that groups together the classes that can create a session (Dispatcher and Server). When a session is
+ * closing, it has to notify its parent about closing. Each parent keeps a Map of its sessions. When some session
+ * closes, it fires onSessionClosed event with its own instance as parameter and the parent of this session will remove
+ * it from his map.
  */
 public interface SessionParent extends Closeable {
 
        /**
-        * This listener method is called when a session that was created by a class implementing this interface,
-        * is closing. Implementation should remove corresponding session from its list of sessions.
+        * This listener method is called when a session that was created by a class implementing this interface, is
+        * closing. Implementation should remove corresponding session from its list of sessions.
+        * 
         * @param session a session that is closing
         */
        public void onSessionClosed(final ProtocolSession session);
-
-       /**
-        * This listener method is called when a session has produced some output and the parent needs to react to
-        * it.
-        * @param session a session that has produced output
-        */
-       public void checkOutputBuffer(final ProtocolSession session);
 }
diff --git a/framework/src/main/java/org/opendaylight/protocol/framework/SessionStreams.java b/framework/src/main/java/org/opendaylight/protocol/framework/SessionStreams.java
deleted file mode 100644 (file)
index bb1fd16..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.util.TimerTask;
-
-/**
- * DTO object to be attached to socket channel. Contains session and
- * streams associated with the socket channel.
- */
-final class SessionStreams {
-
-       private final ProtocolInputStream inputStream;
-
-       private final PipedInputStream pipedInputStream;
-
-       private final PipedOutputStream pipedOutputStream;
-
-       private final ProtocolSession session;
-
-       final ProtocolConnection connection;
-       int connectCount = 0;
-       TimerTask timer = null;
-
-       SessionStreams(PipedOutputStream pipedOutputStream,
-                       PipedInputStream pipedInputStream,
-                       ProtocolInputStream inputStream,
-                       ProtocolSession session, ProtocolConnection connection) {
-               this.pipedOutputStream = pipedOutputStream;
-               this.pipedInputStream = pipedInputStream;
-               this.inputStream = inputStream;
-               this.session = session;
-               this.connection = connection;
-       }
-
-       PipedOutputStream getPipedOutputStream() {
-               return this.pipedOutputStream;
-       }
-
-       PipedInputStream getPipedInputStream() {
-               return this.pipedInputStream;
-       }
-
-       ProtocolInputStream getProtocolInputStream() {
-               return this.inputStream;
-       }
-
-       ProtocolSession getSession() {
-               return this.session;
-       }
-}
index 2d6cad8c5f6cbae8843c0a93f5118edae0b8b170..82cc18c6b18693cab6b0ec8d0cacef00264de6e9 100644 (file)
@@ -7,36 +7,12 @@
  */
 package org.opendaylight.protocol.framework;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
 
 import org.junit.Test;
 
 public class ComplementaryTest {
 
-       private class ProtocolMessageImpl implements ProtocolMessage {
-
-               private static final long serialVersionUID = 1L;
-       }
-
-       private class ProtocolMessageFactoryImpl implements ProtocolMessageFactory {
-
-               public ProtocolMessageFactoryImpl() {
-
-               }
-
-               @Override
-               public ProtocolMessage parse(final byte[] bytes,
-                               final ProtocolMessageHeader msgHeader) throws DeserializerException,
-                               DocumentedException {
-                       return null;
-               }
-
-               @Override
-               public byte[] put(final ProtocolMessage msg) {
-                       return new byte[]{ 12, 13 };
-               }
-       }
-
        @Test
        public void testExceptions() {
                final DeserializerException de = new DeserializerException("some error");
@@ -44,30 +20,4 @@ public class ComplementaryTest {
 
                assertEquals(de.getMessage(), ee.getMessage());
        }
-
-       @Test
-       public void testProtocolOutputStream() {
-               final ProtocolOutputStream pos = new ProtocolOutputStream();
-               pos.putMessage(new ProtocolMessageImpl(), new ProtocolMessageFactoryImpl());
-               try {
-                       pos.putMessage(new ProtocolMessageImpl(), new ProtocolMessageFactory() {
-
-                               @Override
-                               public byte[] put(final ProtocolMessage msg) {
-                                       return null;
-                               }
-
-                               @Override
-                               public ProtocolMessage parse(final byte[] bytes, final ProtocolMessageHeader msgHeader)
-                                               throws DeserializerException, DocumentedException {
-                                       return null;
-                               }
-                       });
-                       fail("Exception should have occured.");
-               } catch (final IllegalArgumentException e) {
-                       assertEquals("Message parsed to null.", e.getMessage());
-                       assertEquals(1, pos.getBuffers().size());
-                       assertArrayEquals(new byte[] { 12, 13}, pos.getBuffers().peek().array());
-               }
-       }
 }
index 593d43cbeba8b55318d5c1497334b3fbde361dcd..4e0bf071b781c2d508b6e97f719fac8d89bb8cda 100644 (file)
@@ -14,13 +14,12 @@ import com.google.common.base.Charsets;
 public class MessageFactory implements ProtocolMessageFactory {
 
        @Override
-       public ProtocolMessage parse(byte[] bytes, ProtocolMessageHeader msgHeader)
-                       throws DeserializerException, DocumentedException {
+       public ProtocolMessage parse(final byte[] bytes) throws DeserializerException, DocumentedException {
                return new Message(Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString());
        }
 
        @Override
-       public byte[] put(ProtocolMessage msg) {
-               return ((Message)msg).getMessage().getBytes();
+       public byte[] put(final ProtocolMessage msg) {
+               return ((Message) msg).getMessage().getBytes();
        }
 }
diff --git a/framework/src/test/java/org/opendaylight/protocol/framework/SecureServerTest.java b/framework/src/test/java/org/opendaylight/protocol/framework/SecureServerTest.java
deleted file mode 100644 (file)
index febd21c..0000000
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetSocketAddress;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.util.Random;
-import java.util.Timer;
-import java.util.concurrent.Executors;
-
-import javax.net.ssl.SSLContext;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.protocol.util.SSLUtil;
-
-public class SecureServerTest {
-       static final Random rnd = new Random();
-
-       private static final int MAX_MSGSIZE = 500;
-       final SimpleSessionListener pce = new SimpleSessionListener();
-       ProtocolSession session;
-       ProtocolServer server;
-       DispatcherImpl dispatcher;
-       SSLContext context;
-       int port;
-
-       @Before
-       public void setUp() throws Exception {
-               final InputStream keyStore = SecureServerTest.class.getResourceAsStream("/keystore.jks");
-               final InputStream trustStore = SecureServerTest.class.getResourceAsStream("/keystore.jks");
-               this.context = SSLUtil.initializeSecureContext("keystore", keyStore, trustStore, "SunX509");
-               keyStore.close();
-               trustStore.close();
-
-               this.dispatcher = new DispatcherImpl(Executors.defaultThreadFactory());
-               this.port = rnd.nextInt(10000) + 20000;
-       }
-
-       @After
-       public void tearDown() throws IOException {
-               this.dispatcher.onSessionClosed(this.session);
-               this.server.close();
-               this.dispatcher.stop();
-               try {
-                       Thread.sleep(100);
-               } catch (final InterruptedException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       @Test
-       public void testServerConnection() throws Exception {
-
-               this.server = this.dispatcher.createServer(new InetSocketAddress("127.0.0.3", this.port), new ProtocolConnectionFactory() {
-                       @Override
-                       public ProtocolConnection createProtocolConnection(final InetSocketAddress address) {
-                               return new ProtocolConnection() {
-                                       @Override
-                                       public SessionPreferencesChecker getProposalChecker() {
-                                               return new SimpleSessionProposalChecker();
-                                       }
-
-                                       @Override
-                                       public SessionPreferences getProposal() {
-                                               return new SimpleSessionPreferences();
-                                       }
-
-                                       @Override
-                                       public InetSocketAddress getPeerAddress() {
-                                               return address;
-                                       }
-
-                                       @Override
-                                       public SessionListener getListener() {
-                                               return new SimpleSessionListener();
-                                       }
-                               };
-                       }
-               }, new SimpleSessionFactory(MAX_MSGSIZE), SimpleInputStream.FACTORY, this.context);
-
-               try {
-                       this.server = this.dispatcher.createServer(new InetSocketAddress("127.0.0.3", this.port), null, null, null, null);
-                       fail("Exception should have occured.");
-               } catch (final IllegalStateException e) {
-                       assertTrue(e.getMessage().startsWith("Server with this address:") && e.getMessage().endsWith("was already created."));
-               }
-
-               this.session = this.dispatcher.createClient(new ProtocolConnection() {
-                       @Override
-                       public SessionPreferencesChecker getProposalChecker() {
-                               return new SimpleSessionProposalChecker();
-                       }
-
-                       @Override
-                       public SessionPreferences getProposal() {
-                               return new SimpleSessionPreferences();
-                       }
-
-                       @Override
-                       public InetSocketAddress getPeerAddress() {
-                               return new InetSocketAddress("127.0.0.3", SecureServerTest.this.port);
-                       }
-
-                       @Override
-                       public SessionListener getListener() {
-                               return SecureServerTest.this.pce;
-                       }
-               }, new SimpleSessionFactory(MAX_MSGSIZE), SimpleInputStream.FACTORY, this.context);
-
-               try {
-                       this.session = this.dispatcher.createClient(new ProtocolConnection() {
-                               @Override
-                               public SessionPreferencesChecker getProposalChecker() {
-                                       return new SimpleSessionProposalChecker();
-                               }
-
-                               @Override
-                               public SessionPreferences getProposal() {
-                                       return new SimpleSessionPreferences();
-                               }
-
-                               @Override
-                               public InetSocketAddress getPeerAddress() {
-                                       return new InetSocketAddress("127.0.0.3", SecureServerTest.this.port);
-                               }
-
-                               @Override
-                               public SessionListener getListener() {
-                                       return SecureServerTest.this.pce;
-                               }
-                       }, null, null, null);
-                       fail("Exception should have occured.");
-               } catch (final IllegalStateException e) {
-                       assertTrue(e.getMessage().startsWith("Attempt to create duplicate client session to the same address:"));
-               }
-
-               synchronized (this.pce) {
-                       while (!this.pce.up)
-                               this.pce.wait();
-               }
-       }
-
-       @Test
-       public void testIO() throws IOException, InterruptedException, KeyManagementException, UnrecoverableKeyException,
-                       NoSuchAlgorithmException, KeyStoreException, CertificateException {
-               this.server = this.dispatcher.createServer(new InetSocketAddress("127.0.0.3", this.port), new ProtocolConnectionFactory() {
-                       @Override
-                       public ProtocolConnection createProtocolConnection(final InetSocketAddress address) {
-                               return new ProtocolConnection() {
-
-                                       @Override
-                                       public SessionPreferencesChecker getProposalChecker() {
-                                               return new SimpleSessionProposalChecker();
-                                       }
-
-                                       @Override
-                                       public SessionPreferences getProposal() {
-                                               return new SimpleSessionPreferences();
-                                       }
-
-                                       @Override
-                                       public InetSocketAddress getPeerAddress() {
-                                               return address;
-                                       }
-
-                                       @Override
-                                       public SessionListener getListener() {
-                                               return new SimpleSessionListener();
-                                       }
-                               };
-                       }
-               }, new ProtocolSessionFactory() {
-                       @Override
-                       public ProtocolSession getProtocolSession(final SessionParent parent, final Timer timer, final ProtocolConnection connection,
-                                       final int sessionId) {
-                               return new Session(parent, MAX_MSGSIZE);
-                       }
-               }, SimpleInputStream.FACTORY, this.context);
-
-               this.session = this.dispatcher.createClient(new ProtocolConnection() {
-                       @Override
-                       public SessionPreferencesChecker getProposalChecker() {
-                               return new SimpleSessionProposalChecker();
-                       }
-
-                       @Override
-                       public SessionPreferences getProposal() {
-                               return new SimpleSessionPreferences();
-                       }
-
-                       @Override
-                       public InetSocketAddress getPeerAddress() {
-                               return new InetSocketAddress("127.0.0.3", SecureServerTest.this.port);
-                       }
-
-                       @Override
-                       public SessionListener getListener() {
-                               return new SimpleSessionListener();
-                       }
-               }, new ProtocolSessionFactory() {
-                       @Override
-                       public ProtocolSession getProtocolSession(final SessionParent parent, final Timer timer, final ProtocolConnection connection,
-                                       final int sessionId) {
-                               return new Session(parent, MAX_MSGSIZE);
-                       }
-               }, SimpleInputStream.FACTORY, this.context);
-       }
-
-}
index 4780e9cec3ff7c4363f8fcdeb3d9c2f79230611f..77b9e0569c2b14c802288a554e6ba0e75bb66da1 100644 (file)
@@ -7,11 +7,14 @@
  */
 package org.opendaylight.protocol.framework;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 import java.io.IOException;
+import java.net.ConnectException;
 import java.net.InetSocketAddress;
-import java.util.concurrent.Executors;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
 
 import org.junit.After;
 import org.junit.Test;
@@ -30,9 +33,11 @@ public class ServerTest {
 
        @Test
        public void testConnectionEstablished() throws Exception {
-               this.dispatcher = new DispatcherImpl(Executors.defaultThreadFactory());
+               this.dispatcher = new DispatcherImpl(new MessageFactory());
 
-               this.server = this.dispatcher.createServer(new InetSocketAddress("127.0.0.3", PORT), new ProtocolConnectionFactory() {
+               final InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.3", PORT);
+
+               this.server = this.dispatcher.createServer(serverAddress, new ProtocolConnectionFactory() {
                        @Override
                        public ProtocolConnection createProtocolConnection(final InetSocketAddress address) {
 
@@ -58,16 +63,9 @@ public class ServerTest {
                                        }
                                };
                        }
-               }, new SimpleSessionFactory(MAX_MSGSIZE), SimpleInputStream.FACTORY);
+               }, new SimpleSessionFactory(MAX_MSGSIZE));
 
-               try {
-                       this.server = this.dispatcher.createServer(new InetSocketAddress("127.0.0.3", PORT), null, null, null);
-                       fail("Exception should have occured.");
-               } catch (final IllegalStateException e) {
-                       assertTrue(e.getMessage().startsWith("Server with this address:") && e.getMessage().endsWith("was already created."));
-               }
-               
-               this.clientDispatcher = new DispatcherImpl(Executors.defaultThreadFactory());
+               this.clientDispatcher = new DispatcherImpl(new MessageFactory());
 
                this.session = this.clientDispatcher.createClient(new ProtocolConnection() {
                        @Override
@@ -89,7 +87,7 @@ public class ServerTest {
                        public SessionListener getListener() {
                                return ServerTest.this.pce;
                        }
-               }, new SimpleSessionFactory(MAX_MSGSIZE), SimpleInputStream.FACTORY);
+               }, new SimpleSessionFactory(MAX_MSGSIZE)).get();
 
                final int maxAttempts = 1000;
                int attempts = 0;
@@ -102,11 +100,12 @@ public class ServerTest {
        }
 
        @Test
-       public void testConnectionFailed() throws IOException, InterruptedException {
-               this.dispatcher = new DispatcherImpl(Executors.defaultThreadFactory());
-               this.clientDispatcher = new DispatcherImpl(Executors.defaultThreadFactory());
+       public void testConnectionFailed() throws IOException, InterruptedException, ExecutionException {
+               this.dispatcher = new DispatcherImpl(new MessageFactory());
+               this.clientDispatcher = new DispatcherImpl(new MessageFactory());
+               final SimpleSessionListener listener = new SimpleSessionListener();
 
-               this.session = this.clientDispatcher.createClient(new ProtocolConnection() {
+               final Future<ProtocolSession> session = this.clientDispatcher.createClient(new ProtocolConnection() {
                        @Override
                        public SessionPreferencesChecker getProposalChecker() {
                                return new SimpleSessionProposalChecker();
@@ -119,22 +118,29 @@ public class ServerTest {
 
                        @Override
                        public InetSocketAddress getPeerAddress() {
-                               return new InetSocketAddress("127.0.0.3", PORT);
+                               return new InetSocketAddress("127.0.0.5", PORT);
                        }
 
                        @Override
                        public SessionListener getListener() {
-                               return ServerTest.this.pce;
+                               return listener;
                        }
-               }, new SimpleSessionFactory(MAX_MSGSIZE), SimpleInputStream.FACTORY);
-               final int maxAttempts = 1000;
+               }, new SimpleSessionFactory(MAX_MSGSIZE));
+               try {
+                       session.get();
+                       fail("Exception should have occurred.");
+               } catch (final ExecutionException e) {
+                       listener.failed = true;
+                       assertTrue(e.getCause() instanceof ConnectException);
+               }
+               final int maxAttempts = 100;
                int attempts = 0;
-               synchronized (this.pce) {
-                       while (!this.pce.failed && ++attempts < maxAttempts) {
-                               this.pce.wait(100);
+               synchronized (listener) {
+                       while (!listener.failed && ++attempts < maxAttempts) {
+                               listener.wait(100);
                        }
                }
-               assertTrue(this.pce.failed);
+               assertTrue(listener.failed);
        }
 
        @After
@@ -142,8 +148,8 @@ public class ServerTest {
                this.dispatcher.onSessionClosed(this.session);
                if (this.server != null)
                        this.server.close();
-               this.dispatcher.stop();
-               this.clientDispatcher.stop();
+               // this.dispatcher.stop();
+               // this.clientDispatcher.stop();
                try {
                        Thread.sleep(100);
                } catch (final InterruptedException e) {
index 0591f0e05c10d5fac5820565efb43cf118f6e057..94e4d0640328b9259f801be32e91a8d329c2de90 100644 (file)
@@ -19,8 +19,6 @@ public class Session implements ProtocolSession {
 
        private static final Logger logger = LoggerFactory.getLogger(Session.class);
 
-       private final ProtocolOutputStream pos;
-
        public final List<ProtocolMessage> msgs = Lists.newArrayList();
 
        private final ProtocolMessageFactory pmf = new MessageFactory();
@@ -32,7 +30,6 @@ public class Session implements ProtocolSession {
        private final int maxMsgSize;
 
        public Session(final SessionParent parent, final int maxMsgSize) {
-               this.pos = new ProtocolOutputStream();
                this.parent = parent;
                this.maxMsgSize = maxMsgSize;
        }
@@ -44,30 +41,24 @@ public class Session implements ProtocolSession {
 
        @Override
        public void startSession() {
-               this.pos.putMessage(new Message("hello"), this.pmf);
-               this.parent.checkOutputBuffer(this);
-       }
-
-       @Override
-       public ProtocolOutputStream getStream() {
-               return this.pos;
+               // this.pos.putMessage(new Message("hello"), this.pmf);
        }
 
        @Override
-       public void handleMessage(ProtocolMessage msg) {
-               logger.debug("Message received: {}", ((Message)msg).getMessage());
+       public void handleMessage(final ProtocolMessage msg) {
+               logger.debug("Message received: {}", ((Message) msg).getMessage());
                this.up = true;
                this.msgs.add(msg);
                logger.debug(this.msgs.size() + "");
        }
 
        @Override
-       public void handleMalformedMessage(DeserializerException e) {
+       public void handleMalformedMessage(final DeserializerException e) {
                logger.debug("Malformed message: {}", e.getMessage(), e);
        }
 
        @Override
-       public void handleMalformedMessage(DocumentedException e) {
+       public void handleMalformedMessage(final DocumentedException e) {
                logger.debug("Malformed message: {}", e.getMessage(), e);
        }
 
@@ -82,12 +73,12 @@ public class Session implements ProtocolSession {
        }
 
        @Override
-       public void onConnectionFailed(IOException e) {
+       public void onConnectionFailed(final IOException e) {
                logger.debug("Connection failed: {}", e.getMessage(), e);
        }
 
        @Override
        public int maximumMessageSize() {
-               return maxMsgSize;
+               return this.maxMsgSize;
        }
 }
diff --git a/framework/src/test/java/org/opendaylight/protocol/framework/SimpleInputStream.java b/framework/src/test/java/org/opendaylight/protocol/framework/SimpleInputStream.java
deleted file mode 100644 (file)
index e06ea49..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-import java.io.IOException;
-import java.io.PipedInputStream;
-
-public class SimpleInputStream implements ProtocolInputStream {
-       public static final ProtocolInputStreamFactory FACTORY = new ProtocolInputStreamFactory() {
-               @Override
-               public ProtocolInputStream getProtocolInputStream(final PipedInputStream pis, final ProtocolMessageFactory pmf) {
-                       return new SimpleInputStream();
-               }
-       };
-
-       private SimpleInputStream() {
-       }
-
-       @Override
-       public boolean isMessageAvailable() throws IOException {
-               return true;
-       }
-
-       @Override
-       public ProtocolMessage getMessage() throws DeserializerException, IOException, DocumentedException {
-               return null;
-       }
-}
diff --git a/framework/src/test/java/org/opendaylight/protocol/framework/SimpleMessageFactory.java b/framework/src/test/java/org/opendaylight/protocol/framework/SimpleMessageFactory.java
deleted file mode 100644 (file)
index d25f566..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.framework;
-
-public class SimpleMessageFactory implements ProtocolMessageFactory {
-
-       @Override
-       public ProtocolMessage parse(byte[] bytes, ProtocolMessageHeader msgHeader)
-                       throws DeserializerException, DocumentedException {
-               return null;
-       }
-
-       @Override
-       public byte[] put(ProtocolMessage msg) {
-               return null;
-       }
-}
index 49fb5de9b589ca7c7615a8f183f0006a540dc4e6..7ecb0f4591219c60accaf640ae6d3025e84932e5 100644 (file)
@@ -17,7 +17,7 @@ public final class SimpleSession implements ProtocolSession {
 
        private final int maxMsgSize;
 
-       public SimpleSession(ProtocolConnection connection, SessionParent d, int maxMsgSize) {
+       public SimpleSession(final ProtocolConnection connection, final SessionParent d, final int maxMsgSize) {
                this.listener = connection.getListener();
                this.d = d;
                this.maxMsgSize = maxMsgSize;
@@ -30,24 +30,19 @@ public final class SimpleSession implements ProtocolSession {
 
        @Override
        public void startSession() {
-               ((SimpleSessionListener)this.listener).onSessionUp(this, null, null);
+               ((SimpleSessionListener) this.listener).onSessionUp(this, null, null);
        }
 
        @Override
-       public ProtocolOutputStream getStream() {
-               return null;
-       }
-
-       @Override
-       public void handleMessage(ProtocolMessage msg) {
+       public void handleMessage(final ProtocolMessage msg) {
        }
 
        @Override
-       public void handleMalformedMessage(DeserializerException e) {
+       public void handleMalformedMessage(final DeserializerException e) {
        }
 
        @Override
-       public void handleMalformedMessage(DocumentedException e) {
+       public void handleMalformedMessage(final DocumentedException e) {
        }
 
        @Override
@@ -60,12 +55,12 @@ public final class SimpleSession implements ProtocolSession {
        }
 
        @Override
-       public void onConnectionFailed(IOException e) {
-               ((SimpleSessionListener)this.listener).onConnectionFailed(this, e);
+       public void onConnectionFailed(final IOException e) {
+               ((SimpleSessionListener) this.listener).onConnectionFailed(this, e);
        }
 
        @Override
        public int maximumMessageSize() {
-               return maxMsgSize;
+               return this.maxMsgSize;
        }
 }
index f982677cabc26fe62cf367f206b162ed217d9732..7d7f5fa692845f44e4d3354e3773c962da0e7278 100644 (file)
@@ -7,17 +7,20 @@
  */
 package org.opendaylight.protocol.framework;
 
+import io.netty.channel.ChannelHandlerContext;
+
 import java.util.Timer;
 
 public final class SimpleSessionFactory implements ProtocolSessionFactory {
        private final int maximumMessageSize;
 
-       public SimpleSessionFactory(int maximumMessageSize) {
+       public SimpleSessionFactory(final int maximumMessageSize) {
                this.maximumMessageSize = maximumMessageSize;
        }
 
        @Override
-       public ProtocolSession getProtocolSession(SessionParent parent, Timer timer, ProtocolConnection connection, int sessionId) {
-               return new SimpleSession(connection, parent, maximumMessageSize);
+       public ProtocolSession getProtocolSession(final SessionParent parent, final Timer timer, final ProtocolConnection connection,
+                       final int sessionId, final ChannelHandlerContext ctx) {
+               return new SimpleSession(connection, parent, this.maximumMessageSize);
        }
 }
index c6c8499f3703f81d0f686b28ce2f1e81f03ed3ae..a3d9b16912e1d7247fd3ffeab5df6bf4563a8564 100644 (file)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.protocol.pcep;
 
+import io.netty.channel.ChannelHandlerContext;
+
 import java.util.Timer;
 
 import org.opendaylight.protocol.framework.ProtocolConnection;
@@ -16,5 +18,6 @@ import org.opendaylight.protocol.framework.SessionParent;
 
 public interface PCEPSessionFactory extends ProtocolSessionFactory {
        @Override
-       public ProtocolSession getProtocolSession(SessionParent parent, Timer timer, ProtocolConnection connection, int sessionId);
+       public ProtocolSession getProtocolSession(SessionParent parent, Timer timer, ProtocolConnection connection, int sessionId,
+                       ChannelHandlerContext ctx);
 }
index 86405e82c0163e0c4f83e3e48d3017e2665bda13..f8178f9848ef6e5aa05708637062cecabe6f1fd5 100644 (file)
@@ -98,6 +98,8 @@
                                                        org.opendaylight.protocol.pcep.tlv,
                             org.opendaylight.protocol.util,
                                                        org.slf4j,
+                                                       io.netty.channel, 
+                                                       io.netty.util.concurrent,
                                                </Import-Package>
                                                <Export-Package>
                                                        org.opendaylight.protocol.pcep.impl.*,
index 7f130bb3929256fdb15464ff262b1756b4271f3e..7cc5ab9e5d295c02aca4117264cd928cd1ab435a 100644 (file)
@@ -43,8 +43,7 @@ public class PCEPDispatcherImpl implements PCEPDispatcher {
        @Override
        public ProtocolServer createServer(final InetSocketAddress address, final PCEPConnectionFactory connectionFactory) throws IOException {
                connectionFactory.setProposal(this.proposalFactory, address, 0);
-               return this.dispatcher.createServer(address, connectionFactory, new PCEPSessionFactoryImpl(this.maxUnknownMessages),
-                               PCEPInputStream.FACTORY);
+               return this.dispatcher.createServer(address, connectionFactory, new PCEPSessionFactoryImpl(this.maxUnknownMessages));
        }
 
        /**
@@ -52,8 +51,7 @@ public class PCEPDispatcherImpl implements PCEPDispatcher {
         */
        @Override
        public PCEPSession createClient(final PCEPConnection connection) throws IOException {
-               return (PCEPSession) this.dispatcher.createClient(connection, new PCEPSessionFactoryImpl(this.maxUnknownMessages),
-                               PCEPInputStream.FACTORY);
+               return (PCEPSession) this.dispatcher.createClient(connection, new PCEPSessionFactoryImpl(this.maxUnknownMessages));
        }
 
        @Override
diff --git a/pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPInputStream.java b/pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPInputStream.java
deleted file mode 100644 (file)
index 0cb56d7..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.pcep.impl;
-
-import java.io.IOException;
-import java.io.PipedInputStream;
-
-import org.opendaylight.protocol.framework.DeserializerException;
-import org.opendaylight.protocol.framework.DocumentedException;
-import org.opendaylight.protocol.framework.ProtocolInputStream;
-import org.opendaylight.protocol.framework.ProtocolInputStreamFactory;
-import org.opendaylight.protocol.framework.ProtocolMessage;
-import org.opendaylight.protocol.framework.ProtocolMessageFactory;
-
-/**
- *
- */
-public class PCEPInputStream implements ProtocolInputStream {
-       static final ProtocolInputStreamFactory FACTORY = new ProtocolInputStreamFactory() {
-               @Override
-               public ProtocolInputStream getProtocolInputStream(final PipedInputStream pis, final ProtocolMessageFactory pmf) {
-                       return new PCEPInputStream(pis, pmf);
-               }
-       };
-
-       private final ProtocolMessageFactory factory;
-       private final PipedInputStream inputStream;
-       private PCEPMessageHeader header;
-
-       public PCEPInputStream(final PipedInputStream inputStream, final ProtocolMessageFactory factory) {
-               this.factory = factory;
-               this.inputStream = inputStream;
-               this.header = new PCEPMessageHeader();
-       }
-
-       /**
-        * Check availability of a message in underlying input stream. A message is available when there are more or the
-        * same amount of bytes in the stream as the message length is specified in message header. If there are not enough
-        * bytes for the message or even to read a message header, return false.
-        *
-        * @return true if there are enough bytes to read a message false if there are not enough bytes to read a message or
-        *         a message header.
-        * @throws IOException
-        */
-       @Override
-       public synchronized boolean isMessageAvailable() throws IOException {
-               if (!this.header.isParsed()) {
-                       // No header, try to parse it
-                       this.header = this.parseHeaderIfAvailable();
-
-                       if (!this.header.isParsed()) {
-                               // No luck, we do not have a message
-                               return false;
-                       }
-               }
-               // message length contains the size of the header too
-               if (this.inputStream.available() < (this.header.getLength() - PCEPMessageHeader.COMMON_HEADER_LENGTH)) {
-                       return false;
-               }
-               return true;
-       }
-
-       /**
-        * If there are enough bytes in the underlying stream, parse the message. Blocking, till there are enough bytes to
-        * read, therefore the call of method isMessageAvailable() is suggested first.
-        *
-        * @param factory protocol specific message factory
-        * @return protocol specific message
-        * @throws DeserializerException
-        * @throws IOException
-        * @throws DocumentedException
-        */
-       @Override
-       public synchronized ProtocolMessage getMessage() throws DeserializerException, IOException, DocumentedException {
-               // isMessageAvailable wasn't called, or there were not enough bytes to form message header
-               // blocking till the header is available
-               while (!this.header.isParsed()) {
-                       this.header = this.parseHeaderIfAvailable();
-               }
-               final byte[] bytes = new byte[this.header.getLength() - PCEPMessageHeader.COMMON_HEADER_LENGTH]; // message
-                                                                                                                                                                                                                       // length
-                                                                                                                                                                                                                       // contains
-                                                                                                                                                                                                                       // the size
-                                                                                                                                                                                                                       // of the
-                                                                                                                                                                                                                       // header
-                                                                                                                                                                                                                       // too
-               // blocking till the whole message is available
-               if (this.inputStream.read(bytes) == -1) {
-                       throw new IOException("PipedInputStream was closed, before data could be read from it.");
-               }
-               final ProtocolMessage msg = this.factory.parse(bytes, this.header);
-
-               this.header.setParsed(); // if we have all the bytes to send the message for parsing, clear the header, to let know,
-                                                               // we're ready to read another message
-
-               return msg;
-       }
-
-       /**
-        * Checks if there are enough bytes to parse a header and parses it. Non-blocking: if there are not enough bytes to
-        * parse a message header, returns false.
-        *
-        * @return cleared header if no header is available
-        * @return header object when enough data is available
-        */
-       private PCEPMessageHeader parseHeaderIfAvailable() throws IOException {
-               if (this.inputStream.available() < PCEPMessageHeader.COMMON_HEADER_LENGTH) {
-                       this.header.setParsed();
-                       return this.header;
-               }
-
-               final byte[] messageHeader = new byte[PCEPMessageHeader.COMMON_HEADER_LENGTH];
-               if (this.inputStream.read(messageHeader) == -1) {
-                       this.header.setParsed();
-                       return this.header;
-               }
-               return this.header.fromBytes(messageHeader);
-       }
-}
index f77b9704ecfc7bab3a1220a04bb852ff02cd35ae..788e982fe646305311eb5cdf6682d127e765a8fe 100644 (file)
@@ -9,15 +9,10 @@ package org.opendaylight.protocol.pcep.impl;
 
 import java.util.HashMap;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.opendaylight.protocol.framework.DeserializerException;
 import org.opendaylight.protocol.framework.DocumentedException;
 import org.opendaylight.protocol.framework.ProtocolMessage;
 import org.opendaylight.protocol.framework.ProtocolMessageFactory;
-import org.opendaylight.protocol.framework.ProtocolMessageHeader;
-import org.opendaylight.protocol.util.ByteArray;
 import org.opendaylight.protocol.pcep.PCEPDeserializerException;
 import org.opendaylight.protocol.pcep.PCEPDocumentedException;
 import org.opendaylight.protocol.pcep.PCEPErrors;
@@ -47,98 +42,110 @@ import org.opendaylight.protocol.pcep.message.PCEPRequestMessage;
 import org.opendaylight.protocol.pcep.message.PCEPUpdateRequestMessage;
 import org.opendaylight.protocol.pcep.message.PCEPXRAddTunnelMessage;
 import org.opendaylight.protocol.pcep.message.PCEPXRDeleteTunnelMessage;
+import org.opendaylight.protocol.util.ByteArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.primitives.UnsignedBytes;
 
 /**
  * Factory for subclasses of {@link org.opendaylight.protocol.pcep.PCEPMessage PCEPMessage}
  */
 public class PCEPMessageFactory implements ProtocolMessageFactory {
 
-    private final static Logger logger = LoggerFactory.getLogger(PCEPMessageFactory.class);
+       private final static Logger logger = LoggerFactory.getLogger(PCEPMessageFactory.class);
+
+       private final static int TYPE_SIZE = 1; // bytes
 
-    /**
-     * Type identifier for {@link org.opendaylight.protocol.pcep.PCEPMessage PCEPMessage}
-     */
-    public enum PCEPMessageType {
+       private final static int LENGTH_SIZE = 2; // bytes
+
+       public final static int COMMON_HEADER_LENGTH = 4; // bytes
+
+       /**
+        * Type identifier for {@link org.opendaylight.protocol.pcep.PCEPMessage PCEPMessage}
+        */
+       public enum PCEPMessageType {
                OPEN(1), NOTIFICATION(5), KEEPALIVE(2), RESPONSE(4), REQUEST(3), ERROR(6), CLOSE(7), UPDATE_REQUEST(11), STATUS_REPORT(10),
                // TODO: replace with actual values by IANA
-               XR_ADD_TUNNEL(8),
-               XR_DELETE_TUNNEL(9),
-               PCCREATE(12);
+               XR_ADD_TUNNEL(8), XR_DELETE_TUNNEL(9), PCCREATE(12);
 
                private final int identifier;
 
                PCEPMessageType(final int identifier) {
-                   this.identifier = identifier;
+                       this.identifier = identifier;
                }
 
                public int getIdentifier() {
-                   return this.identifier;
+                       return this.identifier;
                }
 
                public static PCEPMessageType getFromInt(final int type) throws PCEPDeserializerException {
 
-                   for (final PCEPMessageType type_e : PCEPMessageType.values()) {
-                       if (type_e.getIdentifier() == type)
-                           return type_e;
-                   }
+                       for (final PCEPMessageType type_e : PCEPMessageType.values()) {
+                               if (type_e.getIdentifier() == type)
+                                       return type_e;
+                       }
 
-                   throw new PCEPDeserializerException("Unknown PCEPMessage Class identifier. Passed: " + type + "; Known: " + PCEPMessageType.values() + ".");
+                       throw new PCEPDeserializerException("Unknown PCEPMessage Class identifier. Passed: " + type + "; Known: "
+                                       + PCEPMessageType.values() + ".");
                }
        }
 
-    private static class MapOfParsers extends HashMap<PCEPMessageType, PCEPMessageParser> {
+       private static class MapOfParsers extends HashMap<PCEPMessageType, PCEPMessageParser> {
 
-       private static final long serialVersionUID = -5715193806554448822L;
+               private static final long serialVersionUID = -5715193806554448822L;
 
-       private final static MapOfParsers instance = new MapOfParsers();
+               private final static MapOfParsers instance = new MapOfParsers();
 
-       private MapOfParsers() {
-           this.fillInMap();
-       }
+               private MapOfParsers() {
+                       this.fillInMap();
+               }
 
-       private void fillInMap() {
-           this.put(PCEPMessageType.OPEN, new PCEPOpenMessageParser());
-           this.put(PCEPMessageType.KEEPALIVE, new PCEPKeepAliveMessageParser());
-           this.put(PCEPMessageType.NOTIFICATION, new PCEPNotificationMessageParser());
-           this.put(PCEPMessageType.ERROR, new PCEPErrorMessageParser());
-           this.put(PCEPMessageType.RESPONSE, new PCEPReplyMessageParser());
-           this.put(PCEPMessageType.REQUEST, new PCEPRequestMessageParser());
-           this.put(PCEPMessageType.UPDATE_REQUEST, new PCEPUpdateRequestMessageParser());
-           this.put(PCEPMessageType.STATUS_REPORT, new PCEPReportMessageParser());
-           this.put(PCEPMessageType.CLOSE, new PCEPCloseMessageParser());
-           this.put(PCEPMessageType.XR_ADD_TUNNEL, new PCEPXRAddTunnelMessageParser());
-           this.put(PCEPMessageType.XR_DELETE_TUNNEL, new PCEPXRDeleteTunnelMessageParser());
-           this.put(PCEPMessageType.PCCREATE, new PCCreateMessageParser());
-       }
+               private void fillInMap() {
+                       this.put(PCEPMessageType.OPEN, new PCEPOpenMessageParser());
+                       this.put(PCEPMessageType.KEEPALIVE, new PCEPKeepAliveMessageParser());
+                       this.put(PCEPMessageType.NOTIFICATION, new PCEPNotificationMessageParser());
+                       this.put(PCEPMessageType.ERROR, new PCEPErrorMessageParser());
+                       this.put(PCEPMessageType.RESPONSE, new PCEPReplyMessageParser());
+                       this.put(PCEPMessageType.REQUEST, new PCEPRequestMessageParser());
+                       this.put(PCEPMessageType.UPDATE_REQUEST, new PCEPUpdateRequestMessageParser());
+                       this.put(PCEPMessageType.STATUS_REPORT, new PCEPReportMessageParser());
+                       this.put(PCEPMessageType.CLOSE, new PCEPCloseMessageParser());
+                       this.put(PCEPMessageType.XR_ADD_TUNNEL, new PCEPXRAddTunnelMessageParser());
+                       this.put(PCEPMessageType.XR_DELETE_TUNNEL, new PCEPXRDeleteTunnelMessageParser());
+                       this.put(PCEPMessageType.PCCREATE, new PCCreateMessageParser());
+               }
 
-       public static MapOfParsers getInstance() {
-           return instance;
+               public static MapOfParsers getInstance() {
+                       return instance;
                }
-    }
-
-    /**
-     *
-     * @param bytes
-     *            assume array of bytes without common header
-     * @param msgHeader
-     * @return Parsed specific PCEPMessage
-     * @throws PCEPDeserializerException
-     * @throws PCEPDocumentedException
-     */
-
-    @Override
-       public ProtocolMessage parse(final byte[] bytes, final ProtocolMessageHeader msgH) throws DeserializerException, DocumentedException {
-       final PCEPMessageHeader msgHeader = (PCEPMessageHeader) msgH;
+       }
+
+       /**
+        * 
+        * @param bytes assume array of bytes without common header
+        * @param msgHeader
+        * @return Parsed specific PCEPMessage
+        * @throws PCEPDeserializerException
+        * @throws PCEPDocumentedException
+        */
+
+       @Override
+       public ProtocolMessage parse(final byte[] bytes) throws DeserializerException, DocumentedException {
                if (bytes == null)
-                   throw new IllegalArgumentException("Array of bytes is mandatory.");
-               if (msgHeader == null)
-                   throw new IllegalArgumentException("PCEPMessageHeader is mandatory.");
+                       throw new IllegalArgumentException("Array of bytes is mandatory.");
 
                logger.trace("Attempt to parse message from bytes: {}", ByteArray.bytesToHexString(bytes));
 
-               if (bytes.length != (msgHeader.getLength() - PCEPMessageHeader.COMMON_HEADER_LENGTH))
-                   throw new DeserializerException("Size don't match size specified in header. Passed: " + bytes.length + "; Expected: "
-                           + (msgHeader.getLength() - PCEPMessageHeader.COMMON_HEADER_LENGTH) + ". " + msgHeader.getLength());
+               final int type = UnsignedBytes.toInt(bytes[0]);
+
+               final int msgLength = ByteArray.bytesToInt(ByteArray.subByte(bytes, TYPE_SIZE, LENGTH_SIZE));
+
+               final byte[] msgBody = ByteArray.cutBytes(bytes, TYPE_SIZE + LENGTH_SIZE);
+
+               if (msgBody.length != (msgLength - COMMON_HEADER_LENGTH))
+                       throw new DeserializerException("Size don't match size specified in header. Passed: " + msgBody.length + "; Expected: "
+                                       + (msgLength - COMMON_HEADER_LENGTH) + ". " + msgLength);
 
                /*
                 * if PCEPObjectIdentifier.getObjectClassFromInt() dont't throws
@@ -146,16 +153,16 @@ public class PCEPMessageFactory implements ProtocolMessageFactory {
                 */
                PCEPMessageType msgType;
                try {
-                       msgType = PCEPMessageType.getFromInt(msgHeader.getType());
+                       msgType = PCEPMessageType.getFromInt(type);
                } catch (final PCEPDeserializerException e) {
                        throw new DeserializerException(e.getMessage(), e);
                }
                if (msgType == null)
-                   throw new DocumentedException("Unhandled message type " + msgHeader.getType(), new PCEPDocumentedException("Unhandled message type " + msgHeader.getType(), PCEPErrors.CAPABILITY_NOT_SUPPORTED));
+                       throw new DocumentedException("Unhandled message type " + type, new PCEPDocumentedException("Unhandled message type " + type, PCEPErrors.CAPABILITY_NOT_SUPPORTED));
 
                PCEPMessage msg;
                try {
-                       msg = new PCEPRawMessage(PCEPObjectFactory.parseObjects(bytes), msgType);
+                       msg = new PCEPRawMessage(PCEPObjectFactory.parseObjects(msgBody), msgType);
                } catch (final PCEPDeserializerException e) {
                        throw new DeserializerException(e.getMessage(), e);
                } catch (final PCEPDocumentedException e) {
@@ -163,51 +170,51 @@ public class PCEPMessageFactory implements ProtocolMessageFactory {
                }
                logger.debug("Message was parsed. {}", msg);
                return msg;
-    }
+       }
 
-    @Override
+       @Override
        public byte[] put(final ProtocolMessage msg) {
-       final PCEPMessage pcepMsg = (PCEPMessage) msg;
+               final PCEPMessage pcepMsg = (PCEPMessage) msg;
                if (pcepMsg == null)
-                   throw new IllegalArgumentException("PCEPMessage is mandatory.");
+                       throw new IllegalArgumentException("PCEPMessage is mandatory.");
 
                final PCEPMessageType msgType;
 
                if (pcepMsg instanceof PCEPOpenMessage) {
-                   msgType = PCEPMessageType.OPEN;
+                       msgType = PCEPMessageType.OPEN;
                } else if (pcepMsg instanceof PCEPKeepAliveMessage) {
-                   msgType = PCEPMessageType.KEEPALIVE;
+                       msgType = PCEPMessageType.KEEPALIVE;
                } else if (pcepMsg instanceof PCEPCloseMessage) {
-                   msgType = PCEPMessageType.CLOSE;
+                       msgType = PCEPMessageType.CLOSE;
                } else if (pcepMsg instanceof PCEPReplyMessage) {
-                   msgType = PCEPMessageType.RESPONSE;
+                       msgType = PCEPMessageType.RESPONSE;
                } else if (pcepMsg instanceof PCEPRequestMessage) {
-                   msgType = PCEPMessageType.REQUEST;
+                       msgType = PCEPMessageType.REQUEST;
                } else if (pcepMsg instanceof PCEPNotificationMessage) {
-                   msgType = PCEPMessageType.NOTIFICATION;
+                       msgType = PCEPMessageType.NOTIFICATION;
                } else if (pcepMsg instanceof PCEPErrorMessage) {
-                   msgType = PCEPMessageType.ERROR;
+                       msgType = PCEPMessageType.ERROR;
                } else if (pcepMsg instanceof PCEPReportMessage) {
-                   msgType = PCEPMessageType.STATUS_REPORT;
+                       msgType = PCEPMessageType.STATUS_REPORT;
                } else if (pcepMsg instanceof PCEPUpdateRequestMessage) {
-                   msgType = PCEPMessageType.UPDATE_REQUEST;
+                       msgType = PCEPMessageType.UPDATE_REQUEST;
                } else if (pcepMsg instanceof PCEPXRAddTunnelMessage) {
-                   msgType = PCEPMessageType.XR_ADD_TUNNEL;
+                       msgType = PCEPMessageType.XR_ADD_TUNNEL;
                } else if (pcepMsg instanceof PCEPXRDeleteTunnelMessage) {
-                   msgType = PCEPMessageType.XR_DELETE_TUNNEL;
+                       msgType = PCEPMessageType.XR_DELETE_TUNNEL;
                } else if (pcepMsg instanceof PCCreateMessage) {
-                   msgType = PCEPMessageType.PCCREATE;
+                       msgType = PCEPMessageType.PCCREATE;
                } else {
-                   logger.error("Unknown instance of PCEPMessage. Message class: {}", pcepMsg.getClass());
-                   throw new IllegalArgumentException("Unknown instance of PCEPMessage. Passed " + pcepMsg.getClass());
+                       logger.error("Unknown instance of PCEPMessage. Message class: {}", pcepMsg.getClass());
+                       throw new IllegalArgumentException("Unknown instance of PCEPMessage. Passed " + pcepMsg.getClass());
                }
 
                logger.trace("Serializing {}", msgType);
 
                final byte[] msgBody = MapOfParsers.getInstance().get(msgType).put(pcepMsg);
 
-               final PCEPMessageHeader msgHeader = new PCEPMessageHeader(msgType.getIdentifier(), msgBody.length + PCEPMessageHeader.COMMON_HEADER_LENGTH,
-                               PCEPMessage.PCEP_VERSION);
+               final PCEPMessageHeader msgHeader = new PCEPMessageHeader(msgType.getIdentifier(), msgBody.length
+                               + PCEPMessageHeader.COMMON_HEADER_LENGTH, PCEPMessage.PCEP_VERSION);
 
                final byte[] headerBytes = msgHeader.toBytes();
                final byte[] retBytes = new byte[headerBytes.length + msgBody.length];
@@ -216,6 +223,5 @@ public class PCEPMessageFactory implements ProtocolMessageFactory {
                ByteArray.copyWhole(msgBody, retBytes, PCEPMessageHeader.COMMON_HEADER_LENGTH);
 
                return retBytes;
-    }
+       }
 }
-
index 58798b62505958606875f062c0836334c669e213..2e67494f4950e435317be89440d2a7eecb3eca7f 100644 (file)
@@ -7,14 +7,16 @@
  */
 package org.opendaylight.protocol.pcep.impl;
 
+import io.netty.channel.ChannelHandlerContext;
+
+import java.util.Timer;
+
 import org.opendaylight.protocol.framework.ProtocolConnection;
 import org.opendaylight.protocol.framework.ProtocolSession;
 import org.opendaylight.protocol.framework.SessionParent;
 import org.opendaylight.protocol.pcep.PCEPConnection;
 import org.opendaylight.protocol.pcep.PCEPSessionFactory;
 
-import java.util.Timer;
-
 public class PCEPSessionFactoryImpl implements PCEPSessionFactory {
 
        private final int maxUnknownMessages;
@@ -24,9 +26,8 @@ public class PCEPSessionFactoryImpl implements PCEPSessionFactory {
        }
 
        @Override
-       public ProtocolSession getProtocolSession(final SessionParent parent, final Timer timer,
-                       final ProtocolConnection connection, final int sessionId) {
-                return new PCEPSessionImpl(parent, timer, (PCEPConnection)connection, new PCEPMessageFactory(),
-                                this.maxUnknownMessages, sessionId);
+       public ProtocolSession getProtocolSession(final SessionParent parent, final Timer timer, final ProtocolConnection connection,
+                       final int sessionId, final ChannelHandlerContext ctx) {
+               return new PCEPSessionImpl(parent, timer, (PCEPConnection) connection, new PCEPMessageFactory(), this.maxUnknownMessages, sessionId, ctx);
        }
 }
index f867462a1e0a12d2a5aef2388e2d2f27fa8454eb..3fa9dda68d2950382c8fc09c2be39fdc9ab5cc4b 100644 (file)
@@ -7,12 +7,23 @@
  */
 package org.opendaylight.protocol.pcep.impl;
 
+import io.netty.channel.ChannelHandlerContext;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+import java.util.Timer;
+import java.util.TimerTask;
+
 import org.opendaylight.protocol.framework.DeserializerException;
 import org.opendaylight.protocol.framework.DocumentedException;
 import org.opendaylight.protocol.framework.ProtocolMessage;
 import org.opendaylight.protocol.framework.ProtocolMessageFactory;
-import org.opendaylight.protocol.framework.ProtocolOutputStream;
 import org.opendaylight.protocol.framework.ProtocolSession;
+import org.opendaylight.protocol.framework.ProtocolSessionOutboundHandler;
 import org.opendaylight.protocol.framework.SessionParent;
 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
 import org.opendaylight.protocol.pcep.PCEPConnection;
@@ -38,15 +49,6 @@ import org.opendaylight.protocol.pcep.tlv.NodeIdentifierTlv;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Queue;
-import java.util.Timer;
-import java.util.TimerTask;
-
 /**
  * Implementation of PCEPSession. (Not final for testing.)
  */
@@ -186,8 +188,6 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
         */
        private PCEPOpenObject remoteOpen = null;
 
-       private final ProtocolOutputStream outputStream;
-
        private static final Logger logger = LoggerFactory.getLogger(PCEPSessionImpl.class);
 
        /**
@@ -205,20 +205,25 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
 
        private final String peerAddress;
 
+       private final ProtocolSessionOutboundHandler handler;
+
+       private final ChannelHandlerContext ctx;
+
        PCEPSessionImpl(final SessionParent parent, final Timer timer, final PCEPConnection connection, final PCEPMessageFactory factory,
-                       final int maxUnknownMessages, final int sessionId) {
+                       final int maxUnknownMessages, final int sessionId, final ChannelHandlerContext ctx) {
                this.state = State.IDLE;
                this.listener = connection.getListener();
                this.checker = connection.getProposalChecker();
                this.sessionId = sessionId;
                this.localOpen = connection.getProposal().getOpenObject();
-               this.outputStream = new ProtocolOutputStream();
                this.peerAddress = connection.getPeerAddress().getHostString();
                this.stateTimer = timer;
                this.parent = parent;
                this.factory = factory;
+               this.ctx = ctx;
                if (this.maxUnknownMessages != 0)
                        this.maxUnknownMessages = maxUnknownMessages;
+               this.handler = new ProtocolSessionOutboundHandler(this);
        }
 
        @Override
@@ -340,7 +345,7 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
 
        /**
         * Makes a callback to check if the session characteristics that FSM received, are acceptable.
-        *
+        * 
         * @param keepAliveTimerValue
         * @param deadTimerValue
         * @param tlvs
@@ -356,22 +361,20 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
 
        /**
         * Sends message to serialization.
-        *
+        * 
         * @param msg to be sent
         */
        @Override
        public void sendMessage(final PCEPMessage msg) {
-               this.outputStream.putMessage(msg, this.factory);
-               this.lastMessageSentAt = System.nanoTime();
-               if (!(msg instanceof PCEPKeepAliveMessage))
-                       logger.debug("Sent message: " + msg);
-               this.parent.checkOutputBuffer(this);
-               this.sentMsgCount++;
-       }
-
-       @Override
-       public ProtocolOutputStream getStream() {
-               return this.outputStream;
+               try {
+                       this.handler.writeDown(this.ctx, msg);
+                       this.lastMessageSentAt = System.nanoTime();
+                       if (!(msg instanceof PCEPKeepAliveMessage))
+                               logger.debug("Sent message: " + msg);
+                       this.sentMsgCount++;
+               } catch (final Exception e) {
+                       logger.warn("Message {} was not sent.", msg, e);
+               }
        }
 
        private void commonClose() {
@@ -382,7 +385,7 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
        /**
         * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
         * modified, because he initiated the closing. (To prevent concurrent modification exception).
-        *
+        * 
         * @param closeObject
         */
        void closeWithoutMessage() {
@@ -433,7 +436,7 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
 
        /**
         * Sends PCEP Error Message with one PCEPError and Open Object.
-        *
+        * 
         * @param value
         * @param open
         */
@@ -461,7 +464,7 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
         * sent (CAPABILITY_NOT_SUPPORTED) and the method checks if the MAX_UNKNOWN_MSG per minute wasn't overstepped.
         * Second, any other error occurred that is specified by rfc. In this case, the an error message is generated and
         * sent.
-        *
+        * 
         * @param error documented error in RFC5440 or draft
         */
        public void handleMalformedMessage(final PCEPErrors error) {
@@ -481,7 +484,7 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
        /**
         * In case of syntactic error or some parsing error, the session needs to be closed with the Reason: malformed
         * message. The user needs to be notified about this error.
-        *
+        * 
         * @param e exception that was thrown from parser
         */
        public void handleMalformedMessage(final Exception e) {
@@ -491,7 +494,7 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
 
        /**
         * Open message should be handled only if the FSM is in OPEN_WAIT state.
-        *
+        * 
         * @param msg
         */
        private void handleOpenMessage(final PCEPOpenMessage msg) {
@@ -550,7 +553,7 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
        /**
         * Error message should be handled in FSM if its state is KEEP_WAIT, otherwise it is just passed to session listener
         * for handling.
-        *
+        * 
         * @param msg
         */
        private void handleErrorMessage(final PCEPErrorMessage msg) {
@@ -600,7 +603,7 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
        /**
         * Handles incoming message. If the session is up, it notifies the user. The user is notified about every message
         * except KeepAlive.
-        *
+        * 
         * @param msg incoming message
         */
        @Override
@@ -703,19 +706,16 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
                return this.receivedMsgCount;
        }
 
-
        @Override
        public Integer getDeadTimerValue() {
                return this.DEAD_TIMER_VALUE;
        }
 
-
        @Override
        public Integer getKeepAliveTimerValue() {
                return this.KEEP_ALIVE_TIMER_VALUE;
        }
 
-
        @Override
        public String getPeerAddress() {
                return this.peerAddress;
@@ -726,7 +726,6 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
                this.close();
        }
 
-
        @Override
        public String getNodeIdentifier() {
                if (!this.remoteOpen.getTlvs().isEmpty()) {
@@ -757,8 +756,6 @@ class PCEPSessionImpl implements PCEPSession, ProtocolSession, PCEPSessionRuntim
                builder.append(this.localOpen);
                builder.append(", remoteOpen=");
                builder.append(this.remoteOpen);
-               builder.append(", outputStream=");
-               builder.append(this.outputStream);
                builder.append("]");
                return builder.toString();
        }
index beaae4136f2f33f131718f916416f9807f7d332a..b3b4845221b9e0cfa18c248b0fb7ff982852ca36 100644 (file)
@@ -18,12 +18,7 @@ import org.opendaylight.protocol.framework.SessionParent;
 public class MockDispatcher implements SessionParent {
 
        @Override
-       public void onSessionClosed(ProtocolSession session) {
-
-       }
-
-       @Override
-       public void checkOutputBuffer(ProtocolSession session) {
+       public void onSessionClosed(final ProtocolSession session) {
 
        }
 
index 7f017f052560d6a969c1475cd74c4826c1cd73d1..49d9f94f441a099fb459aaf8ec68e5a1f3391e9a 100644 (file)
@@ -12,20 +12,17 @@ import static org.junit.Assert.assertEquals;
 
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.List;
 
 import org.junit.Test;
-
-import org.opendaylight.protocol.framework.DeserializerException;
-import org.opendaylight.protocol.framework.DocumentedException;
-import org.opendaylight.protocol.util.ByteArray;
 import org.opendaylight.protocol.concepts.ASNumber;
 import org.opendaylight.protocol.concepts.Bandwidth;
 import org.opendaylight.protocol.concepts.IGPMetric;
 import org.opendaylight.protocol.concepts.IPv4;
 import org.opendaylight.protocol.concepts.IPv4Address;
 import org.opendaylight.protocol.concepts.TEMetric;
+import org.opendaylight.protocol.framework.DeserializerException;
+import org.opendaylight.protocol.framework.DocumentedException;
 import org.opendaylight.protocol.pcep.PCEPDeserializerException;
 import org.opendaylight.protocol.pcep.PCEPDocumentedException;
 import org.opendaylight.protocol.pcep.PCEPErrors;
@@ -93,729 +90,686 @@ import org.opendaylight.protocol.pcep.subobject.XROAsNumberSubobject;
 import org.opendaylight.protocol.pcep.tlv.LSPStateDBVersionTlv;
 import org.opendaylight.protocol.pcep.tlv.LSPSymbolicNameTlv;
 import org.opendaylight.protocol.pcep.tlv.PCEStatefulCapabilityTlv;
+import org.opendaylight.protocol.util.ByteArray;
 
 public class PCEPValidatorTest {
 
-    private static final PCEPLspaObject lspa = new PCEPLspaObject(0L, 0L, 0L, (short) 0, (short) 0, false, false, false, false);
+       private static final PCEPLspaObject lspa = new PCEPLspaObject(0L, 0L, 0L, (short) 0, (short) 0, false, false, false, false);
 
-    private final List<ExplicitRouteSubobject> eroSubobjects = asList(
-           new EROAsNumberSubobject(new ASNumber(0xFFFFL), false),
-           new EROUnnumberedInterfaceSubobject(new IPv4Address(
-                   new byte[] { (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33 }), new UnnumberedInterfaceIdentifier(0x00FF00FF), false));
+       private final List<ExplicitRouteSubobject> eroSubobjects = asList(
+                       new EROAsNumberSubobject(new ASNumber(0xFFFFL), false),
+                       new EROUnnumberedInterfaceSubobject(new IPv4Address(new byte[] { (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33 }), new UnnumberedInterfaceIdentifier(0x00FF00FF), false));
 
-    private final List<ReportedRouteSubobject> rroSubobjects = asList((ReportedRouteSubobject) new RROUnnumberedInterfaceSubobject(new IPv4Address(new byte[] { (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33 }),
-           new UnnumberedInterfaceIdentifier(0x00FF00FF)));
+       private final List<ReportedRouteSubobject> rroSubobjects = asList((ReportedRouteSubobject) new RROUnnumberedInterfaceSubobject(new IPv4Address(new byte[] {
+                       (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33 }), new UnnumberedInterfaceIdentifier(0x00FF00FF)));
 
-    private final List<Long> requestIds = asList(0x000001L);
+       private final List<Long> requestIds = asList(0x000001L);
 
-    private final IPv4Address ip4addr = new IPv4Address(new byte[] { (byte) 0xFF, 0x00, 0x00, 0x01 });
+       private final IPv4Address ip4addr = new IPv4Address(new byte[] { (byte) 0xFF, 0x00, 0x00, 0x01 });
 
-    private final PCEPSvecObject svecObj = new PCEPSvecObject(true, true, true, false, false, PCEPValidatorTest.this.requestIds, true);
+       private final PCEPSvecObject svecObj = new PCEPSvecObject(true, true, true, false, false, PCEPValidatorTest.this.requestIds, true);
 
-    private final PCEPRequestParameterObject requestParameter = new PCEPRequestParameterObject(true, false, false, false, false, false, false, false,
-           (short) 3, 1, true, false);
+       private final PCEPRequestParameterObject requestParameter = new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, true, false);
 
-    // private final PCEPEndPointsObject<IPv4Address> endPoints = new
-    // PCEPEndPointsObject<IPv4Address>(this.ip4addr, this.ip4addr);
+       // private final PCEPEndPointsObject<IPv4Address> endPoints = new
+       // PCEPEndPointsObject<IPv4Address>(this.ip4addr, this.ip4addr);
 
-    private final PCEPEndPointsObject<IPv4Address> endPoints = new PCEPEndPointsObject<IPv4Address>(this.ip4addr, this.ip4addr);
+       private final PCEPEndPointsObject<IPv4Address> endPoints = new PCEPEndPointsObject<IPv4Address>(this.ip4addr, this.ip4addr);
 
-    private final PCEPMessageFactory msgFactory = new PCEPMessageFactory();
+       private final PCEPMessageFactory msgFactory = new PCEPMessageFactory();
 
-    // private final PCEPClassTypeObject classType = new
-    // PCEPClassTypeObject((short) 7);
-    // private final PCEPClassTypeObjectProvider classTypeProvider = new
-    // PCEPClassTypeObjectProvider((short) 7, true);
+       // private final PCEPClassTypeObject classType = new
+       // PCEPClassTypeObject((short) 7);
+       // private final PCEPClassTypeObjectProvider classTypeProvider = new
+       // PCEPClassTypeObjectProvider((short) 7, true);
 
-    private static List<PCEPMessage> deserMsg(final String srcFile) throws IOException, DeserializerException, DocumentedException, PCEPDeserializerException {
+       private static List<PCEPMessage> deserMsg(final String srcFile) throws IOException, DeserializerException, DocumentedException,
+                       PCEPDeserializerException {
                final byte[] bytesFromFile = ByteArray.fileToBytes(srcFile);
-               final PCEPRawMessage rawMessage = (PCEPRawMessage) new PCEPMessageFactory().parse(ByteArray.cutBytes(bytesFromFile, PCEPMessageHeader.COMMON_HEADER_LENGTH),
-                       new PCEPMessageHeader().fromBytes(Arrays.copyOf(bytesFromFile, PCEPMessageHeader.COMMON_HEADER_LENGTH)));
+               final PCEPRawMessage rawMessage = (PCEPRawMessage) new PCEPMessageFactory().parse(ByteArray.cutBytes(bytesFromFile, 1));
 
                return PCEPMessageValidator.getValidator(rawMessage.getMsgType()).validate(rawMessage.getAllObjects());
-    }
-
-    @Test
-    public void testOpenMessageValidationFromBin() throws IOException, DeserializerException, DocumentedException, PCEPDeserializerException {
-       assertEquals(
-               deserMsg("src/test/resources/PCEPOpenMessage1.bin"),
-               asList(new PCEPOpenMessage(new PCEPOpenObject(30, 120, 1, asList(new PCEStatefulCapabilityTlv(false, true, true), new LSPStateDBVersionTlv(
-                       0x80))))));
-
-       assertEquals(deserMsg("src/test/resources/Open.1.bin"), asList(new PCEPOpenMessage(new PCEPOpenObject(1, 4, 1))));
-
-       assertEquals(
-               deserMsg("src/test/resources/Open.3.bin"),
-               asList(new PCEPOpenMessage(new PCEPOpenObject(1, 4, 1, asList(new PCEStatefulCapabilityTlv(false, true, true), new LSPStateDBVersionTlv(53))))));
-    }
-
-    @Test
-    public void testKeepAliveMessageValidationFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException, DeserializerException, DocumentedException {
-       assertEquals(deserMsg("src/test/resources/PCEPKeepAliveMessage1.bin"), asList(new PCEPKeepAliveMessage()));
-       assertEquals(deserMsg("src/test/resources/Keepalive.1.bin"), asList(new PCEPKeepAliveMessage()));
-    }
-
-    @Test
-    public void testCloseMsg() throws PCEPDeserializerException, IOException, PCEPDocumentedException, DeserializerException, DocumentedException {
-       assertEquals(deserMsg("src/test/resources/PCEPCloseMessage1.bin"), asList(new PCEPCloseMessage(new PCEPCloseObject(Reason.TOO_MANY_UNKNOWN_MSG))));
-       assertEquals(deserMsg("src/test/resources/Close.1.bin"), asList(new PCEPCloseMessage(new PCEPCloseObject(Reason.UNKNOWN))));
-    }
-
-    @Test
-    public void testRequestMessageValidationFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException, DeserializerException, DocumentedException {
-       List<CompositeRequestObject> requests = new ArrayList<CompositeRequestObject>();
-       final byte[] ipAdress = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };
-       requests.add(new CompositeRequestObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 5, 0xDEADBEEFL,
-               true, false), new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress), new IPv4Address(ipAdress))));
-       PCEPRequestMessage specMessage = new PCEPRequestMessage(requests);
-       List<PCEPMessage> deserMsgs = deserMsg("src/test/resources/PCEPRequestMessage1.bin");
-       final List<PCEPMessage> specMessages = new ArrayList<PCEPMessage>();
-       specMessages.add(specMessage);
-
-       assertEquals(deserMsgs, specMessages);
-
-       requests = new ArrayList<CompositeRequestObject>();
-       final byte[] ipAdress2 = { (byte) 0x7F, (byte) 0x00, (byte) 0x00, (byte) 0x01 };
-       requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2))));
-       specMessage = new PCEPRequestMessage(requests);
-       deserMsgs = deserMsg("src/test/resources/PCReq.1.bin");
-       specMessages.clear();
-       specMessages.add(specMessage);
-       assertEquals(deserMsgs, specMessages);
-
-       requests = new ArrayList<CompositeRequestObject>();
-       requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2)), null, null, null, null,
-               null, null, null, null, new PCEPLoadBalancingObject(3, new Bandwidth(1024.75f), false)));
-       specMessage = new PCEPRequestMessage(requests);
-       deserMsgs = deserMsg("src/test/resources/PCReq.2.bin");
-       specMessages.clear();
-       specMessages.add(specMessage);
-       assertEquals(deserMsgs, specMessages);
-
-       requests = new ArrayList<CompositeRequestObject>();
-       requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2)), null, new PCEPLspObject(1,
-               false, false, true, false), PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(1000), false, false),
-               new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, true, new IGPMetric(53L), false, false));
-                   }
-               }, new PCEPReportedRouteObject(this.rroSubobjects, false), new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false),
-               new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new PCEPLoadBalancingObject(5, new Bandwidth(3f), false)));
-
-       List<CompositeRequestSvecObject> svecList = new ArrayList<CompositeRequestSvecObject>();
-       svecList.add(new CompositeRequestSvecObject(new PCEPSvecObject(true, false, false, false, false, this.requestIds, false)));
-
-       specMessage = new PCEPRequestMessage(svecList, requests);
-       deserMsgs = deserMsg("src/test/resources/PCReq.3.bin");
-       specMessages.clear();
-       specMessages.add(specMessage);
-       assertEquals(deserMsgs, specMessages);
-
-       specMessages.clear();
-       requests = new ArrayList<CompositeRequestObject>();
-       requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2)), null, null, null, null,
-               null, null, null, null, null));
-       specMessages.add(new PCEPRequestMessage(requests));
-
-       final byte[] ipAdress3 = { (byte) 0x7F, (byte) 0x00, (byte) 0x30, (byte) 0x01 };
-       requests = new ArrayList<CompositeRequestObject>();
-       requests.add(new CompositeRequestObject(new PCEPRequestParameterObject(false, false, false, false, false, false, false, false, (short) 4, 1, true,
-               false), new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress3), new IPv4Address(ipAdress2)), null, null, null, null, null, null, null, null, null));
-       specMessages.add(new PCEPRequestMessage(requests));
-
-       final byte[] ipAdress4 = { (byte) 0x7F, (byte) 0x30, (byte) 0x00, (byte) 0x01 };
-       requests = new ArrayList<CompositeRequestObject>();
-       requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress4)), null, null, null, null,
-               null, null, null, null, null));
-       specMessages.add(new PCEPRequestMessage(requests));
-
-       final byte[] ipAdress5 = { (byte) 0x7F, (byte) 0xd0, (byte) 0x00, (byte) 0x01 };
-       requests = new ArrayList<CompositeRequestObject>();
-       requests.add(new CompositeRequestObject(
-               new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 1, true, false),
-               new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress5), new IPv4Address(ipAdress5)), null, null, null, null, null, null, null, null, null));
-
-       specMessages.add(new PCEPRequestMessage(requests));
-       deserMsgs = deserMsg("src/test/resources/PCReq.4.bin");
-       assertEquals(deserMsgs, specMessages);
-
-       specMessages.clear();
-       svecList = new ArrayList<CompositeRequestSvecObject>();
-       svecList.add(new CompositeRequestSvecObject(new PCEPSvecObject(true, false, false, false, false, this.requestIds, false)));
-       svecList.add(new CompositeRequestSvecObject(new PCEPSvecObject(false, true, true, false, false, this.requestIds, false),
-               new PCEPObjectiveFunctionObject(PCEPOFCodes.MCC, true, false), new PCEPGlobalConstraintsObject((short) 0x55, (short) 1, (short) 100,
-                       (short) 0x26, true, false), new PCEPExcludeRouteObject(new ArrayList<ExcludeRouteSubobject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new XROAsNumberSubobject(new ASNumber(0x12), true));
-                   }
+       }
+
+       @Test
+       public void testOpenMessageValidationFromBin() throws IOException, DeserializerException, DocumentedException,
+                       PCEPDeserializerException {
+               assertEquals(
+                               deserMsg("src/test/resources/PCEPOpenMessage1.bin"),
+                               asList(new PCEPOpenMessage(new PCEPOpenObject(30, 120, 1, asList(new PCEStatefulCapabilityTlv(false, true, true),
+                                               new LSPStateDBVersionTlv(0x80))))));
+
+               assertEquals(deserMsg("src/test/resources/Open.1.bin"), asList(new PCEPOpenMessage(new PCEPOpenObject(1, 4, 1))));
+
+               assertEquals(
+                               deserMsg("src/test/resources/Open.3.bin"),
+                               asList(new PCEPOpenMessage(new PCEPOpenObject(1, 4, 1, asList(new PCEStatefulCapabilityTlv(false, true, true),
+                                               new LSPStateDBVersionTlv(53))))));
+       }
+
+       @Test
+       public void testKeepAliveMessageValidationFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException,
+                       DeserializerException, DocumentedException {
+               assertEquals(deserMsg("src/test/resources/PCEPKeepAliveMessage1.bin"), asList(new PCEPKeepAliveMessage()));
+               assertEquals(deserMsg("src/test/resources/Keepalive.1.bin"), asList(new PCEPKeepAliveMessage()));
+       }
+
+       @Test
+       public void testCloseMsg() throws PCEPDeserializerException, IOException, PCEPDocumentedException, DeserializerException,
+                       DocumentedException {
+               assertEquals(deserMsg("src/test/resources/PCEPCloseMessage1.bin"),
+                               asList(new PCEPCloseMessage(new PCEPCloseObject(Reason.TOO_MANY_UNKNOWN_MSG))));
+               assertEquals(deserMsg("src/test/resources/Close.1.bin"), asList(new PCEPCloseMessage(new PCEPCloseObject(Reason.UNKNOWN))));
+       }
+
+       @Test
+       public void testRequestMessageValidationFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException,
+                       DeserializerException, DocumentedException {
+               List<CompositeRequestObject> requests = new ArrayList<CompositeRequestObject>();
+               final byte[] ipAdress = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };
+               requests.add(new CompositeRequestObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 5, 0xDEADBEEFL, true, false), new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress), new IPv4Address(ipAdress))));
+               PCEPRequestMessage specMessage = new PCEPRequestMessage(requests);
+               List<PCEPMessage> deserMsgs = deserMsg("src/test/resources/PCEPRequestMessage1.bin");
+               final List<PCEPMessage> specMessages = new ArrayList<PCEPMessage>();
+               specMessages.add(specMessage);
+
+               assertEquals(deserMsgs, specMessages);
+
+               requests = new ArrayList<CompositeRequestObject>();
+               final byte[] ipAdress2 = { (byte) 0x7F, (byte) 0x00, (byte) 0x00, (byte) 0x01 };
+               requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2))));
+               specMessage = new PCEPRequestMessage(requests);
+               deserMsgs = deserMsg("src/test/resources/PCReq.1.bin");
+               specMessages.clear();
+               specMessages.add(specMessage);
+               assertEquals(deserMsgs, specMessages);
+
+               requests = new ArrayList<CompositeRequestObject>();
+               requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2)), null, null, null, null, null, null, null, null, new PCEPLoadBalancingObject(3, new Bandwidth(1024.75f), false)));
+               specMessage = new PCEPRequestMessage(requests);
+               deserMsgs = deserMsg("src/test/resources/PCReq.2.bin");
+               specMessages.clear();
+               specMessages.add(specMessage);
+               assertEquals(deserMsgs, specMessages);
+
+               requests = new ArrayList<CompositeRequestObject>();
+               requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2)), null, new PCEPLspObject(1, false, false, true, false), PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(1000), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, true, new IGPMetric(53L), false, false));
+                       }
+               }, new PCEPReportedRouteObject(this.rroSubobjects, false), new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new PCEPLoadBalancingObject(5, new Bandwidth(3f), false)));
+
+               List<CompositeRequestSvecObject> svecList = new ArrayList<CompositeRequestSvecObject>();
+               svecList.add(new CompositeRequestSvecObject(new PCEPSvecObject(true, false, false, false, false, this.requestIds, false)));
+
+               specMessage = new PCEPRequestMessage(svecList, requests);
+               deserMsgs = deserMsg("src/test/resources/PCReq.3.bin");
+               specMessages.clear();
+               specMessages.add(specMessage);
+               assertEquals(deserMsgs, specMessages);
+
+               specMessages.clear();
+               requests = new ArrayList<CompositeRequestObject>();
+               requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2)), null, null, null, null, null, null, null, null, null));
+               specMessages.add(new PCEPRequestMessage(requests));
+
+               final byte[] ipAdress3 = { (byte) 0x7F, (byte) 0x00, (byte) 0x30, (byte) 0x01 };
+               requests = new ArrayList<CompositeRequestObject>();
+               requests.add(new CompositeRequestObject(new PCEPRequestParameterObject(false, false, false, false, false, false, false, false, (short) 4, 1, true, false), new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress3), new IPv4Address(ipAdress2)), null, null, null, null, null, null, null, null, null));
+               specMessages.add(new PCEPRequestMessage(requests));
+
+               final byte[] ipAdress4 = { (byte) 0x7F, (byte) 0x30, (byte) 0x00, (byte) 0x01 };
+               requests = new ArrayList<CompositeRequestObject>();
+               requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress4)), null, null, null, null, null, null, null, null, null));
+               specMessages.add(new PCEPRequestMessage(requests));
+
+               final byte[] ipAdress5 = { (byte) 0x7F, (byte) 0xd0, (byte) 0x00, (byte) 0x01 };
+               requests = new ArrayList<CompositeRequestObject>();
+               requests.add(new CompositeRequestObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 1, true, false), new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress5), new IPv4Address(ipAdress5)), null, null, null, null, null, null, null, null, null));
+
+               specMessages.add(new PCEPRequestMessage(requests));
+               deserMsgs = deserMsg("src/test/resources/PCReq.4.bin");
+               assertEquals(deserMsgs, specMessages);
+
+               specMessages.clear();
+               svecList = new ArrayList<CompositeRequestSvecObject>();
+               svecList.add(new CompositeRequestSvecObject(new PCEPSvecObject(true, false, false, false, false, this.requestIds, false)));
+               svecList.add(new CompositeRequestSvecObject(new PCEPSvecObject(false, true, true, false, false, this.requestIds, false), new PCEPObjectiveFunctionObject(PCEPOFCodes.MCC, true, false), new PCEPGlobalConstraintsObject((short) 0x55, (short) 1, (short) 100, (short) 0x26, true, false), new PCEPExcludeRouteObject(new ArrayList<ExcludeRouteSubobject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new XROAsNumberSubobject(new ASNumber(0x12), true));
+                       }
                }, true, true, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, true, new TEMetric(123456L), true, false));
+                       }
+               }));
 
-                   {
-                       this.add(new PCEPMetricObject(true, true, new TEMetric(123456L), true, false));
-                   }
+               requests = new ArrayList<CompositeRequestObject>();
+               requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2)), null, null, PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(1000), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, true, new IGPMetric(53L), false, false));
+                               this.add(new PCEPMetricObject(true, true, new IGPMetric(5335L), false, false));
+                               this.add(new PCEPMetricObject(true, true, new IGPMetric(128256), false, false));
+                       }
+               }, new PCEPReportedRouteObject(this.rroSubobjects, false), new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new PCEPLoadBalancingObject(5, new Bandwidth(3f), false)));
+
+               final byte[] ipAdress6 = { (byte) 0x7F, (byte) 0xF0, (byte) 0x00, (byte) 0x01 };
+               specMessages.add(new PCEPRequestMessage(svecList, requests));
+
+               requests = new ArrayList<CompositeRequestObject>();
+               requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress6), new IPv4Address(ipAdress6)), null, null, PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(1000), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, true, new IGPMetric(53L), false, false));
+                       }
+               }, new PCEPReportedRouteObject(this.rroSubobjects, false), new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new PCEPLoadBalancingObject(5, new Bandwidth(3f), false)));
+               deserMsgs = deserMsg("src/test/resources/PCReq.5.bin");
+               specMessages.add(new PCEPRequestMessage(svecList, requests));
+               assertEquals(deserMsgs, specMessages);
+
+               // FIXME: need construct with invalid processed parameter
+               // assertEquals(deserMsg("src/test/resources/PCReq.6.invalid.bin"),
+               // asList(
+               // new PCEPErrorMessage(new CompositeErrorObject(new
+               // PCEPRequestParameterObject(true, false, false, false, false, false,
+               // false, false, (short) 3,
+               // 1L, false, false), new PCEPErrorObject(PCEPErrors.P_FLAG_NOT_SET))),
+               // new PCEPRequestMessage(asList(new
+               // CompositeRequestObject(this.requestParameter, new
+               // PCEPEndPointsObject<IPv4Address>(IPv4Address
+               // .getNetworkAddressFactory().getNetworkAddressForBytes(new byte[] {
+               // 127, 0, 0, 1 }), IPv4Address.getNetworkAddressFactory()
+               // .getNetworkAddressForBytes(new byte[] { 127, 0, 0, 1 })), null, null,
+               // null, null, null, null, null, null, new PCEPLoadBalancingObject(
+               // 3, new Bandwidth(1024.75), false))))));
+
+       }
+
+       @Test
+       public void testRequestMessageValidationFromRawMsg() throws PCEPDeserializerException {
+               List<PCEPObject> objs = new ArrayList<PCEPObject>();
+               List<PCEPMessage> msgs;
+               PCEPRequestParameterObject tmpRP;
+
+               // test unrecognized object in svec list
+               objs.add(this.svecObj);
+               objs.add(new UnknownObject(true, false, PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
+               objs.add(new PCEPSvecObject(true, true, true, false, false, PCEPValidatorTest.this.requestIds, true));
+
+               msgs = PCEPMessageValidator.getValidator(PCEPMessageType.REQUEST).validate(objs);
+
+               assertEquals(msgs.get(0), new PCEPErrorMessage(new ArrayList<PCEPErrorObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
+                       }
                }));
 
-       requests = new ArrayList<CompositeRequestObject>();
-       requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress2), new IPv4Address(ipAdress2)), null, null,
-               PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(1000), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, true, new IGPMetric(53L), false, false));
-                       this.add(new PCEPMetricObject(true, true, new IGPMetric(5335L), false, false));
-                       this.add(new PCEPMetricObject(true, true, new IGPMetric(128256), false, false));
-                   }
-               }, new PCEPReportedRouteObject(this.rroSubobjects, false), new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false),
-               new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new PCEPLoadBalancingObject(5, new Bandwidth(3f), false)));
-
-       final byte[] ipAdress6 = { (byte) 0x7F, (byte) 0xF0, (byte) 0x00, (byte) 0x01 };
-       specMessages.add(new PCEPRequestMessage(svecList, requests));
-
-       requests = new ArrayList<CompositeRequestObject>();
-       requests.add(new CompositeRequestObject(this.requestParameter, new PCEPEndPointsObject<IPv4Address>(new IPv4Address(ipAdress6), new IPv4Address(ipAdress6)), null, null,
-               PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(1000), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, true, new IGPMetric(53L), false, false));
-                   }
-               }, new PCEPReportedRouteObject(this.rroSubobjects, false), new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false),
-               new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new PCEPLoadBalancingObject(5, new Bandwidth(3f), false)));
-       deserMsgs = deserMsg("src/test/resources/PCReq.5.bin");
-       specMessages.add(new PCEPRequestMessage(svecList, requests));
-       assertEquals(deserMsgs, specMessages);
-
-       // FIXME: need construct with invalid processed parameter
-       // assertEquals(deserMsg("src/test/resources/PCReq.6.invalid.bin"),
-       // asList(
-       // new PCEPErrorMessage(new CompositeErrorObject(new
-       // PCEPRequestParameterObject(true, false, false, false, false, false,
-       // false, false, (short) 3,
-       // 1L, false, false), new PCEPErrorObject(PCEPErrors.P_FLAG_NOT_SET))),
-       // new PCEPRequestMessage(asList(new
-       // CompositeRequestObject(this.requestParameter, new
-       // PCEPEndPointsObject<IPv4Address>(IPv4Address
-       // .getNetworkAddressFactory().getNetworkAddressForBytes(new byte[] {
-       // 127, 0, 0, 1 }), IPv4Address.getNetworkAddressFactory()
-       // .getNetworkAddressForBytes(new byte[] { 127, 0, 0, 1 })), null, null,
-       // null, null, null, null, null, null, new PCEPLoadBalancingObject(
-       // 3, new Bandwidth(1024.75), false))))));
-
-    }
-
-    @Test
-    public void testRequestMessageValidationFromRawMsg() throws PCEPDeserializerException {
-       List<PCEPObject> objs = new ArrayList<PCEPObject>();
-       List<PCEPMessage> msgs;
-       PCEPRequestParameterObject tmpRP;
-
-       // test unrecognized object in svec list
-       objs.add(this.svecObj);
-       objs.add(new UnknownObject(true, false, PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
-       objs.add(new PCEPSvecObject(true, true, true, false, false, PCEPValidatorTest.this.requestIds, true));
-
-       msgs = PCEPMessageValidator.getValidator(PCEPMessageType.REQUEST).validate(objs);
-
-       assertEquals(msgs.get(0), new PCEPErrorMessage(new ArrayList<PCEPErrorObject>() {
-           private static final long serialVersionUID = 1L;
-
-           {
-               this.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
-           }
-       }));
-
-       // test with request p flag not set and ignoracion of more than one
-       // end-points objects
-       objs = new ArrayList<PCEPObject>();
-       objs.add(this.svecObj);
-       objs.add(this.svecObj);
-       tmpRP = new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false);
-       objs.add(tmpRP);
-       objs.add(this.endPoints);
-
-       objs.add(this.requestParameter);
-       objs.add(this.endPoints);
-       objs.add(this.endPoints);
-       // FIXME:mv use object constructor with set processed flag
-       // objs.add(this.classTypeProvider);
-       // objs.add(this.requestParameter);
-       // objs.add(this.endPointsProvider);
-       // objs.add(new PCEPClassTypeObjectProvider((short) 7, false));
-
-       msgs = PCEPMessageValidator.getValidator(PCEPMessageType.REQUEST).validate(objs);
-       // FIXME:mv use object constructor with set processed flag
-       // assertEquals(msgs.get(0), new PCEPErrorMessage(new
-       // CompositeErrorObject(tmpRP, new
-       // PCEPErrorObject(PCEPErrors.P_FLAG_NOT_SET))));
-       // assertEquals(
-       // msgs.get(1),
-       // new PCEPRequestMessage(asList(new
-       // CompositeRequestSvecObject(this.svecObj), new
-       // CompositeRequestSvecObject(this.svecObj)), Util
-       // .asList(new CompositeRequestObject(this.requestParameter,
-       // this.endPoints, this.classType, null, null, null, null, null, null,
-       // null,
-       // null))));
-       // assertEquals(msgs.get(2), new PCEPErrorMessage(new
-       // CompositeErrorObject(tmpRP, new
-       // PCEPErrorObject(PCEPErrors.P_FLAG_NOT_SET))));
-    }
-
-    @Test
-    public void testReplyMessageValidatorFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException, DeserializerException, DocumentedException {
-
-       List<PCEPReplyMessage> specMessages = new ArrayList<PCEPReplyMessage>();
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 5, 0xDEADBEEFL, true, true)))));
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, true, true, false, false, false,
-               false, false, (short) 7, 0x12345678L, false, false)))));
-       assertEquals(deserMsg("src/test/resources/PCEPReplyMessage1.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPReplyMessage>();
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 3, 1, false, false)))));
-       assertEquals(deserMsg("src/test/resources/PCRep.1.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPReplyMessage>();
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 3, 1, false, false)))));
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(false, false, false, false, false, false,
-               false, false, (short) 5, 2, false, false), new PCEPNoPathObject((short) 0, false, false), null, null, null, null, null, null))));
-       assertEquals(deserMsg("src/test/resources/PCRep.2.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPReplyMessage>();
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 3, 1, false, false), new PCEPNoPathObject((short) 1, true, false), new PCEPLspObject(1, true, true, false, true),
-               PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, true, new IGPMetric(234), false, false));
-                   }
+               // test with request p flag not set and ignoracion of more than one
+               // end-points objects
+               objs = new ArrayList<PCEPObject>();
+               objs.add(this.svecObj);
+               objs.add(this.svecObj);
+               tmpRP = new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false);
+               objs.add(tmpRP);
+               objs.add(this.endPoints);
+
+               objs.add(this.requestParameter);
+               objs.add(this.endPoints);
+               objs.add(this.endPoints);
+               // FIXME:mv use object constructor with set processed flag
+               // objs.add(this.classTypeProvider);
+               // objs.add(this.requestParameter);
+               // objs.add(this.endPointsProvider);
+               // objs.add(new PCEPClassTypeObjectProvider((short) 7, false));
+
+               msgs = PCEPMessageValidator.getValidator(PCEPMessageType.REQUEST).validate(objs);
+               // FIXME:mv use object constructor with set processed flag
+               // assertEquals(msgs.get(0), new PCEPErrorMessage(new
+               // CompositeErrorObject(tmpRP, new
+               // PCEPErrorObject(PCEPErrors.P_FLAG_NOT_SET))));
+               // assertEquals(
+               // msgs.get(1),
+               // new PCEPRequestMessage(asList(new
+               // CompositeRequestSvecObject(this.svecObj), new
+               // CompositeRequestSvecObject(this.svecObj)), Util
+               // .asList(new CompositeRequestObject(this.requestParameter,
+               // this.endPoints, this.classType, null, null, null, null, null, null,
+               // null,
+               // null))));
+               // assertEquals(msgs.get(2), new PCEPErrorMessage(new
+               // CompositeErrorObject(tmpRP, new
+               // PCEPErrorObject(PCEPErrors.P_FLAG_NOT_SET))));
+       }
+
+       @Test
+       public void testReplyMessageValidatorFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException,
+                       DeserializerException, DocumentedException {
+
+               List<PCEPReplyMessage> specMessages = new ArrayList<PCEPReplyMessage>();
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 5, 0xDEADBEEFL, true, true)))));
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, true, true, false, false, false, false, false, (short) 7, 0x12345678L, false, false)))));
+               assertEquals(deserMsg("src/test/resources/PCEPReplyMessage1.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPReplyMessage>();
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false)))));
+               assertEquals(deserMsg("src/test/resources/PCRep.1.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPReplyMessage>();
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false)))));
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(false, false, false, false, false, false, false, false, (short) 5, 2, false, false), new PCEPNoPathObject((short) 0, false, false), null, null, null, null, null, null))));
+               assertEquals(deserMsg("src/test/resources/PCRep.2.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPReplyMessage>();
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false), new PCEPNoPathObject((short) 1, true, false), new PCEPLspObject(1, true, true, false, true), PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, true, new IGPMetric(234), false, false));
+                       }
                }, new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new ArrayList<CompositePathObject>() {
-                   private static final long serialVersionUID = 1L;
+                       private static final long serialVersionUID = 1L;
 
-                   {
-                       this.add(new CompositePathObject(new PCEPExplicitRouteObject(PCEPValidatorTest.this.eroSubobjects, false), lspa,
-                               new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
-                                   private static final long serialVersionUID = 1L;
+                       {
+                               this.add(new CompositePathObject(new PCEPExplicitRouteObject(PCEPValidatorTest.this.eroSubobjects, false), lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
+                                       private static final long serialVersionUID = 1L;
 
-                                   {
-                                       this.add(new PCEPMetricObject(true, true, new IGPMetric(234L), false, false));
-                                   }
+                                       {
+                                               this.add(new PCEPMetricObject(true, true, new IGPMetric(234L), false, false));
+                                       }
                                }, new PCEPIncludeRouteObject(PCEPValidatorTest.this.eroSubobjects, false, false)));
-                   }
+                       }
                }))));
-       assertEquals(deserMsg("src/test/resources/PCRep.3.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPReplyMessage>();
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 7, 1, false, false)))));
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 1, 2, false, false)))));
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 2, 4, false, false)))));
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(false, false, false, false, false, false,
-               false, false, (short) 3, 4, false, false)))));
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(false, false, false, false, false, false,
-               false, false, (short) 6, 5, false, false)))));
-       assertEquals(deserMsg("src/test/resources/PCRep.4.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPReplyMessage>();
-       final List<Long> requestIDs = new ArrayList<Long>();
-       requestIDs.add(0x25069045L);
-
-       final List<PCEPMetricObject> metrics = new ArrayList<PCEPMetricObject>();
-       metrics.add(new PCEPMetricObject(true, true, new IGPMetric(234L), true, false));
-
-       final List<CompositeReplySvecObject> svecList = new ArrayList<CompositeReplySvecObject>();
-       svecList.add(new CompositeReplySvecObject(new PCEPSvecObject(true, true, true, false, false, requestIDs, true), new PCEPObjectiveFunctionObject(
-               PCEPOFCodes.MCC, true, false), metrics));
-
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 3, 1, false, false), new PCEPNoPathObject((short) 1, true, false), null, PCEPValidatorTest.lspa,
-               new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, true, new IGPMetric(234), false, false));
-                   }
+               assertEquals(deserMsg("src/test/resources/PCRep.3.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPReplyMessage>();
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 7, 1, false, false)))));
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 2, false, false)))));
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 2, 4, false, false)))));
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(false, false, false, false, false, false, false, false, (short) 3, 4, false, false)))));
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(false, false, false, false, false, false, false, false, (short) 6, 5, false, false)))));
+               assertEquals(deserMsg("src/test/resources/PCRep.4.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPReplyMessage>();
+               final List<Long> requestIDs = new ArrayList<Long>();
+               requestIDs.add(0x25069045L);
+
+               final List<PCEPMetricObject> metrics = new ArrayList<PCEPMetricObject>();
+               metrics.add(new PCEPMetricObject(true, true, new IGPMetric(234L), true, false));
+
+               final List<CompositeReplySvecObject> svecList = new ArrayList<CompositeReplySvecObject>();
+               svecList.add(new CompositeReplySvecObject(new PCEPSvecObject(true, true, true, false, false, requestIDs, true), new PCEPObjectiveFunctionObject(PCEPOFCodes.MCC, true, false), metrics));
+
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false), new PCEPNoPathObject((short) 1, true, false), null, PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, true, new IGPMetric(234), false, false));
+                       }
                }, new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new ArrayList<CompositePathObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new CompositePathObject(new PCEPExplicitRouteObject(PCEPValidatorTest.this.eroSubobjects, false), lspa,
-                               new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
-                                   private static final long serialVersionUID = 1L;
-
-                                   {
-                                       this.add(new PCEPMetricObject(true, true, new IGPMetric(234L), false, false));
-                                       this.add(new PCEPMetricObject(true, true, new IGPMetric(5355L), false, false));
-                                       this.add(new PCEPMetricObject(true, true, new IGPMetric(5353L), false, false));
-                                   }
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new CompositePathObject(new PCEPExplicitRouteObject(PCEPValidatorTest.this.eroSubobjects, false), lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
+                                       private static final long serialVersionUID = 1L;
+
+                                       {
+                                               this.add(new PCEPMetricObject(true, true, new IGPMetric(234L), false, false));
+                                               this.add(new PCEPMetricObject(true, true, new IGPMetric(5355L), false, false));
+                                               this.add(new PCEPMetricObject(true, true, new IGPMetric(5353L), false, false));
+                                       }
                                }, new PCEPIncludeRouteObject(PCEPValidatorTest.this.eroSubobjects, false, false)));
-                   }
+                       }
                })), svecList));
-       specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false,
-               false, false, (short) 3, 1, false, false), new PCEPNoPathObject((short) 1, true, false), null, PCEPValidatorTest.lspa,
-               new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, true, new IGPMetric(234), false, false));
-                   }
+               specMessages.add(new PCEPReplyMessage(asList(new CompositeResponseObject(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false), new PCEPNoPathObject((short) 1, true, false), null, PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, true, new IGPMetric(234), false, false));
+                       }
                }, new PCEPIncludeRouteObject(this.eroSubobjects, false, false), new ArrayList<CompositePathObject>() {
-                   private static final long serialVersionUID = 1L;
+                       private static final long serialVersionUID = 1L;
 
-                   {
-                       this.add(new CompositePathObject(new PCEPExplicitRouteObject(PCEPValidatorTest.this.eroSubobjects, false), lspa,
-                               new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
-                                   private static final long serialVersionUID = 1L;
+                       {
+                               this.add(new CompositePathObject(new PCEPExplicitRouteObject(PCEPValidatorTest.this.eroSubobjects, false), lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
+                                       private static final long serialVersionUID = 1L;
 
-                                   {
-                                       this.add(new PCEPMetricObject(true, true, new IGPMetric(234L), false, false));
-                                   }
+                                       {
+                                               this.add(new PCEPMetricObject(true, true, new IGPMetric(234L), false, false));
+                                       }
                                }, new PCEPIncludeRouteObject(PCEPValidatorTest.this.eroSubobjects, false, false)));
-                       this.add(new CompositePathObject(new PCEPExplicitRouteObject(PCEPValidatorTest.this.eroSubobjects, false), lspa,
-                               new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
-                                   private static final long serialVersionUID = 1L;
+                               this.add(new CompositePathObject(new PCEPExplicitRouteObject(PCEPValidatorTest.this.eroSubobjects, false), lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(500f), false, false), new ArrayList<PCEPMetricObject>() {
+                                       private static final long serialVersionUID = 1L;
 
-                                   {
-                                       this.add(new PCEPMetricObject(true, true, new IGPMetric(234L), false, false));
-                                   }
+                                       {
+                                               this.add(new PCEPMetricObject(true, true, new IGPMetric(234L), false, false));
+                                       }
                                }, new PCEPIncludeRouteObject(PCEPValidatorTest.this.eroSubobjects, false, false)));
-                   }
+                       }
                })), svecList));
-       assertEquals(deserMsg("src/test/resources/PCRep.5.bin"), specMessages);
-    }
-
-    @Test
-    public void testUpdMessageValidatorFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException, DeserializerException, DocumentedException {
-       List<PCEPMessage> specMessages = new ArrayList<PCEPMessage>();
-
-       List<CompositeUpdateRequestObject> requests = new ArrayList<CompositeUpdateRequestObject>();
-       requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true)));
-
-       specMessages.add(new PCEPUpdateRequestMessage(requests));
-       assertEquals(deserMsg("src/test/resources/PCUpd.1.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPMessage>();
-       List<CompositeUpdPathObject> paths = new ArrayList<CompositeUpdPathObject>();
-       paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, null, null));
-       requests = new ArrayList<CompositeUpdateRequestObject>();
-       requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true), paths));
-       specMessages.add(new PCEPUpdateRequestMessage(requests));
-       assertEquals(deserMsg("src/test/resources/PCUpd.2.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPMessage>();
-       paths = new ArrayList<CompositeUpdPathObject>();
-       paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+               assertEquals(deserMsg("src/test/resources/PCRep.5.bin"), specMessages);
+       }
+
+       @Test
+       public void testUpdMessageValidatorFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException,
+                       DeserializerException, DocumentedException {
+               List<PCEPMessage> specMessages = new ArrayList<PCEPMessage>();
+
+               List<CompositeUpdateRequestObject> requests = new ArrayList<CompositeUpdateRequestObject>();
+               requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true)));
+
+               specMessages.add(new PCEPUpdateRequestMessage(requests));
+               assertEquals(deserMsg("src/test/resources/PCUpd.1.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPMessage>();
+               List<CompositeUpdPathObject> paths = new ArrayList<CompositeUpdPathObject>();
+               paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, null, null));
+               requests = new ArrayList<CompositeUpdateRequestObject>();
+               requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true), paths));
+               specMessages.add(new PCEPUpdateRequestMessage(requests));
+               assertEquals(deserMsg("src/test/resources/PCUpd.2.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPMessage>();
+               paths = new ArrayList<CompositeUpdPathObject>();
+               paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
-       requests = new ArrayList<CompositeUpdateRequestObject>();
-       requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true), paths));
-       specMessages.add(new PCEPUpdateRequestMessage(requests));
-       assertEquals(deserMsg("src/test/resources/PCUpd.3.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPMessage>();
-       requests = new ArrayList<CompositeUpdateRequestObject>();
-       requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true)));
-       requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true)));
-       specMessages.add(new PCEPUpdateRequestMessage(requests));
-       assertEquals(deserMsg("src/test/resources/PCUpd.4.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPMessage>();
-       requests = new ArrayList<CompositeUpdateRequestObject>();
-       requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true)));
-       paths = new ArrayList<CompositeUpdPathObject>();
-       paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+               requests = new ArrayList<CompositeUpdateRequestObject>();
+               requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true), paths));
+               specMessages.add(new PCEPUpdateRequestMessage(requests));
+               assertEquals(deserMsg("src/test/resources/PCUpd.3.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPMessage>();
+               requests = new ArrayList<CompositeUpdateRequestObject>();
+               requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true)));
+               requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true)));
+               specMessages.add(new PCEPUpdateRequestMessage(requests));
+               assertEquals(deserMsg("src/test/resources/PCUpd.4.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPMessage>();
+               requests = new ArrayList<CompositeUpdateRequestObject>();
+               requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true)));
+               paths = new ArrayList<CompositeUpdPathObject>();
+               paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
-       requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true), paths));
-       paths = new ArrayList<CompositeUpdPathObject>();
-       paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+               requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true), paths));
+               paths = new ArrayList<CompositeUpdPathObject>();
+               paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
-       paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
+               paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
 
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
-       paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+               paths.add(new CompositeUpdPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPRequestedPathBandwidthObject(new Bandwidth(5353), false, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
-       requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true), paths));
-       specMessages.add(new PCEPUpdateRequestMessage(requests));
-       assertEquals(deserMsg("src/test/resources/PCUpd.5.bin"), specMessages);
-    }
-
-    @Test
-    public void testRptMessageValidatorFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException, DeserializerException, DocumentedException {
-       List<PCEPMessage> specMessages = new ArrayList<PCEPMessage>();
-       List<CompositeStateReportObject> reports = new ArrayList<CompositeStateReportObject>();
-       reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true)));
-       specMessages.add(new PCEPReportMessage(reports));
-       assertEquals(deserMsg("src/test/resources/PCRpt.1.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPMessage>();
-       List<CompositeRptPathObject> paths = new ArrayList<CompositeRptPathObject>();
-       paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, null, null, null));
-       reports = new ArrayList<CompositeStateReportObject>();
-       reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true), paths));
-       specMessages.add(new PCEPReportMessage(reports));
-       assertEquals(deserMsg("src/test/resources/PCRpt.2.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPMessage>();
-       paths = new ArrayList<CompositeRptPathObject>();
-       paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPReportedRouteObject(this.rroSubobjects, false),
-               new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+               requests.add(new CompositeUpdateRequestObject(new PCEPLspObject(1, true, false, true, true), paths));
+               specMessages.add(new PCEPUpdateRequestMessage(requests));
+               assertEquals(deserMsg("src/test/resources/PCUpd.5.bin"), specMessages);
+       }
+
+       @Test
+       public void testRptMessageValidatorFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException,
+                       DeserializerException, DocumentedException {
+               List<PCEPMessage> specMessages = new ArrayList<PCEPMessage>();
+               List<CompositeStateReportObject> reports = new ArrayList<CompositeStateReportObject>();
+               reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true)));
+               specMessages.add(new PCEPReportMessage(reports));
+               assertEquals(deserMsg("src/test/resources/PCRpt.1.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPMessage>();
+               List<CompositeRptPathObject> paths = new ArrayList<CompositeRptPathObject>();
+               paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, null, null, null));
+               reports = new ArrayList<CompositeStateReportObject>();
+               reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true), paths));
+               specMessages.add(new PCEPReportMessage(reports));
+               assertEquals(deserMsg("src/test/resources/PCRpt.2.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPMessage>();
+               paths = new ArrayList<CompositeRptPathObject>();
+               paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPReportedRouteObject(this.rroSubobjects, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
 
-       reports = new ArrayList<CompositeStateReportObject>();
-       reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true), paths));
-       specMessages.add(new PCEPReportMessage(reports));
-       //FIXME:
-       //assertEquals(deserMsg("src/test/resources/PCRpt.3.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPMessage>();
-       reports = new ArrayList<CompositeStateReportObject>();
-       reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true)));
-       reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true)));
-       reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true)));
-       specMessages.add(new PCEPReportMessage(reports));
-       assertEquals(deserMsg("src/test/resources/PCRpt.4.bin"), specMessages);
-
-       specMessages = new ArrayList<PCEPMessage>();
-       reports = new ArrayList<CompositeStateReportObject>();
-       paths = new ArrayList<CompositeRptPathObject>();
-       paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPReportedRouteObject(this.rroSubobjects, false),
-               new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+               reports = new ArrayList<CompositeStateReportObject>();
+               reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true), paths));
+               specMessages.add(new PCEPReportMessage(reports));
+               // FIXME:
+               // assertEquals(deserMsg("src/test/resources/PCRpt.3.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPMessage>();
+               reports = new ArrayList<CompositeStateReportObject>();
+               reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true)));
+               reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true)));
+               reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true)));
+               specMessages.add(new PCEPReportMessage(reports));
+               assertEquals(deserMsg("src/test/resources/PCRpt.4.bin"), specMessages);
+
+               specMessages = new ArrayList<PCEPMessage>();
+               reports = new ArrayList<CompositeStateReportObject>();
+               paths = new ArrayList<CompositeRptPathObject>();
+               paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPReportedRouteObject(this.rroSubobjects, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
-       reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true), paths));
-       paths = new ArrayList<CompositeRptPathObject>();
-       paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPReportedRouteObject(this.rroSubobjects, false),
-               new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+               reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true), paths));
+               paths = new ArrayList<CompositeRptPathObject>();
+               paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPReportedRouteObject(this.rroSubobjects, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
+               }));
+               paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa, new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPReportedRouteObject(this.rroSubobjects, false), new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
-       paths.add(new CompositeRptPathObject(new PCEPExplicitRouteObject(this.eroSubobjects, false), PCEPValidatorTest.lspa,
-               new PCEPExistingPathBandwidthObject(new Bandwidth(5353), false, false), new PCEPReportedRouteObject(this.rroSubobjects, false),
-               new ArrayList<PCEPMetricObject>() {
-                   private static final long serialVersionUID = 1L;
-
-                   {
-                       this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-                   }
+               reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true), paths));
+               specMessages.add(new PCEPReportMessage(reports));
+               // FIXME
+               // assertEquals(deserMsg("src/test/resources/PCRpt.5.bin"), specMessages);
+       }
+
+       @Test
+       public void testXRDeleteTunnelMessage() throws DeserializerException, DocumentedException, PCEPDeserializerException {
+               final PCEPXRDeleteTunnelMessage dTunnel = new PCEPXRDeleteTunnelMessage(new PCEPLspObject(1, false, true, false, true));
+               final byte[] bytes = this.msgFactory.put(dTunnel);
+
+               final PCEPRawMessage rawMessage = (PCEPRawMessage) this.msgFactory.parse(ByteArray.cutBytes(bytes, 1));
+
+               assertEquals(PCEPMessageValidator.getValidator(rawMessage.getMsgType()).validate(rawMessage.getAllObjects()),
+                               asList((PCEPMessage) dTunnel));
+       }
+
+       @Test
+       public void testXRAddTunnelMessage() throws DeserializerException, DocumentedException, PCEPDeserializerException {
+               final List<ExplicitRouteSubobject> subs = new ArrayList<ExplicitRouteSubobject>();
+               subs.add(new EROAsNumberSubobject(new ASNumber(10), false));
+               final PCEPXRAddTunnelMessage addTunnel = new PCEPXRAddTunnelMessage(new PCEPLspObject(1, false, false, false, false), new PCEPEndPointsObject<IPv4Address>(IPv4.FAMILY.addressForString("127.0.0.2"), IPv4.FAMILY.addressForString("127.0.0.1")), new PCEPExplicitRouteObject(subs, true));
+               final byte[] bytes = this.msgFactory.put(addTunnel);
+
+               final PCEPRawMessage rawMessage = (PCEPRawMessage) this.msgFactory.parse(ByteArray.cutBytes(bytes, 1));
+               assertEquals(PCEPMessageValidator.getValidator(rawMessage.getMsgType()).validate(rawMessage.getAllObjects()),
+                               asList((PCEPMessage) addTunnel));
+       }
+
+       @Test
+       public void testPCCreateMessage() throws DeserializerException, DocumentedException, PCEPDeserializerException {
+               final List<CompositeInstantiationObject> insts = new ArrayList<CompositeInstantiationObject>();
+               final List<ExplicitRouteSubobject> subs = new ArrayList<ExplicitRouteSubobject>();
+               subs.add(new EROAsNumberSubobject(new ASNumber(10), false));
+               final List<PCEPTlv> tlvs = new ArrayList<PCEPTlv>();
+               final LSPSymbolicNameTlv tlv = new LSPSymbolicNameTlv(new LSPSymbolicName(new byte[] { 5, 4 }));
+               tlvs.add(tlv);
+               insts.add(new CompositeInstantiationObject(new PCEPEndPointsObject<IPv4Address>(IPv4.FAMILY.addressForString("127.0.0.2"), IPv4.FAMILY.addressForString("127.0.0.1")), PCEPValidatorTest.lspa, new PCEPExplicitRouteObject(subs, true), null, new ArrayList<PCEPMetricObject>() {
+                       private static final long serialVersionUID = 1L;
+
+                       {
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
+                       }
                }));
-       reports.add(new CompositeStateReportObject(new PCEPLspObject(1, true, false, true, true), paths));
-       specMessages.add(new PCEPReportMessage(reports));
-       //FIXME
-       //assertEquals(deserMsg("src/test/resources/PCRpt.5.bin"), specMessages);
-    }
-
-    @Test
-    public void testXRDeleteTunnelMessage() throws DeserializerException, DocumentedException, PCEPDeserializerException {
-       final PCEPXRDeleteTunnelMessage dTunnel = new PCEPXRDeleteTunnelMessage(new PCEPLspObject(1, false, true, false, true));
-       final byte[] bytes = this.msgFactory.put(dTunnel);
-
-       final PCEPRawMessage rawMessage = (PCEPRawMessage) this.msgFactory.parse(ByteArray.cutBytes(bytes, PCEPMessageHeader.COMMON_HEADER_LENGTH),
-               new PCEPMessageHeader().fromBytes(Arrays.copyOf(bytes, PCEPMessageHeader.COMMON_HEADER_LENGTH)));
-
-       assertEquals(PCEPMessageValidator.getValidator(rawMessage.getMsgType()).validate(rawMessage.getAllObjects()), asList((PCEPMessage) dTunnel));
-    }
-
-    @Test
-    public void testXRAddTunnelMessage() throws DeserializerException, DocumentedException, PCEPDeserializerException {
-       final List<ExplicitRouteSubobject> subs = new ArrayList<ExplicitRouteSubobject>();
-       subs.add(new EROAsNumberSubobject(new ASNumber(10), false));
-       final PCEPXRAddTunnelMessage addTunnel = new PCEPXRAddTunnelMessage(new PCEPLspObject(1, false, false, false, false),
-               new PCEPEndPointsObject<IPv4Address>(IPv4.FAMILY.addressForString("127.0.0.2"), IPv4.FAMILY.addressForString("127.0.0.1")),
-               new PCEPExplicitRouteObject(subs, true));
-       final byte[] bytes = this.msgFactory.put(addTunnel);
-
-       final PCEPRawMessage rawMessage = (PCEPRawMessage) this.msgFactory.parse(ByteArray.cutBytes(bytes, PCEPMessageHeader.COMMON_HEADER_LENGTH),
-               new PCEPMessageHeader().fromBytes(Arrays.copyOf(bytes, PCEPMessageHeader.COMMON_HEADER_LENGTH)));
-       assertEquals(PCEPMessageValidator.getValidator(rawMessage.getMsgType()).validate(rawMessage.getAllObjects()), asList((PCEPMessage) addTunnel));
-    }
-
-    @Test
-    public void testPCCreateMessage() throws DeserializerException, DocumentedException, PCEPDeserializerException {
-       final List<CompositeInstantiationObject> insts = new ArrayList<CompositeInstantiationObject>();
-       final List<ExplicitRouteSubobject> subs = new ArrayList<ExplicitRouteSubobject>();
-       subs.add(new EROAsNumberSubobject(new ASNumber(10), false));
-       final List<PCEPTlv> tlvs = new ArrayList<PCEPTlv>();
-       final LSPSymbolicNameTlv tlv = new LSPSymbolicNameTlv(new LSPSymbolicName(new byte[] { 5, 4 }));
-       tlvs.add(tlv);
-       insts.add(new CompositeInstantiationObject(new PCEPEndPointsObject<IPv4Address>(IPv4.FAMILY.addressForString("127.0.0.2"),
-                       IPv4.FAMILY.addressForString("127.0.0.1")), PCEPValidatorTest.lspa, new PCEPExplicitRouteObject(subs, true), null, new ArrayList<PCEPMetricObject>() {
-           private static final long serialVersionUID = 1L;
-
-           {
-               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-               this.add(new PCEPMetricObject(true, false, new IGPMetric(4L), false, false));
-           }
-       }));
-       final PCCreateMessage msg = new PCCreateMessage(insts);
-
-       final byte[] bytes = this.msgFactory.put(msg);
-
-       // FIXME: need construct with invalid processed parameter
-       final PCEPRawMessage rawMessage = (PCEPRawMessage) this.msgFactory.parse(ByteArray.cutBytes(bytes, PCEPMessageHeader.COMMON_HEADER_LENGTH),
-               new PCEPMessageHeader().fromBytes(Arrays.copyOf(bytes, PCEPMessageHeader.COMMON_HEADER_LENGTH)));
-
-       assertEquals(PCEPMessageValidator.getValidator(rawMessage.getMsgType()).validate(rawMessage.getAllObjects()), asList((PCEPMessage) msg));
-    }
-
-    @Test
-    public void testNotificationValidatorFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException, DeserializerException, DocumentedException {
-       List<CompositeNotifyObject> notifications = new ArrayList<CompositeNotifyObject>();
-       List<PCEPNotificationObject> notificationsList = new ArrayList<PCEPNotificationObject>();
-       notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
-       notifications.add(new CompositeNotifyObject(notificationsList));
-       PCEPNotificationMessage specMessage = new PCEPNotificationMessage(notifications);
-       assertEquals(deserMsg("src/test/resources/PCNtf.1.bin"), asList((PCEPMessage) specMessage));
-
-       notifications = new ArrayList<CompositeNotifyObject>();
-       notificationsList = new ArrayList<PCEPNotificationObject>();
-       notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
-       List<PCEPRequestParameterObject> requestsList = new ArrayList<PCEPRequestParameterObject>();
-       requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false));
-       notifications.add(new CompositeNotifyObject(requestsList, notificationsList));
-       specMessage = new PCEPNotificationMessage(notifications);
-       assertEquals(deserMsg("src/test/resources/PCNtf.2.bin"), asList((PCEPMessage) specMessage));
-
-       notifications = new ArrayList<CompositeNotifyObject>();
-       notificationsList = new ArrayList<PCEPNotificationObject>();
-       notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
-       requestsList = new ArrayList<PCEPRequestParameterObject>();
-       requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 10, false, false));
-       notifications.add(new CompositeNotifyObject(requestsList, notificationsList));
-       specMessage = new PCEPNotificationMessage(notifications);
-       assertEquals(deserMsg("src/test/resources/PCNtf.3.bin"), asList((PCEPMessage) specMessage));
-
-       notifications = new ArrayList<CompositeNotifyObject>();
-       notificationsList = new ArrayList<PCEPNotificationObject>();
-       notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
-       notificationsList.add(new PCEPNotificationObject((short) 1, (short) 2));
-       notificationsList.add(new PCEPNotificationObject((short) 2, (short) 1));
-       notificationsList.add(new PCEPNotificationObject((short) 2, (short) 2));
-       notifications.add(new CompositeNotifyObject(notificationsList));
-       specMessage = new PCEPNotificationMessage(notifications);
-       assertEquals(deserMsg("src/test/resources/PCNtf.4.bin"), asList((PCEPMessage) specMessage));
-
-       notifications = new ArrayList<CompositeNotifyObject>();
-       notificationsList = new ArrayList<PCEPNotificationObject>();
-       notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
-       requestsList = new ArrayList<PCEPRequestParameterObject>();
-       requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 10, false, false));
-       notifications.add(new CompositeNotifyObject(requestsList, notificationsList));
-       notificationsList = new ArrayList<PCEPNotificationObject>();
-       notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
-       notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
-       requestsList = new ArrayList<PCEPRequestParameterObject>();
-       requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 10, false, false));
-       requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 10, false, false));
-       notifications.add(new CompositeNotifyObject(requestsList, notificationsList));
-       specMessage = new PCEPNotificationMessage(notifications);
-       assertEquals(deserMsg("src/test/resources/PCNtf.5.bin"), asList((PCEPMessage) specMessage));
-    }
-
-    @Test
-    public void testErrorMessageValidatoinFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException, DeserializerException, DocumentedException {
-       List<PCEPErrorObject> errorsList = new ArrayList<PCEPErrorObject>();
-       errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
-
-       PCEPErrorMessage specMessage = new PCEPErrorMessage(errorsList);
-       assertEquals(deserMsg("src/test/resources/PCErr.1.bin"), asList((PCEPMessage) specMessage));
-
-       List<PCEPRequestParameterObject> requests = new ArrayList<PCEPRequestParameterObject>();
-       requests.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false));
-
-       List<CompositeErrorObject> errors = new ArrayList<CompositeErrorObject>();
-       errors.add(new CompositeErrorObject(requests, errorsList));
-
-       specMessage = new PCEPErrorMessage(errors);
-       assertEquals(deserMsg("src/test/resources/PCErr.2.bin"), asList((PCEPMessage) specMessage));
-
-       specMessage = new PCEPErrorMessage(new PCEPOpenObject(0, 0, 0), errorsList, null);
-       assertEquals(deserMsg("src/test/resources/PCErr.3.bin"), asList((PCEPMessage) specMessage));
-
-       requests = new ArrayList<PCEPRequestParameterObject>();
-       requests.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 53, false, false));
-
-       errors = new ArrayList<CompositeErrorObject>();
-       errors.add(new CompositeErrorObject(requests, errorsList));
-
-       specMessage = new PCEPErrorMessage(errors);
-       assertEquals(deserMsg("src/test/resources/PCErr.3b.bin"), asList((PCEPMessage) specMessage));
-
-       errorsList = new ArrayList<PCEPErrorObject>();
-       errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
-       errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
-       errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
-
-       specMessage = new PCEPErrorMessage(null, errorsList, null);
-       assertEquals(deserMsg("src/test/resources/PCErr.4.bin"), asList((PCEPMessage) specMessage));
-
-       requests = new ArrayList<PCEPRequestParameterObject>();
-       requests.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 53, false, false));
-
-       errorsList = new ArrayList<PCEPErrorObject>();
-       errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
-
-       errors = new ArrayList<CompositeErrorObject>();
-       errors.add(new CompositeErrorObject(requests, errorsList));
-       errors.add(new CompositeErrorObject(requests, errorsList));
-
-       specMessage = new PCEPErrorMessage(errors);
-       assertEquals(deserMsg("src/test/resources/PCErr.5.bin"), asList((PCEPMessage) specMessage));
-    }
+               final PCCreateMessage msg = new PCCreateMessage(insts);
+
+               final byte[] bytes = this.msgFactory.put(msg);
+
+               // FIXME: need construct with invalid processed parameter
+               final PCEPRawMessage rawMessage = (PCEPRawMessage) this.msgFactory.parse(ByteArray.cutBytes(bytes, 1));
+
+               assertEquals(PCEPMessageValidator.getValidator(rawMessage.getMsgType()).validate(rawMessage.getAllObjects()),
+                               asList((PCEPMessage) msg));
+       }
+
+       @Test
+       public void testNotificationValidatorFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException,
+                       DeserializerException, DocumentedException {
+               List<CompositeNotifyObject> notifications = new ArrayList<CompositeNotifyObject>();
+               List<PCEPNotificationObject> notificationsList = new ArrayList<PCEPNotificationObject>();
+               notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
+               notifications.add(new CompositeNotifyObject(notificationsList));
+               PCEPNotificationMessage specMessage = new PCEPNotificationMessage(notifications);
+               assertEquals(deserMsg("src/test/resources/PCNtf.1.bin"), asList((PCEPMessage) specMessage));
+
+               notifications = new ArrayList<CompositeNotifyObject>();
+               notificationsList = new ArrayList<PCEPNotificationObject>();
+               notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
+               List<PCEPRequestParameterObject> requestsList = new ArrayList<PCEPRequestParameterObject>();
+               requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false));
+               notifications.add(new CompositeNotifyObject(requestsList, notificationsList));
+               specMessage = new PCEPNotificationMessage(notifications);
+               assertEquals(deserMsg("src/test/resources/PCNtf.2.bin"), asList((PCEPMessage) specMessage));
+
+               notifications = new ArrayList<CompositeNotifyObject>();
+               notificationsList = new ArrayList<PCEPNotificationObject>();
+               notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
+               requestsList = new ArrayList<PCEPRequestParameterObject>();
+               requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 10, false, false));
+               notifications.add(new CompositeNotifyObject(requestsList, notificationsList));
+               specMessage = new PCEPNotificationMessage(notifications);
+               assertEquals(deserMsg("src/test/resources/PCNtf.3.bin"), asList((PCEPMessage) specMessage));
+
+               notifications = new ArrayList<CompositeNotifyObject>();
+               notificationsList = new ArrayList<PCEPNotificationObject>();
+               notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
+               notificationsList.add(new PCEPNotificationObject((short) 1, (short) 2));
+               notificationsList.add(new PCEPNotificationObject((short) 2, (short) 1));
+               notificationsList.add(new PCEPNotificationObject((short) 2, (short) 2));
+               notifications.add(new CompositeNotifyObject(notificationsList));
+               specMessage = new PCEPNotificationMessage(notifications);
+               assertEquals(deserMsg("src/test/resources/PCNtf.4.bin"), asList((PCEPMessage) specMessage));
+
+               notifications = new ArrayList<CompositeNotifyObject>();
+               notificationsList = new ArrayList<PCEPNotificationObject>();
+               notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
+               requestsList = new ArrayList<PCEPRequestParameterObject>();
+               requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 10, false, false));
+               notifications.add(new CompositeNotifyObject(requestsList, notificationsList));
+               notificationsList = new ArrayList<PCEPNotificationObject>();
+               notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
+               notificationsList.add(new PCEPNotificationObject((short) 1, (short) 1));
+               requestsList = new ArrayList<PCEPRequestParameterObject>();
+               requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 10, false, false));
+               requestsList.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 10, false, false));
+               notifications.add(new CompositeNotifyObject(requestsList, notificationsList));
+               specMessage = new PCEPNotificationMessage(notifications);
+               assertEquals(deserMsg("src/test/resources/PCNtf.5.bin"), asList((PCEPMessage) specMessage));
+       }
+
+       @Test
+       public void testErrorMessageValidatoinFromBin() throws IOException, PCEPDeserializerException, PCEPDocumentedException,
+                       DeserializerException, DocumentedException {
+               List<PCEPErrorObject> errorsList = new ArrayList<PCEPErrorObject>();
+               errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
+
+               PCEPErrorMessage specMessage = new PCEPErrorMessage(errorsList);
+               assertEquals(deserMsg("src/test/resources/PCErr.1.bin"), asList((PCEPMessage) specMessage));
+
+               List<PCEPRequestParameterObject> requests = new ArrayList<PCEPRequestParameterObject>();
+               requests.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 3, 1, false, false));
+
+               List<CompositeErrorObject> errors = new ArrayList<CompositeErrorObject>();
+               errors.add(new CompositeErrorObject(requests, errorsList));
+
+               specMessage = new PCEPErrorMessage(errors);
+               assertEquals(deserMsg("src/test/resources/PCErr.2.bin"), asList((PCEPMessage) specMessage));
+
+               specMessage = new PCEPErrorMessage(new PCEPOpenObject(0, 0, 0), errorsList, null);
+               assertEquals(deserMsg("src/test/resources/PCErr.3.bin"), asList((PCEPMessage) specMessage));
+
+               requests = new ArrayList<PCEPRequestParameterObject>();
+               requests.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 53, false, false));
+
+               errors = new ArrayList<CompositeErrorObject>();
+               errors.add(new CompositeErrorObject(requests, errorsList));
+
+               specMessage = new PCEPErrorMessage(errors);
+               assertEquals(deserMsg("src/test/resources/PCErr.3b.bin"), asList((PCEPMessage) specMessage));
+
+               errorsList = new ArrayList<PCEPErrorObject>();
+               errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
+               errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
+               errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
+
+               specMessage = new PCEPErrorMessage(null, errorsList, null);
+               assertEquals(deserMsg("src/test/resources/PCErr.4.bin"), asList((PCEPMessage) specMessage));
+
+               requests = new ArrayList<PCEPRequestParameterObject>();
+               requests.add(new PCEPRequestParameterObject(true, false, false, false, false, false, false, false, (short) 1, 53, false, false));
+
+               errorsList = new ArrayList<PCEPErrorObject>();
+               errorsList.add(new PCEPErrorObject(PCEPErrors.UNRECOGNIZED_OBJ_CLASS));
+
+               errors = new ArrayList<CompositeErrorObject>();
+               errors.add(new CompositeErrorObject(requests, errorsList));
+               errors.add(new CompositeErrorObject(requests, errorsList));
+
+               specMessage = new PCEPErrorMessage(errors);
+               assertEquals(deserMsg("src/test/resources/PCErr.5.bin"), asList((PCEPMessage) specMessage));
+       }
 }
index 7f72e0788c8cc94dd0136183c01973f357d12d1a..1f15a1809a5354dcbe5e21f6993ad80caf421ec4 100644 (file)
@@ -7,6 +7,11 @@
  */
 package org.opendaylight.protocol.pcep.impl;
 
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.util.Timer;
+
 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
 import org.opendaylight.protocol.pcep.PCEPConnection;
 import org.opendaylight.protocol.pcep.PCEPMessage;
@@ -16,11 +21,6 @@ import org.opendaylight.protocol.pcep.PCEPSessionProposalChecker;
 import org.opendaylight.protocol.pcep.object.PCEPCloseObject.Reason;
 import org.opendaylight.protocol.pcep.object.PCEPOpenObject;
 
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.Timer;
-
 public class ServerSessionMock extends PCEPSessionImpl {
 
        private final MockPCE client;
@@ -51,7 +51,7 @@ public class ServerSessionMock extends PCEPSessionImpl {
                        public PCEPSessionProposalChecker getProposalChecker() {
                                return new SimpleSessionProposalChecker();
                        }
-               }, new PCEPMessageFactory(), 5, 30);
+               }, new PCEPMessageFactory(), 5, 30, null);
                this.client = (MockPCE) client;
        }
 
index 7bd16b0137a84a6d52da30fe5889536c4c1873fb..2ec8987b5a4f2d2caf96a0c8de60fd648ab1849e 100644 (file)
@@ -7,6 +7,10 @@
  */
 package org.opendaylight.protocol.pcep.testtool;
 
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+
 import org.opendaylight.protocol.framework.DispatcherImpl;
 import org.opendaylight.protocol.pcep.PCEPConnection;
 import org.opendaylight.protocol.pcep.PCEPConnectionFactory;
@@ -18,14 +22,10 @@ import org.opendaylight.protocol.pcep.PCEPSessionProposalCheckerFactory;
 import org.opendaylight.protocol.pcep.PCEPSessionProposalFactory;
 import org.opendaylight.protocol.pcep.impl.PCEPConnectionImpl;
 import org.opendaylight.protocol.pcep.impl.PCEPDispatcherImpl;
+import org.opendaylight.protocol.pcep.impl.PCEPMessageFactory;
 import org.opendaylight.protocol.pcep.impl.PCEPSessionProposalCheckerFactoryImpl;
 import org.opendaylight.protocol.pcep.impl.PCEPSessionProposalFactoryImpl;
 
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.concurrent.Executors;
-
 public class Main {
 
        public static String usage = "DESCRIPTION:\n" + "\tCreates a server with given parameters. As long as it runs, it accepts connections "
@@ -140,7 +140,7 @@ public class Main {
 
                final PCEPSessionProposal prefs = spf.getSessionProposal(address, 0);
 
-               final DispatcherImpl d = new DispatcherImpl(Executors.defaultThreadFactory());
+               final DispatcherImpl d = new DispatcherImpl(new PCEPMessageFactory());
                final PCEPDispatcherImpl dispatcher = new PCEPDispatcherImpl(d, spf);
 
                try {
@@ -169,7 +169,7 @@ public class Main {
 
                } finally {
                        ((PCEPSessionProposalCheckerFactoryImpl) spcf).close();
-                       d.stop();
+                       // d.stop();
                }
        }
 }
index 8236bae2d39b2cbc73eb8fcf191fa859d001bd8a..6c33111c8855b5721f2e46df45e37ae1fd383301 100644 (file)
@@ -7,6 +7,10 @@
  */
 package org.opendaylight.protocol.pcep.testtool;
 
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.List;
+
 import org.opendaylight.protocol.framework.DispatcherImpl;
 import org.opendaylight.protocol.framework.SessionPreferences;
 import org.opendaylight.protocol.pcep.PCEPConnection;
@@ -17,14 +21,11 @@ import org.opendaylight.protocol.pcep.PCEPSessionProposalChecker;
 import org.opendaylight.protocol.pcep.PCEPSessionProposalFactory;
 import org.opendaylight.protocol.pcep.PCEPTlv;
 import org.opendaylight.protocol.pcep.impl.PCEPDispatcherImpl;
+import org.opendaylight.protocol.pcep.impl.PCEPMessageFactory;
 import org.opendaylight.protocol.pcep.object.PCEPOpenObject;
 import org.opendaylight.protocol.pcep.tlv.NodeIdentifierTlv;
-import com.google.common.collect.Lists;
 
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.List;
-import java.util.concurrent.Executors;
+import com.google.common.collect.Lists;
 
 public class PCCMock {
 
@@ -32,7 +33,7 @@ public class PCCMock {
                final List<PCEPTlv> tlvs = Lists.newArrayList();
                tlvs.add(new NodeIdentifierTlv(new byte[] { (byte) 127, (byte) 2, (byte) 3, (byte) 7 }));
                final PCEPSessionPreferences prop = new PCEPSessionPreferences(new PCEPOpenObject(30, 120, 0, tlvs));
-               final DispatcherImpl di = new DispatcherImpl(Executors.defaultThreadFactory());
+               final DispatcherImpl di = new DispatcherImpl(new PCEPMessageFactory());
                final PCEPDispatcherImpl d = new PCEPDispatcherImpl(di, new PCEPSessionProposalFactory() {
 
                        @Override
@@ -96,7 +97,7 @@ public class PCCMock {
                        // Thread.sleep(1000);
 
                } finally {
-                       di.stop();
+                       // di.stop();
                }
        }
 }