KeyMapping is immutable 71/98571/6
authorRobert Varga <robert.varga@pantheon.tech>
Tue, 16 Nov 2021 12:16:00 +0000 (13:16 +0100)
committerRobert Varga <robert.varga@pantheon.tech>
Wed, 17 Nov 2021 04:53:39 +0000 (05:53 +0100)
This core concept should be immutable and protect its byte[] from
modification. This allows us to reason about its lifecycle.

JIRA: BGPCEP-983
Change-Id: I63c6a377ff1b62f058fd2bfb4c7e0ff07f8a2516
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
25 files changed:
bgp/peer-acceptor/src/main/java/org/opendaylight/protocol/bgp/peer/acceptor/BGPPeerAcceptorImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPDispatcherImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeer.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtil.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/BGPDispatcherImplTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtilTest.java
bmp/bmp-impl/src/main/java/org/opendaylight/protocol/bmp/impl/BmpDispatcherUtil.java
bmp/bmp-impl/src/main/java/org/opendaylight/protocol/bmp/impl/app/BmpMonitoringStationImpl.java
bmp/bmp-impl/src/main/java/org/opendaylight/protocol/bmp/impl/app/KeyConstructorUtil.java [deleted file]
bmp/bmp-impl/src/test/java/org/opendaylight/protocol/bmp/impl/session/BmpDispatcherImplTest.java
bmp/bmp-mock/src/main/java/org/opendaylight/protocol/bmp/mock/BmpMockDispatcher.java
bmp/bmp-mock/src/test/java/org/opendaylight/protocol/bmp/mock/BmpMockDispatcherTest.java
bmp/bmp-mock/src/test/java/org/opendaylight/protocol/bmp/mock/BmpMockTest.java
concepts/src/main/java/org/opendaylight/protocol/concepts/KeyMapping.java
pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPDispatcherImpl.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/PCEPDispatcherImplTest.java
pcep/pcc-mock/src/main/java/org/opendaylight/protocol/pcep/pcc/mock/PCCsBuilder.java
pcep/pcc-mock/src/main/java/org/opendaylight/protocol/pcep/pcc/mock/protocol/PCCDispatcherImpl.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCDispatcherImplTest.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCMockCommon.java
pcep/testtool/src/main/java/org/opendaylight/protocol/pcep/testtool/TestToolPCEPDispatcherDependencies.java
pcep/testtool/src/test/java/org/opendaylight/protocol/pcep/testtool/PCCMock.java
pcep/topology/topology-provider/src/main/java/org/opendaylight/bgpcep/pcep/topology/provider/config/PCEPTopologyConfiguration.java
pcep/topology/topology-provider/src/main/java/org/opendaylight/bgpcep/pcep/topology/provider/config/PCEPTopologyProviderUtil.java [deleted file]
pcep/topology/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/AbstractPCEPSessionTest.java

index 540dc5ccb96bf69bc80dfef19739bd0718183641..a8188b42a9854b8e322b5fe1153243d675477be9 100644 (file)
@@ -21,10 +21,11 @@ import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.UnknownHostException;
 import java.security.AccessControlException;
+import java.util.HashMap;
+import java.util.Map;
 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.PeerRegistryListener;
-import org.opendaylight.protocol.concepts.KeyMapping;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
@@ -42,7 +43,7 @@ public final class BGPPeerAcceptorImpl implements AutoCloseable {
     public BGPPeerAcceptorImpl(final IpAddressNoZone bindingAddress, final PortNumber portNumber,
             final BGPDispatcher bgpDispatcher) {
         this.bgpDispatcher = requireNonNull(bgpDispatcher);
-        this.address = getAddress(requireNonNull(bindingAddress), requireNonNull(portNumber));
+        address = getAddress(requireNonNull(bindingAddress), requireNonNull(portNumber));
         if (!PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()
                 && portNumber.getValue().toJava() < PRIVILEGED_PORTS) {
             throw new AccessControlException("Unable to bind port " + portNumber.getValue()
@@ -51,16 +52,16 @@ public final class BGPPeerAcceptorImpl implements AutoCloseable {
     }
 
     public void start() {
-        LOG.debug("Instantiating BGP Peer Acceptor : {}", this.address);
+        LOG.debug("Instantiating BGP Peer Acceptor : {}", address);
 
-        this.futureChannel = this.bgpDispatcher.createServer(this.address);
+        futureChannel = bgpDispatcher.createServer(address);
         // Validate future success
-        this.futureChannel.addListener(future -> {
+        futureChannel.addListener(future -> {
             Preconditions.checkArgument(future.isSuccess(), "Unable to start bgp server on %s",
-                this.address, future.cause());
-            final Channel channel = this.futureChannel.channel();
+                address, future.cause());
+            final Channel channel = futureChannel.channel();
             if (Epoll.isAvailable()) {
-                this.listenerRegistration = this.bgpDispatcher.getBGPPeerRegistry().registerPeerRegisterListener(
+                listenerRegistration = bgpDispatcher.getBGPPeerRegistry().registerPeerRegisterListener(
                     new BGPPeerAcceptorImpl.PeerRegistryListenerImpl(channel.config()));
             }
         });
@@ -83,34 +84,33 @@ public final class BGPPeerAcceptorImpl implements AutoCloseable {
      **/
     @Override
     public void close() throws Exception {
-        this.futureChannel.cancel(true);
-        this.futureChannel.channel().close();
-        if (this.listenerRegistration != null) {
-            this.listenerRegistration.close();
+        futureChannel.cancel(true);
+        futureChannel.channel().close();
+        if (listenerRegistration != null) {
+            listenerRegistration.close();
         }
     }
 
     private static final class PeerRegistryListenerImpl implements PeerRegistryListener {
+        private final Map<InetAddress, byte[]> keys = new HashMap<>();
         private final ChannelConfig channelConfig;
-        private final KeyMapping keys;
 
         PeerRegistryListenerImpl(final ChannelConfig channelConfig) {
             this.channelConfig = channelConfig;
-            this.keys = KeyMapping.getKeyMapping();
         }
 
         @Override
         public void onPeerAdded(final IpAddressNoZone ip, final BGPSessionPreferences prefs) {
-            if (prefs.getMd5Password().isPresent()) {
-                this.keys.put(IetfInetUtil.INSTANCE.inetAddressForNoZone(ip), prefs.getMd5Password().get());
-                this.channelConfig.setOption(EpollChannelOption.TCP_MD5SIG, this.keys);
-            }
+            prefs.getMd5Password().ifPresent(password -> {
+                keys.put(IetfInetUtil.INSTANCE.inetAddressForNoZone(ip), password);
+                channelConfig.setOption(EpollChannelOption.TCP_MD5SIG, keys);
+            });
         }
 
         @Override
         public void onPeerRemoved(final IpAddressNoZone ip) {
-            if (this.keys.remove(IetfInetUtil.INSTANCE.inetAddressForNoZone(ip)) != null) {
-                this.channelConfig.setOption(EpollChannelOption.TCP_MD5SIG, this.keys);
+            if (keys.remove(IetfInetUtil.INSTANCE.inetAddressForNoZone(ip)) != null) {
+                channelConfig.setOption(EpollChannelOption.TCP_MD5SIG, keys);
             }
         }
     }
index ad820776b246f65cb9486ba1e65c452698643266..0aa3bd6d230b1fc0076dea1f143081a2383ccf7f 100644 (file)
@@ -92,19 +92,19 @@ public final class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
             this.workerGroup = requireNonNull(workerGroup);
         }
         this.bgpPeerRegistry = requireNonNull(bgpPeerRegistry);
-        this.handlerFactory = new BGPHandlerFactory(extensions.getMessageRegistry());
+        handlerFactory = new BGPHandlerFactory(extensions.getMessageRegistry());
     }
 
     @VisibleForTesting
     public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress localAddress,
             final InetSocketAddress remoteAddress, final int retryTimer, final boolean reuseAddress) {
-        final Bootstrap clientBootStrap = createClientBootStrap(KeyMapping.getKeyMapping(), reuseAddress, localAddress);
-        final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(this.bgpPeerRegistry);
+        final Bootstrap clientBootStrap = createClientBootStrap(KeyMapping.of(), reuseAddress, localAddress);
+        final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(bgpPeerRegistry);
         final ChannelPipelineInitializer<BGPSessionImpl> initializer = BGPChannel.createChannelPipelineInitializer(
-                this.handlerFactory, snf);
+                handlerFactory, snf);
 
         final BGPProtocolSessionPromise<BGPSessionImpl> sessionPromise = new BGPProtocolSessionPromise<>(remoteAddress,
-                retryTimer, clientBootStrap, this.bgpPeerRegistry);
+                retryTimer, clientBootStrap, bgpPeerRegistry);
         clientBootStrap.handler(BGPChannel.createClientChannelHandler(initializer, sessionPromise));
         sessionPromise.connect();
         LOG.debug("Client created.");
@@ -122,7 +122,7 @@ public final class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
         }
         if (keys != null && !keys.isEmpty()) {
             if (Epoll.isAvailable()) {
-                bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
+                bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
             } else {
                 throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
             }
@@ -135,7 +135,7 @@ public final class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
         bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
 
         if (bootstrap.config().group() == null) {
-            bootstrap.group(this.workerGroup);
+            bootstrap.group(workerGroup);
         }
         bootstrap.localAddress(localAddress);
 
@@ -148,8 +148,8 @@ public final class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
     public synchronized void close() {
         if (Epoll.isAvailable()) {
             LOG.debug("Closing Dispatcher");
-            this.workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
-            this.bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+            workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+            bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
         }
     }
 
@@ -163,20 +163,20 @@ public final class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
     synchronized Future<Void> createReconnectingClient(final InetSocketAddress remoteAddress,
             final int retryTimer, final KeyMapping keys, final InetSocketAddress localAddress,
             final boolean reuseAddress) {
-        final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(this.bgpPeerRegistry);
+        final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(bgpPeerRegistry);
         final Bootstrap bootstrap = createClientBootStrap(keys, reuseAddress, localAddress);
         final BGPReconnectPromise<?> reconnectPromise = new BGPReconnectPromise<>(GlobalEventExecutor.INSTANCE,
-                remoteAddress, retryTimer, bootstrap, this.bgpPeerRegistry,
-                BGPChannel.createChannelPipelineInitializer(this.handlerFactory, snf));
+                remoteAddress, retryTimer, bootstrap, bgpPeerRegistry,
+                BGPChannel.createChannelPipelineInitializer(handlerFactory, snf));
         reconnectPromise.connect();
         return reconnectPromise;
     }
 
     @Override
     public synchronized ChannelFuture createServer(final InetSocketAddress serverAddress) {
-        final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(this.bgpPeerRegistry);
+        final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(bgpPeerRegistry);
         final ChannelPipelineInitializer<?> initializer = BGPChannel.createChannelPipelineInitializer(
-            this.handlerFactory, snf);
+            handlerFactory, snf);
         final ServerBootstrap serverBootstrap = createServerBootstrap(initializer);
         final ChannelFuture channelFuture = serverBootstrap.bind(serverAddress);
         LOG.debug("Initiated server {} at {}.", channelFuture, serverAddress);
@@ -185,7 +185,7 @@ public final class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
 
     @Override
     public BGPPeerRegistry getBGPPeerRegistry() {
-        return this.bgpPeerRegistry;
+        return bgpPeerRegistry;
     }
 
     private synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer<?> initializer) {
@@ -207,7 +207,7 @@ public final class BGPDispatcherImpl implements BGPDispatcher, AutoCloseable {
         serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, RECV_ALLOCATOR);
 
         if (serverBootstrap.config().group() == null) {
-            serverBootstrap.group(this.bossGroup, this.workerGroup);
+            serverBootstrap.group(bossGroup, workerGroup);
         }
         return serverBootstrap;
     }
index 187a0385c4997df8be59da916caafae6255f0ca2..10c4766a6c9de5573da369021d8d215cbc3c011e 100644 (file)
@@ -134,104 +134,95 @@ public class BgpPeer implements PeerBean, BGPPeerStateProvider {
         return caps;
     }
 
-    @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
-            justification = "https://github.com/spotbugs/spotbugs/issues/811")
-    private static Optional<byte[]> getPassword(final KeyMapping key) {
-        if (key != null) {
-            return Optional.of(Iterables.getOnlyElement(key.values()));
-        }
-        return Optional.empty();
-    }
-
     @Override
     public synchronized void start(final RIB rib, final Neighbor neighbor, final InstanceIdentifier<Bgp> bgpIid,
             final PeerGroupConfigLoader peerGroupLoader, final BGPTableTypeRegistryConsumer tableTypeRegistry) {
-        Preconditions.checkState(this.bgpPeerSingletonService == null,
+        Preconditions.checkState(bgpPeerSingletonService == null,
                 "Previous peer instance was not closed.");
 
-        this.bgpPeerSingletonService = new BgpPeerSingletonService(rib, neighbor, bgpIid, peerGroupLoader,
+        bgpPeerSingletonService = new BgpPeerSingletonService(rib, neighbor, bgpIid, peerGroupLoader,
                 tableTypeRegistry);
-        this.currentConfiguration = neighbor;
-        this.stateProviderRegistration = this.stateProviderRegistry.register(this);
+        currentConfiguration = neighbor;
+        stateProviderRegistration = stateProviderRegistry.register(this);
     }
 
     @Override
     public synchronized void restart(final RIB rib, final InstanceIdentifier<Bgp> bgpIid,
             final PeerGroupConfigLoader peerGroupLoader, final BGPTableTypeRegistryConsumer tableTypeRegistry) {
-        Preconditions.checkState(this.currentConfiguration != null);
-        if (this.bgpPeerSingletonService != null) {
-            this.bgpPeerSingletonService.closeServiceInstance();
-            this.bgpPeerSingletonService = null;
+        Preconditions.checkState(currentConfiguration != null);
+        if (bgpPeerSingletonService != null) {
+            bgpPeerSingletonService.closeServiceInstance();
+            bgpPeerSingletonService = null;
         }
-        start(rib, this.currentConfiguration, bgpIid, peerGroupLoader, tableTypeRegistry);
+        start(rib, currentConfiguration, bgpIid, peerGroupLoader, tableTypeRegistry);
     }
 
     @Override
     public synchronized void close() {
-        if (this.bgpPeerSingletonService != null) {
-            this.bgpPeerSingletonService.closeServiceInstance();
-            this.bgpPeerSingletonService = null;
+        if (bgpPeerSingletonService != null) {
+            bgpPeerSingletonService.closeServiceInstance();
+            bgpPeerSingletonService = null;
         }
-        if (this.stateProviderRegistration != null) {
-            this.stateProviderRegistration.close();
-            this.stateProviderRegistration = null;
+        if (stateProviderRegistration != null) {
+            stateProviderRegistration.close();
+            stateProviderRegistration = null;
         }
     }
 
     @Override
     public synchronized void instantiateServiceInstance() {
-        if (this.bgpPeerSingletonService != null) {
-            this.bgpPeerSingletonService.instantiateServiceInstance();
+        if (bgpPeerSingletonService != null) {
+            bgpPeerSingletonService.instantiateServiceInstance();
         }
     }
 
     @Override
     public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
-        if (this.bgpPeerSingletonService != null) {
-            return this.bgpPeerSingletonService.closeServiceInstance();
+        if (bgpPeerSingletonService != null) {
+            return bgpPeerSingletonService.closeServiceInstance();
         }
         return CommitInfo.emptyFluentFuture();
     }
 
     @Override
     public synchronized Boolean containsEqualConfiguration(final Neighbor neighbor) {
-        if (this.currentConfiguration == null) {
+        if (currentConfiguration == null) {
             return false;
         }
-        final AfiSafis actAfiSafi = this.currentConfiguration.getAfiSafis();
+        final AfiSafis actAfiSafi = currentConfiguration.getAfiSafis();
         final AfiSafis extAfiSafi = neighbor.getAfiSafis();
         final Collection<AfiSafi> actualSafi = actAfiSafi != null ? actAfiSafi.nonnullAfiSafi().values()
                 : Collections.emptyList();
         final Collection<AfiSafi> extSafi = extAfiSafi != null ? extAfiSafi.nonnullAfiSafi().values()
                 : Collections.emptyList();
         return actualSafi.containsAll(extSafi) && extSafi.containsAll(actualSafi)
-                && Objects.equals(this.currentConfiguration.getConfig(), neighbor.getConfig())
-                && Objects.equals(this.currentConfiguration.getNeighborAddress(), neighbor.getNeighborAddress())
-                && Objects.equals(this.currentConfiguration.getAddPaths(), neighbor.getAddPaths())
-                && Objects.equals(this.currentConfiguration.getApplyPolicy(), neighbor.getApplyPolicy())
-                && Objects.equals(this.currentConfiguration.getAsPathOptions(), neighbor.getAsPathOptions())
-                && Objects.equals(this.currentConfiguration.getEbgpMultihop(), neighbor.getEbgpMultihop())
-                && Objects.equals(this.currentConfiguration.getGracefulRestart(), neighbor.getGracefulRestart())
-                && Objects.equals(this.currentConfiguration.getErrorHandling(), neighbor.getErrorHandling())
-                && Objects.equals(this.currentConfiguration.getLoggingOptions(), neighbor.getLoggingOptions())
-                && Objects.equals(this.currentConfiguration.getRouteReflector(), neighbor.getRouteReflector())
-                && Objects.equals(this.currentConfiguration.getState(), neighbor.getState())
-                && Objects.equals(this.currentConfiguration.getTimers(), neighbor.getTimers())
-                && Objects.equals(this.currentConfiguration.getTransport(), neighbor.getTransport());
+                && Objects.equals(currentConfiguration.getConfig(), neighbor.getConfig())
+                && Objects.equals(currentConfiguration.getNeighborAddress(), neighbor.getNeighborAddress())
+                && Objects.equals(currentConfiguration.getAddPaths(), neighbor.getAddPaths())
+                && Objects.equals(currentConfiguration.getApplyPolicy(), neighbor.getApplyPolicy())
+                && Objects.equals(currentConfiguration.getAsPathOptions(), neighbor.getAsPathOptions())
+                && Objects.equals(currentConfiguration.getEbgpMultihop(), neighbor.getEbgpMultihop())
+                && Objects.equals(currentConfiguration.getGracefulRestart(), neighbor.getGracefulRestart())
+                && Objects.equals(currentConfiguration.getErrorHandling(), neighbor.getErrorHandling())
+                && Objects.equals(currentConfiguration.getLoggingOptions(), neighbor.getLoggingOptions())
+                && Objects.equals(currentConfiguration.getRouteReflector(), neighbor.getRouteReflector())
+                && Objects.equals(currentConfiguration.getState(), neighbor.getState())
+                && Objects.equals(currentConfiguration.getTimers(), neighbor.getTimers())
+                && Objects.equals(currentConfiguration.getTransport(), neighbor.getTransport());
     }
 
     @Override
     public synchronized BGPPeerState getPeerState() {
-        if (this.bgpPeerSingletonService == null) {
+        if (bgpPeerSingletonService == null) {
             return null;
         }
-        return this.bgpPeerSingletonService.getPeerState();
+        return bgpPeerSingletonService.getPeerState();
     }
 
     synchronized void removePeer(final BGPPeerRegistry bgpPeerRegistry) {
-        if (this.currentConfiguration != null) {
+        if (currentConfiguration != null) {
             bgpPeerRegistry.removePeer(OpenConfigMappingUtil.convertIpAddress(
-                this.currentConfiguration.getNeighborAddress()));
+                currentConfiguration.getNeighborAddress()));
         }
     }
 
@@ -254,7 +245,7 @@ public class BgpPeer implements PeerBean, BGPPeerStateProvider {
 
         private BgpPeerSingletonService(final RIB rib, final Neighbor neighbor, final InstanceIdentifier<Bgp> bgpIid,
                 final PeerGroupConfigLoader peerGroupLoader, final BGPTableTypeRegistryConsumer tableTypeRegistry) {
-            this.neighborAddress = OpenConfigMappingUtil.convertIpAddress(neighbor.getNeighborAddress());
+            neighborAddress = OpenConfigMappingUtil.convertIpAddress(neighbor.getNeighborAddress());
 
             PeerGroup peerGroup = null;
             String peerGroupName = null;
@@ -280,13 +271,12 @@ public class BgpPeer implements PeerBean, BGPPeerStateProvider {
             final ClusterIdentifier clusterId = OpenConfigMappingUtil
                     .getNeighborClusterIdentifier(neighbor.getRouteReflector(), peerGroup);
             final int hold = OpenConfigMappingUtil.getHoldTimer(neighbor, peerGroup);
-            this.gracefulRestartTimer = OpenConfigMappingUtil.getGracefulRestartTimer(neighbor,
-                    peerGroup, hold);
+            gracefulRestartTimer = OpenConfigMappingUtil.getGracefulRestartTimer(neighbor, peerGroup, hold);
             final Set<TablesKey> gracefulTables = GracefulRestartUtil.getGracefulTables(
                 afisSafis.nonnullAfiSafi().values(), tableTypeRegistry);
             final Map<TablesKey, Integer> llGracefulTimers = GracefulRestartUtil.getLlGracefulTimers(
                 afisSafis.nonnullAfiSafi().values(), tableTypeRegistry);
-            this.finalCapabilities = getBgpCapabilities(afisSafis, rib, tableTypeRegistry);
+            finalCapabilities = getBgpCapabilities(afisSafis, rib, tableTypeRegistry);
             final List<BgpParameters> bgpParameters = getInitialBgpParameters(gracefulTables, llGracefulTimers);
             final KeyMapping keyMapping = OpenConfigMappingUtil.getNeighborKey(neighbor);
             final IpAddressNoZone neighborLocalAddress = OpenConfigMappingUtil.getLocalAddress(neighbor.getTransport());
@@ -300,24 +290,26 @@ public class BgpPeer implements PeerBean, BGPPeerStateProvider {
                 neighborLocalAs = globalAs;
             }
 
-            this.errorHandling = OpenConfigMappingUtil.getRevisedErrorHandling(role, peerGroup, neighbor);
-            this.bgpPeer = new BGPPeer(tableTypeRegistry, this.neighborAddress, peerGroupName, rib, role, clusterId,
-                    neighborLocalAs, BgpPeer.this.rpcRegistry, afiSafisAdvertized, gracefulTables, llGracefulTimers,
+            errorHandling = OpenConfigMappingUtil.getRevisedErrorHandling(role, peerGroup, neighbor);
+            bgpPeer = new BGPPeer(tableTypeRegistry, neighborAddress, peerGroupName, rib, role, clusterId,
+                    neighborLocalAs, rpcRegistry, afiSafisAdvertized, gracefulTables, llGracefulTimers,
                     BgpPeer.this);
-            this.prefs = new BGPSessionPreferences(neighborLocalAs, hold, rib.getBgpIdentifier(),
-                    neighborRemoteAs, bgpParameters, getPassword(keyMapping));
-            this.activeConnection = OpenConfigMappingUtil.isActive(neighbor, peerGroup);
-            this.retryTimer = OpenConfigMappingUtil.getRetryTimer(neighbor, peerGroup);
-            this.dispatcher = rib.getDispatcher();
+            prefs = new BGPSessionPreferences(neighborLocalAs, hold, rib.getBgpIdentifier(),
+                    neighborRemoteAs, bgpParameters,
+                    keyMapping == null ? Optional.empty()
+                        : Optional.of(Iterables.getOnlyElement(keyMapping.asMap().values())));
+            activeConnection = OpenConfigMappingUtil.isActive(neighbor, peerGroup);
+            retryTimer = OpenConfigMappingUtil.getRetryTimer(neighbor, peerGroup);
+            dispatcher = rib.getDispatcher();
 
             final PortNumber port = OpenConfigMappingUtil.getPort(neighbor, peerGroup);
-            this.inetAddress = Ipv4Util.toInetSocketAddress(this.neighborAddress, port);
+            inetAddress = Ipv4Util.toInetSocketAddress(neighborAddress, port);
             if (neighborLocalAddress != null) {
-                this.localAddress = Ipv4Util.toInetSocketAddress(neighborLocalAddress, port);
+                localAddress = Ipv4Util.toInetSocketAddress(neighborLocalAddress, port);
             } else {
-                this.localAddress = null;
+                localAddress = null;
             }
-            this.keys = keyMapping;
+            keys = keyMapping;
         }
 
         private List<BgpParameters> getInitialBgpParameters(final Set<TablesKey> gracefulTables,
@@ -326,56 +318,55 @@ public class BgpPeer implements PeerBean, BGPPeerStateProvider {
                     .map(entry -> new BgpPeerUtil.LlGracefulRestartDTO(entry.getKey(), entry.getValue(), false))
                     .collect(Collectors.toSet());
             return Collections.singletonList(
-                    GracefulRestartUtil.getGracefulBgpParameters(this.finalCapabilities, gracefulTables,
+                    GracefulRestartUtil.getGracefulBgpParameters(finalCapabilities, gracefulTables,
                             Collections.emptySet(), gracefulRestartTimer, false, llGracefulRestarts));
         }
 
         synchronized void instantiateServiceInstance() {
             if (isServiceInstantiated) {
-                LOG.warn("Peer {} has already been instantiated", this.neighborAddress);
+                LOG.warn("Peer {} has already been instantiated", neighborAddress);
                 return;
             }
-            this.isServiceInstantiated = true;
-            LOG.info("Peer instantiated {}", this.neighborAddress);
-            this.bgpPeer.instantiateServiceInstance();
-            this.dispatcher.getBGPPeerRegistry().addPeer(this.neighborAddress, this.bgpPeer, this.prefs);
-            if (this.activeConnection) {
-                this.connection = this.dispatcher.createReconnectingClient(this.inetAddress, this.localAddress,
-                        this.retryTimer, this.keys);
+            isServiceInstantiated = true;
+            LOG.info("Peer instantiated {}", neighborAddress);
+            bgpPeer.instantiateServiceInstance();
+            dispatcher.getBGPPeerRegistry().addPeer(neighborAddress, bgpPeer, prefs);
+            if (activeConnection) {
+                connection = dispatcher.createReconnectingClient(inetAddress, localAddress, retryTimer, keys);
             }
         }
 
         synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
-            if (!this.isServiceInstantiated) {
-                LOG.info("Peer {} already closed", this.neighborAddress);
+            if (!isServiceInstantiated) {
+                LOG.info("Peer {} already closed", neighborAddress);
                 return CommitInfo.emptyFluentFuture();
             }
-            LOG.info("Close Peer {}", this.neighborAddress);
-            this.isServiceInstantiated = false;
-            if (this.connection != null) {
-                this.connection.cancel(true);
-                this.connection = null;
+            LOG.info("Close Peer {}", neighborAddress);
+            isServiceInstantiated = false;
+            if (connection != null) {
+                connection.cancel(true);
+                connection = null;
             }
-            final FluentFuture<? extends CommitInfo> future = this.bgpPeer.close();
-            removePeer(this.dispatcher.getBGPPeerRegistry());
+            final FluentFuture<? extends CommitInfo> future = bgpPeer.close();
+            removePeer(dispatcher.getBGPPeerRegistry());
             return future;
         }
 
         @Override
         public BGPPeerState getPeerState() {
-            return this.bgpPeer.getPeerState();
+            return bgpPeer.getPeerState();
         }
     }
 
     public synchronized List<OptionalCapabilities> getBgpFixedCapabilities() {
-        return this.bgpPeerSingletonService.finalCapabilities;
+        return bgpPeerSingletonService.finalCapabilities;
     }
 
     public synchronized int getGracefulRestartTimer() {
-        return this.bgpPeerSingletonService.gracefulRestartTimer;
+        return bgpPeerSingletonService.gracefulRestartTimer;
     }
 
     public synchronized Optional<RevisedErrorHandlingSupport> getErrorHandling() {
-        return Optional.ofNullable(this.bgpPeerSingletonService.errorHandling);
+        return Optional.ofNullable(bgpPeerSingletonService.errorHandling);
     }
 }
index 2972f347253de22acfea2b25be95d3c9edaee37f..da94843cf5a01e27bf993f6ad3c40f097481eccb 100644 (file)
@@ -96,10 +96,11 @@ final class OpenConfigMappingUtil {
     }
 
     static KeyMapping getNeighborKey(final Neighbor neighbor) {
-        if (neighbor.getConfig() != null) {
-            final String authPassword = neighbor.getConfig().getAuthPassword();
+        final var config = neighbor.getConfig();
+        if (config != null) {
+            final String authPassword = config.getAuthPassword();
             if (authPassword != null) {
-                return KeyMapping.getKeyMapping(INSTANCE.inetAddressFor(neighbor.getNeighborAddress()), authPassword);
+                return KeyMapping.of(INSTANCE.inetAddressFor(neighbor.getNeighborAddress()), authPassword);
             }
         }
         return null;
index 5204c63a1039442a6615c442b367f7983fb9c86e..6268c0039b3235517d18d0cf1ce1daaf13d8bcd5 100755 (executable)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkIdleState;
 
 import com.google.common.collect.Sets;
@@ -14,7 +16,6 @@ import io.netty.channel.Channel;
 import io.netty.util.concurrent.Future;
 import java.net.InetSocketAddress;
 import java.util.concurrent.ExecutionException;
-import org.junit.Assert;
 import org.junit.Test;
 import org.opendaylight.protocol.bgp.rib.spi.State;
 import org.opendaylight.protocol.concepts.KeyMapping;
@@ -25,31 +26,31 @@ public class BGPDispatcherImplTest extends AbstractBGPDispatcherTest {
     public void testCreateClient() throws InterruptedException, ExecutionException {
         final InetSocketAddress serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
         final Channel serverChannel = createServer(serverAddress);
-        final Future<BGPSessionImpl> futureClient = this.clientDispatcher.createClient(this.clientAddress,
-            serverAddress, 2, true);
+        final Future<BGPSessionImpl> futureClient = clientDispatcher.createClient(clientAddress, serverAddress, 2,
+            true);
         futureClient.sync();
         final BGPSessionImpl session = futureClient.get();
-        Assert.assertEquals(State.UP, this.clientListener.getState());
-        Assert.assertEquals(State.UP, this.serverListener.getState());
-        Assert.assertEquals(AS_NUMBER, session.getAsNumber());
-        Assert.assertEquals(Sets.newHashSet(IPV_4_TT), session.getAdvertisedTableTypes());
-        Assert.assertTrue(serverChannel.isWritable());
+        assertEquals(State.UP, clientListener.getState());
+        assertEquals(State.UP, serverListener.getState());
+        assertEquals(AS_NUMBER, session.getAsNumber());
+        assertEquals(Sets.newHashSet(IPV_4_TT), session.getAdvertisedTableTypes());
+        assertTrue(serverChannel.isWritable());
         session.close();
-        this.serverListener.releaseConnection();
-        checkIdleState(this.clientListener);
-        checkIdleState(this.serverListener);
+        serverListener.releaseConnection();
+        checkIdleState(clientListener);
+        checkIdleState(serverListener);
     }
 
     @Test
     public void testCreateReconnectingClient() throws Exception {
         final InetSocketAddress serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
-        final Future<Void> future = this.clientDispatcher.createReconnectingClient(serverAddress, RETRY_TIMER,
-            KeyMapping.getKeyMapping(), this.clientAddress, true);
+        final Future<Void> future = clientDispatcher.createReconnectingClient(serverAddress, RETRY_TIMER,
+            KeyMapping.of(), clientAddress, true);
         final Channel serverChannel = createServer(serverAddress);
-        Assert.assertEquals(State.UP, this.serverListener.getState());
-        Assert.assertTrue(serverChannel.isWritable());
+        assertEquals(State.UP, serverListener.getState());
+        assertTrue(serverChannel.isWritable());
         future.cancel(true);
-        this.serverListener.releaseConnection();
-        checkIdleState(this.serverListener);
+        serverListener.releaseConnection();
+        checkIdleState(serverListener);
     }
 }
index 0999be2b719b70b6d192b3856a2770dc4ad3d5f5..77c9bf6004e7ca42f212da4d86b7410c3b73e7d5 100644 (file)
@@ -153,11 +153,11 @@ public class OpenConfigMappingUtilTest {
 
     @Before
     public void setUp() {
-        doReturn(BGP_TABLE_TYPE_IPV4).when(this.tableTypeRegistry).getTableType(IPV4UNICAST.class);
-        doReturn(BGP_TABLE_TYPE_IPV6).when(this.tableTypeRegistry).getTableType(IPV6UNICAST.class);
+        doReturn(BGP_TABLE_TYPE_IPV4).when(tableTypeRegistry).getTableType(IPV4UNICAST.class);
+        doReturn(BGP_TABLE_TYPE_IPV6).when(tableTypeRegistry).getTableType(IPV6UNICAST.class);
         doReturn(new BgpTableTypeImpl(Ipv6AddressFamily.class, MplsLabeledVpnSubsequentAddressFamily.class))
-            .when(this.tableTypeRegistry).getTableType(IPV6LABELLEDUNICAST.class);
-        doReturn(AS).when(this.rib).getLocalAs();
+            .when(tableTypeRegistry).getTableType(IPV6LABELLEDUNICAST.class);
+        doReturn(AS).when(rib).getLocalAs();
     }
 
     @Test
@@ -182,12 +182,11 @@ public class OpenConfigMappingUtilTest {
     public void testGetRemotePeerAs() {
         final ConfigBuilder configBuilder = new ConfigBuilder();
         assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(NEIGHBOR.getConfig(), null, null));
-        assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(configBuilder.build(), null,
-                this.rib.getLocalAs()));
+        assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(configBuilder.build(), null, rib.getLocalAs()));
 
         assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(NEIGHBOR.getConfig(), EMPTY_PEERGROUP, null));
         assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(configBuilder.build(), EMPTY_PEERGROUP,
-                this.rib.getLocalAs()));
+                rib.getLocalAs()));
 
         assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(null, new PeerGroupBuilder().setPeerGroupName("foo")
                         .setConfig(new ConfigBuilder().setPeerAs(AS).build()).build(), null));
@@ -236,7 +235,7 @@ public class OpenConfigMappingUtilTest {
     @Test
     public void testGetNeighborKey() {
         assertArrayEquals(MD5_PASSWORD.getBytes(StandardCharsets.US_ASCII),
-            OpenConfigMappingUtil.getNeighborKey(NEIGHBOR).get(INSTANCE.inetAddressFor(NEIGHBOR_ADDRESS)));
+            OpenConfigMappingUtil.getNeighborKey(NEIGHBOR).asMap().get(INSTANCE.inetAddressFor(NEIGHBOR_ADDRESS)));
         assertNull(OpenConfigMappingUtil.getNeighborKey(EMPTY_NEIGHBOR));
         assertNull(OpenConfigMappingUtil.getNeighborKey(new NeighborBuilder().setNeighborAddress(NEIGHBOR_ADDRESS)
                 .setConfig(new ConfigBuilder().build()).build()));
@@ -377,7 +376,7 @@ public class OpenConfigMappingUtilTest {
         families.add(new AfiSafiBuilder().setAfiSafiName(IPV6UNICAST.class)
             .addAugmentation(new GlobalAddPathsConfigBuilder().setSendMax(ALL_PATHS).build()).build());
         final Map<BgpTableType, PathSelectionMode> result = OpenConfigMappingUtil
-                .toPathSelectionMode(families, this.tableTypeRegistry);
+                .toPathSelectionMode(families, tableTypeRegistry);
         final Map<BgpTableType, PathSelectionMode> expected = new HashMap<>();
         expected.put(new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class),
                 ADD_PATH_BEST_N_PATH_SELECTION);
@@ -420,8 +419,7 @@ public class OpenConfigMappingUtilTest {
                 .setReceive(Boolean.FALSE).setSendMax(N_PATHS).build()).build());
         families.add(new AfiSafiBuilder().setAfiSafiName(IPV6LABELLEDUNICAST.class)
             .addAugmentation(new NeighborAddPathsConfigBuilder().setReceive(Boolean.FALSE).build()).build());
-        final List<AddressFamilies> result = OpenConfigMappingUtil
-                .toAddPathCapability(families, this.tableTypeRegistry);
+        final List<AddressFamilies> result = OpenConfigMappingUtil .toAddPathCapability(families, tableTypeRegistry);
         assertEquals(FAMILIES, result);
     }
 
@@ -501,4 +499,4 @@ public class OpenConfigMappingUtilTest {
         assertEquals(RevisedErrorHandlingSupportImpl.forExternalPeer(),
                 OpenConfigMappingUtil.getRevisedErrorHandling(PeerRole.Ebgp, peerGroup.build(), neighbor.build()));
     }
-}
\ No newline at end of file
+}
index 789f64bd22fb61995e2dcdf2b63469eba4f623e8..ba89ad18f8eb9d4cb8e95f4cd1c8906a77b2698b 100644 (file)
@@ -91,7 +91,7 @@ public final class BmpDispatcherUtil {
 
             if (!keys.isEmpty()) {
                 if (Epoll.isAvailable()) {
-                    serverBootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
+                    serverBootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
                 } else {
                     throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
                 }
@@ -140,7 +140,7 @@ public final class BmpDispatcherUtil {
             }
             if (!keys.isEmpty()) {
                 if (Epoll.isAvailable()) {
-                    bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
+                    bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
                 } else {
                     throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
                 }
index b82579e95c03263618027e51d2a4eb3e4ea3be82..b79568c61099f134c215910a09ea526ec3a18ef5 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.protocol.bmp.impl.app;
 
 import static java.util.Objects.requireNonNull;
-import static org.opendaylight.protocol.bmp.impl.app.KeyConstructorUtil.constructKeys;
 
 import com.google.common.base.Preconditions;
 import com.google.common.net.InetAddresses;
@@ -19,6 +18,8 @@ import io.netty.channel.ChannelFutureListener;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.concurrent.ExecutionException;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
 import org.opendaylight.mdsal.common.api.CommitInfo;
@@ -34,6 +35,7 @@ import org.opendaylight.protocol.bmp.api.BmpDispatcher;
 import org.opendaylight.protocol.bmp.impl.spi.BmpMonitoringStation;
 import org.opendaylight.protocol.concepts.KeyMapping;
 import org.opendaylight.protocol.util.Ipv4Util;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.config.rev200120.odl.bmp.monitors.bmp.monitor.config.MonitoredRouter;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev200120.BmpMonitor;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev200120.MonitorId;
@@ -71,55 +73,73 @@ public final class BmpMonitoringStationImpl implements BmpMonitoringStation, Clu
         this.domDataBroker = requireNonNull(domDataBroker);
         this.dispatcher = requireNonNull(dispatcher);
         this.monitorId = monitorId;
-        this.monitoredRouters = mrs;
+        monitoredRouters = mrs;
         this.address = requireNonNull(address);
 
-        this.yangMonitorId = YangInstanceIdentifier.builder()
+        yangMonitorId = YangInstanceIdentifier.builder()
                 .node(BmpMonitor.QNAME).node(Monitor.QNAME)
                 .nodeWithKey(Monitor.QNAME, MONITOR_ID_QNAME, monitorId.getValue()).build();
 
-        this.sessionManager = new RouterSessionManager(this.yangMonitorId, this.domDataBroker, extensions, codecTree);
+        sessionManager = new RouterSessionManager(yangMonitorId, this.domDataBroker, extensions, codecTree);
 
         LOG.info("BMP Monitor Singleton Service {} registered, Monitor Id {}",
                 getIdentifier().getName(), this.monitorId.getValue());
-        this.singletonServiceRegistration = singletonProvider.registerClusterSingletonService(this);
+        singletonServiceRegistration = singletonProvider.registerClusterSingletonService(this);
     }
 
     @Override
     public synchronized void instantiateServiceInstance() {
         LOG.info("BMP Monitor Singleton Service {} instantiated, Monitor Id {}",
-                getIdentifier().getName(), this.monitorId.getValue());
+                getIdentifier().getName(), monitorId.getValue());
 
-        final ChannelFuture channelFuture = this.dispatcher.createServer(this.address, this.sessionManager,
-                constructKeys(this.monitoredRouters));
+        final ChannelFuture channelFuture = dispatcher.createServer(address, sessionManager,
+                constructKeys(monitoredRouters));
         try {
-            this.channel = channelFuture.sync().channel();
+            channel = channelFuture.sync().channel();
             createEmptyMonitor();
-            LOG.info("BMP Monitoring station {} started", this.monitorId.getValue());
+            LOG.info("BMP Monitoring station {} started", monitorId.getValue());
 
-            connectMonitoredRouters(this.dispatcher);
+            connectMonitoredRouters(dispatcher);
             LOG.info("Connecting to monitored routers completed.");
         } catch (final InterruptedException e) {
-            LOG.error("Failed to instantiate BMP Monitor Singleton {}", this.monitorId.getValue(), e);
+            LOG.error("Failed to instantiate BMP Monitor Singleton {}", monitorId.getValue(), e);
+        }
+
+    }
+
+    private static KeyMapping constructKeys(final Collection<MonitoredRouter> mrs) {
+        if (mrs == null || mrs.isEmpty()) {
+            return KeyMapping.of();
         }
 
+        final Map<InetAddress, String> passwords = new HashMap<>();
+        for (MonitoredRouter mr : mrs) {
+            if (mr != null) {
+                final Rfc2385Key password = mr.getPassword();
+                if (password != null && !password.getValue().isEmpty()) {
+                    passwords.put(IetfInetUtil.INSTANCE.inetAddressForNoZone(mr.getAddress()), password.getValue());
+                }
+            }
+        }
+
+        return KeyMapping.of(passwords);
     }
 
     @Override
     public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
         LOG.info("BMP Monitor Singleton Service {} instance closed, Monitor Id {}",
-                getIdentifier().getName(), this.monitorId.getValue());
-        if (this.channel != null) {
-            this.channel.close().addListener((ChannelFutureListener) future -> {
+                getIdentifier().getName(), monitorId.getValue());
+        if (channel != null) {
+            channel.close().addListener((ChannelFutureListener) future -> {
                 Preconditions.checkArgument(future.isSuccess(),
                         "Channel failed to close: %s", future.cause());
                 BmpMonitoringStationImpl.this.sessionManager.close();
             });
         }
 
-        final DOMDataTreeWriteTransaction wTx = this.domDataBroker.newWriteOnlyTransaction();
-        wTx.delete(LogicalDatastoreType.OPERATIONAL, this.yangMonitorId);
-        LOG.info("BMP monitoring station {} closed.", this.monitorId.getValue());
+        final DOMDataTreeWriteTransaction wTx = domDataBroker.newWriteOnlyTransaction();
+        wTx.delete(LogicalDatastoreType.OPERATIONAL, yangMonitorId);
+        LOG.info("BMP monitoring station {} closed.", monitorId.getValue());
         return wTx.commit();
     }
 
@@ -129,8 +149,8 @@ public final class BmpMonitoringStationImpl implements BmpMonitoringStation, Clu
     }
 
     private void connectMonitoredRouters(final BmpDispatcher pdispatcher) {
-        if (this.monitoredRouters != null) {
-            for (final MonitoredRouter mr : this.monitoredRouters) {
+        if (monitoredRouters != null) {
+            for (final MonitoredRouter mr : monitoredRouters) {
                 if (mr.getActive()) {
                     requireNonNull(mr.getAddress());
                     requireNonNull(mr.getPort());
@@ -138,35 +158,35 @@ public final class BmpMonitoringStationImpl implements BmpMonitoringStation, Clu
                     final InetAddress addr = InetAddresses.forString(s);
                     final KeyMapping ret;
                     final Rfc2385Key rfc2385KeyPassword = mr.getPassword();
-                    ret = KeyMapping.getKeyMapping(addr, rfc2385KeyPassword.getValue());
+                    ret = KeyMapping.of(addr, rfc2385KeyPassword.getValue());
                     pdispatcher.createClient(Ipv4Util.toInetSocketAddress(mr.getAddress(), mr.getPort()),
-                            this.sessionManager, ret);
+                            sessionManager, ret);
                 }
             }
         }
     }
 
     private synchronized void createEmptyMonitor() {
-        final DOMDataTreeWriteTransaction wTx = this.domDataBroker.newWriteOnlyTransaction();
+        final DOMDataTreeWriteTransaction wTx = domDataBroker.newWriteOnlyTransaction();
         wTx.put(LogicalDatastoreType.OPERATIONAL,
                 YangInstanceIdentifier.builder().node(BmpMonitor.QNAME).node(Monitor.QNAME)
-                        .nodeWithKey(Monitor.QNAME, MONITOR_ID_QNAME, this.monitorId.getValue()).build(),
-                ImmutableNodes.mapEntryBuilder(Monitor.QNAME, MONITOR_ID_QNAME, this.monitorId.getValue())
-                        .addChild(ImmutableNodes.leafNode(MONITOR_ID_QNAME, this.monitorId.getValue()))
+                        .nodeWithKey(Monitor.QNAME, MONITOR_ID_QNAME, monitorId.getValue()).build(),
+                ImmutableNodes.mapEntryBuilder(Monitor.QNAME, MONITOR_ID_QNAME, monitorId.getValue())
+                        .addChild(ImmutableNodes.leafNode(MONITOR_ID_QNAME, monitorId.getValue()))
                         .addChild(ImmutableNodes.mapNodeBuilder(Router.QNAME).build())
                         .build());
         try {
             wTx.commit().get();
         } catch (final ExecutionException | InterruptedException e) {
-            LOG.error("Failed to initiate BMP Monitor {}.", this.monitorId.getValue(), e);
+            LOG.error("Failed to initiate BMP Monitor {}.", monitorId.getValue(), e);
         }
     }
 
     @Override
     public synchronized void close() throws Exception {
-        if (this.singletonServiceRegistration != null) {
-            this.singletonServiceRegistration.close();
-            this.singletonServiceRegistration = null;
+        if (singletonServiceRegistration != null) {
+            singletonServiceRegistration.close();
+            singletonServiceRegistration = null;
         }
     }
 }
diff --git a/bmp/bmp-impl/src/main/java/org/opendaylight/protocol/bmp/impl/app/KeyConstructorUtil.java b/bmp/bmp-impl/src/main/java/org/opendaylight/protocol/bmp/impl/app/KeyConstructorUtil.java
deleted file mode 100644 (file)
index 44c0b05..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.bmp.impl.app;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Collection;
-import java.util.Objects;
-import org.opendaylight.protocol.concepts.KeyMapping;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.config.rev200120.odl.bmp.monitors.bmp.monitor.config.MonitoredRouter;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.rfc2385.cfg.rev160324.Rfc2385Key;
-
-public final class KeyConstructorUtil {
-    private KeyConstructorUtil() {
-        // Hidden on purpose
-    }
-
-    public static KeyMapping constructKeys(final Collection<MonitoredRouter> mrs) {
-        final KeyMapping ret = KeyMapping.getKeyMapping();
-        if (mrs != null) {
-            mrs.stream().filter(Objects::nonNull).filter(KeyConstructorUtil::isNotNullorEmpty)
-                .forEach(mr -> {
-                    final Rfc2385Key rfc2385KeyPassword = mr.getPassword();
-                    ret.put(IetfInetUtil.INSTANCE.inetAddressForNoZone(mr.getAddress()),
-                        rfc2385KeyPassword.getValue().getBytes(StandardCharsets.US_ASCII));
-                });
-        }
-
-        return ret;
-    }
-
-    private static boolean isNotNullorEmpty(final MonitoredRouter mr) {
-        final Rfc2385Key password = mr.getPassword();
-        return password != null && !password.getValue().isEmpty();
-    }
-}
index c97bea49bc9a4b90dec37e08178d2a1e7d59b254..1d677c4b8bfed8eb7e39d0606631ed541cccf258 100644 (file)
@@ -78,15 +78,13 @@ public class BmpDispatcherImplTest {
 
     @Test
     public void testCreateServer() throws Exception {
-        final ChannelFuture futureServer = dispatcher.createServer(SERVER, mockedListenerFactory,
-            KeyMapping.getKeyMapping());
+        final ChannelFuture futureServer = dispatcher.createServer(SERVER, mockedListenerFactory, KeyMapping.of());
         waitFutureSuccess(futureServer);
         final Channel serverChannel = futureServer.channel();
         checkEquals(() -> assertTrue(serverChannel.isActive()));
 
-
         final ChannelFuture futureClient = dispatcher.createClient(CLIENT_REMOTE, mockedListenerFactory,
-            KeyMapping.getKeyMapping());
+            KeyMapping.of());
         waitFutureSuccess(futureClient);
 
         final Channel clientChannel = futureClient.channel();
index 8c32c8f66119634e2f5253e24a8f8ab981384874..8cc8e61073bf2b357defad29a62fae281deaafce 100644 (file)
@@ -36,7 +36,7 @@ final class BmpMockDispatcher implements AutoCloseable {
     private static final Logger LOG = LoggerFactory.getLogger(BmpMockDispatcher.class);
     private static final int CONNECT_TIMEOUT = 2000;
     private static final int INITIAL_BACKOFF = 15_000;
-    private static final KeyMapping KEY_MAPPING = KeyMapping.getKeyMapping();
+
     private final BmpHandlerFactory hf;
     private final BmpSessionFactory sessionFactory;
 
@@ -48,16 +48,16 @@ final class BmpMockDispatcher implements AutoCloseable {
 
     BmpMockDispatcher(final BmpMessageRegistry registry, final BmpSessionFactory sessionFactory) {
         this.sessionFactory = requireNonNull(sessionFactory);
-        this.slf = new BmpMockSessionListenerFactory();
+        slf = new BmpMockSessionListenerFactory();
         requireNonNull(registry);
-        this.hf = new BmpHandlerFactory(registry);
+        hf = new BmpHandlerFactory(registry);
     }
 
     ChannelFuture createClient(final @NonNull SocketAddress localAddress,
             final @NonNull InetSocketAddress remoteAddress) {
-        final Bootstrap bootstrap = BmpDispatcherUtil.createClientBootstrap(this.sessionFactory, this.hf,
-                BmpDispatcherUtil::createChannelWithEncoder, this.slf, remoteAddress, localAddress, this.workerGroup,
-                CONNECT_TIMEOUT, KEY_MAPPING, true, false);
+        final Bootstrap bootstrap = BmpDispatcherUtil.createClientBootstrap(sessionFactory, hf,
+                BmpDispatcherUtil::createChannelWithEncoder, slf, remoteAddress, localAddress, workerGroup,
+                CONNECT_TIMEOUT, KeyMapping.of(), true, false);
         final ChannelFuture channelFuture = bootstrap.connect(remoteAddress);
         LOG.info("BMP client {} <--> {} deployed", localAddress, remoteAddress);
         channelFuture.addListener(new BootstrapListener(bootstrap, localAddress, remoteAddress));
@@ -66,9 +66,9 @@ final class BmpMockDispatcher implements AutoCloseable {
 
     ChannelFuture createServer(final InetSocketAddress localAddress) {
         requireNonNull(localAddress);
-        final ServerBootstrap serverBootstrap = BmpDispatcherUtil.createServerBootstrap(this.sessionFactory,
-                this.hf, this.slf, BmpDispatcherUtil::createChannelWithEncoder,
-                this.bossGroup, this.workerGroup, KEY_MAPPING, false);
+        final ServerBootstrap serverBootstrap = BmpDispatcherUtil.createServerBootstrap(sessionFactory,
+                hf, slf, BmpDispatcherUtil::createChannelWithEncoder,
+                bossGroup, workerGroup, KeyMapping.of(), false);
         final ChannelFuture channelFuture = serverBootstrap.bind(localAddress);
         LOG.info("Initiated BMP server at {}.", localAddress);
         return channelFuture;
@@ -76,7 +76,7 @@ final class BmpMockDispatcher implements AutoCloseable {
 
     @Override
     public synchronized void close() {
-        this.close = true;
+        close = true;
     }
 
     private class BootstrapListener implements ChannelFutureListener {
@@ -91,7 +91,7 @@ final class BmpMockDispatcher implements AutoCloseable {
             this.bootstrap = bootstrap;
             this.remoteAddress = remoteAddress;
             this.localAddress = localAddress;
-            this.delay = INITIAL_BACKOFF;
+            delay = INITIAL_BACKOFF;
         }
 
         @Override
@@ -103,20 +103,18 @@ final class BmpMockDispatcher implements AutoCloseable {
                 future.channel().closeFuture().addListener((ChannelFutureListener) channelFuture -> scheduleConnect());
             } else {
                 final EventLoop loop = future.channel().eventLoop();
-                loop.schedule(() -> this.bootstrap.connect().addListener(this), this.delay, TimeUnit.MILLISECONDS);
+                loop.schedule(() -> bootstrap.connect().addListener(this), delay, TimeUnit.MILLISECONDS);
                 LOG.info("The connection try to BMP router {} failed. Next reconnection attempt in {} milliseconds.",
-                        this.remoteAddress, this.delay);
+                        remoteAddress, delay);
             }
         }
 
         private void scheduleConnect() {
-            if (!BmpMockDispatcher.this.close) {
-
+            if (!close) {
                 timer.schedule(new TimerTask() {
                     @Override
                     public void run() {
-                        createClient(BootstrapListener.this.localAddress,
-                                BmpMockDispatcher.BootstrapListener.this.remoteAddress);
+                        createClient(localAddress, remoteAddress);
                     }
                 }, 5);
             }
index d06de317fba76c72f4aaa2ae1fa9acf7bcc6963b..554f35c24021033ab4176134b13f0185bb05acc3 100644 (file)
@@ -47,9 +47,9 @@ public class BmpMockDispatcherTest {
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
-        doReturn(this.sl).when(this.slf).getSessionListener();
-        doReturn(this.registry).when(this.ctx).getBmpMessageRegistry();
-        this.bmpMockDispatcher = new BmpMockDispatcher(this.registry, this.sessionFactory);
+        doReturn(sl).when(slf).getSessionListener();
+        doReturn(registry).when(ctx).getBmpMessageRegistry();
+        bmpMockDispatcher = new BmpMockDispatcher(registry, sessionFactory);
     }
 
     @Test(timeout = 20000)
@@ -58,53 +58,52 @@ public class BmpMockDispatcherTest {
         final InetSocketAddress serverAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
 
         final BmpDispatcherImpl bmpDispatcher = new BmpDispatcherImpl(
-                new NioEventLoopGroup(), new NioEventLoopGroup(), this.ctx, this.sessionFactory);
+                new NioEventLoopGroup(), new NioEventLoopGroup(), ctx, sessionFactory);
         final ChannelFuture futureServer = bmpDispatcher
-                .createServer(serverAddr, this.slf, KeyMapping.getKeyMapping());
+                .createServer(serverAddr, slf, KeyMapping.of());
         waitFutureSuccess(futureServer);
 
-        final ChannelFuture channelFuture = this.bmpMockDispatcher.createClient(InetSocketAddressUtil
+        final ChannelFuture channelFuture = bmpMockDispatcher.createClient(InetSocketAddressUtil
                 .getRandomLoopbackInetSocketAddress(0), serverAddr);
         final Channel channel = channelFuture.sync().channel();
 
         assertTrue(channel.isActive());
-        checkEquals(() -> assertTrue(this.sl.getStatus()));
+        checkEquals(() -> assertTrue(sl.getStatus()));
         channel.close();
         bmpDispatcher.close();
-        checkEquals(() -> assertFalse(this.sl.getStatus()));
+        checkEquals(() -> assertFalse(sl.getStatus()));
 
         final BmpDispatcherImpl bmpDispatcher2 = new BmpDispatcherImpl(
-                new NioEventLoopGroup(), new NioEventLoopGroup(), this.ctx, this.sessionFactory);
-        final ChannelFuture futureServer2 = bmpDispatcher2
-                .createServer(serverAddr, this.slf, KeyMapping.getKeyMapping());
+                new NioEventLoopGroup(), new NioEventLoopGroup(), ctx, sessionFactory);
+        final ChannelFuture futureServer2 = bmpDispatcher2.createServer(serverAddr, slf, KeyMapping.of());
         futureServer2.sync();
-        checkEquals(() -> assertTrue(this.sl.getStatus()));
+        checkEquals(() -> assertTrue(sl.getStatus()));
 
         bmpDispatcher2.close();
-        this.bmpMockDispatcher.close();
-        checkEquals(() -> assertFalse(this.sl.getStatus()));
+        bmpMockDispatcher.close();
+        checkEquals(() -> assertFalse(sl.getStatus()));
     }
 
     @Test(timeout = 20000)
     public void testCreateServer() throws Exception {
         final int port = InetSocketAddressUtil.getRandomPort();
         final BmpDispatcherImpl bmpDispatcher = new BmpDispatcherImpl(
-                new NioEventLoopGroup(), new NioEventLoopGroup(), this.ctx, this.sessionFactory);
-        final ChannelFuture futureServer = this.bmpMockDispatcher.createServer(
+                new NioEventLoopGroup(), new NioEventLoopGroup(), ctx, sessionFactory);
+        final ChannelFuture futureServer = bmpMockDispatcher.createServer(
                 new InetSocketAddress(InetAddresses.forString("0.0.0.0"), port));
         futureServer.sync();
         final ChannelFuture channelFuture = bmpDispatcher.createClient(
-                InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port), this.slf, KeyMapping.getKeyMapping());
+                InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port), slf, KeyMapping.of());
         final Channel channel = channelFuture.sync().channel();
 
         assertTrue(channel.isActive());
-        checkEquals(() -> assertTrue(this.sl.getStatus()));
+        checkEquals(() -> assertTrue(sl.getStatus()));
         assertTrue(futureServer.channel().isActive());
         channel.close();
 
         bmpDispatcher.close();
-        this.bmpMockDispatcher.close();
-        checkEquals(() -> assertFalse(this.sl.getStatus()));
+        bmpMockDispatcher.close();
+        checkEquals(() -> assertFalse(sl.getStatus()));
     }
 
 }
index df662a3301b59939b86463895258cee12cc90904..fa1f63708e6a591605d1232ac9235d43ed46457b 100644 (file)
@@ -45,24 +45,24 @@ public class BmpMockTest {
     @Before
     public void setUp() {
         final BmpExtensionProviderContext ctx = new SimpleBmpExtensionProviderContext();
-        this.bmpActivator = new BmpActivator(
+        bmpActivator = new BmpActivator(
             ServiceLoader.load(BGPExtensionConsumerContext.class).findFirst().orElseThrow());
-        this.bmpActivator.start(ctx);
-        this.bmpDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), ctx,
+        bmpActivator.start(ctx);
+        bmpDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), ctx,
             new DefaultBmpSessionFactory());
     }
 
     @After
     public void tearDown() throws Exception {
-        this.bmpDispatcher.close();
+        bmpDispatcher.close();
     }
 
     @Test(timeout = 20000)
     public void testMain() throws Exception {
         final InetSocketAddress serverAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
         final BmpSessionListenerFactory bmpSessionListenerFactory = () -> BmpMockTest.this.sessionListener;
-        final ChannelFuture futureServer = this.bmpDispatcher.createServer(serverAddr,
-                bmpSessionListenerFactory, KeyMapping.getKeyMapping());
+        final ChannelFuture futureServer = bmpDispatcher.createServer(serverAddr,
+                bmpSessionListenerFactory, KeyMapping.of());
         final Channel serverChannel;
         final int sessionUpWait;
         if (futureServer.isSuccess()) {
@@ -81,10 +81,10 @@ public class BmpMockTest {
             "--pre_policy_routes",
             "3"});
 
-        verify(this.sessionListener, timeout(TimeUnit.SECONDS.toMillis(sessionUpWait)))
+        verify(sessionListener, timeout(TimeUnit.SECONDS.toMillis(sessionUpWait)))
                 .onSessionUp(any(BmpSession.class));
         //1 * Initiate message + 3 * PeerUp Notification + 9 * Route Monitoring message
-        verify(this.sessionListener, timeout(TimeUnit.SECONDS.toMillis(10))
+        verify(sessionListener, timeout(TimeUnit.SECONDS.toMillis(10))
             .times(13))
             .onMessage(any(Notification.class));
 
@@ -104,8 +104,8 @@ public class BmpMockTest {
             "--peers_count", "3", "--pre_policy_routes", "3", "--passive"});
         Assert.assertEquals(1, futureServers.size());
         futureServers.get(0).sync();
-        final ChannelFuture futureClient = this.bmpDispatcher.createClient(serverAddr,
-                bmpSessionListenerFactory, KeyMapping.getKeyMapping());
+        final ChannelFuture futureClient = bmpDispatcher.createClient(serverAddr,
+                bmpSessionListenerFactory, KeyMapping.of());
         futureClient.sync();
         final Channel serverChannel;
         final int sessionUpWait;
@@ -118,10 +118,10 @@ public class BmpMockTest {
             sessionUpWait = 40;
         }
 
-        verify(this.sessionListener, timeout(TimeUnit.SECONDS.toMillis(sessionUpWait)))
+        verify(sessionListener, timeout(TimeUnit.SECONDS.toMillis(sessionUpWait)))
             .onSessionUp(any(BmpSession.class));
         //1 * Initiate message + 3 * PeerUp Notification + 9 * Route Monitoring message
-        verify(this.sessionListener, timeout(TimeUnit.SECONDS.toMillis(10))
+        verify(sessionListener, timeout(TimeUnit.SECONDS.toMillis(10))
             .times(13))
             .onMessage(any(Notification.class));
 
index 4fcfed50e0c592c8580084440d46fb5dbdb03947..d74c72a573b2566e4fe424b5040b2992c8c18ab3 100644 (file)
@@ -7,31 +7,42 @@
  */
 package org.opendaylight.protocol.concepts;
 
-import static com.google.common.base.Strings.isNullOrEmpty;
-
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
 import java.net.InetAddress;
 import java.nio.charset.StandardCharsets;
-import java.util.HashMap;
+import java.util.Map;
 import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.yangtools.concepts.Immutable;
+
+public final class KeyMapping implements Immutable {
+    private static final @NonNull KeyMapping EMPTY = new KeyMapping(ImmutableMap.of());
+
+    private final ImmutableMap<InetAddress, byte[]> map;
+
+    private KeyMapping(final Map<InetAddress, byte[]> map) {
+        this.map = ImmutableMap.copyOf(map);
+    }
+
+    public static @NonNull KeyMapping of() {
+        return EMPTY;
+    }
 
-public final class KeyMapping extends HashMap<InetAddress, byte[]> {
-    private static final long serialVersionUID = 1L;
+    public static @NonNull KeyMapping of(final @NonNull InetAddress inetAddress, final @NonNull String password) {
+        return new KeyMapping(ImmutableMap.of(inetAddress, password.getBytes(StandardCharsets.US_ASCII)));
+    }
 
-    private KeyMapping() {
-        super();
+    public static @NonNull KeyMapping of(final Map<InetAddress, String> passwords) {
+        return passwords.isEmpty() ? of()
+            : new KeyMapping(Maps.transformValues(passwords, password -> password.getBytes(StandardCharsets.US_ASCII)));
     }
 
-    public static @NonNull KeyMapping getKeyMapping(final @NonNull InetAddress inetAddress,
-            final @Nullable String password) {
-        final KeyMapping keyMapping = new KeyMapping();
-        if (!isNullOrEmpty(password)) {
-            keyMapping.put(inetAddress, password.getBytes(StandardCharsets.US_ASCII));
-        }
-        return keyMapping;
+    public boolean isEmpty() {
+        return map.isEmpty();
     }
 
-    public static KeyMapping getKeyMapping() {
-        return new KeyMapping();
+    public @NonNull Map<InetAddress, byte[]> asMap() {
+        // Careful: do not leak our byte[]s
+        return Maps.transformValues(map, byte[]::clone);
     }
 }
index 9f2694c0828cbed8d336dd670737c9fa59d0fb1c..1e2b42ace84c4489bff7fd05f6f2b93aff20150e 100644 (file)
@@ -66,8 +66,8 @@ public class PCEPDispatcherImpl implements PCEPDispatcher, Closeable {
     public PCEPDispatcherImpl(final @NonNull MessageRegistry registry,
             final @NonNull PCEPSessionNegotiatorFactory<PCEPSessionImpl> negotiatorFactory,
             final @NonNull EventLoopGroup bossGroup, final @NonNull EventLoopGroup workerGroup) {
-        this.snf = requireNonNull(negotiatorFactory);
-        this.hf = new PCEPHandlerFactory(registry);
+        snf = requireNonNull(negotiatorFactory);
+        hf = new PCEPHandlerFactory(registry);
         if (Epoll.isAvailable()) {
             this.bossGroup = new EpollEventLoopGroup();
             this.workerGroup = new EpollEventLoopGroup();
@@ -75,18 +75,18 @@ public class PCEPDispatcherImpl implements PCEPDispatcher, Closeable {
             this.bossGroup = requireNonNull(bossGroup);
             this.workerGroup = requireNonNull(workerGroup);
         }
-        this.executor = requireNonNull(GlobalEventExecutor.INSTANCE);
+        executor = requireNonNull(GlobalEventExecutor.INSTANCE);
     }
 
     @Override
     public final synchronized ChannelFuture createServer(final PCEPDispatcherDependencies dispatcherDependencies) {
-        this.keys = dispatcherDependencies.getKeys();
+        keys = dispatcherDependencies.getKeys();
 
         final ChannelPipelineInitializer initializer = (ch, promise) -> {
-            ch.pipeline().addLast(this.hf.getDecoders());
-            ch.pipeline().addLast("negotiator", this.snf
+            ch.pipeline().addLast(hf.getDecoders());
+            ch.pipeline().addLast("negotiator", snf
                     .getSessionNegotiator(dispatcherDependencies, ch, promise));
-            ch.pipeline().addLast(this.hf.getEncoders());
+            ch.pipeline().addLast(hf.getEncoders());
         };
 
         final ServerBootstrap b = createServerBootstrap(initializer);
@@ -94,7 +94,8 @@ public class PCEPDispatcherImpl implements PCEPDispatcher, Closeable {
         final ChannelFuture f = b.bind(address);
         LOG.debug("Initiated server {} at {}.", f, address);
 
-        this.keys = KeyMapping.getKeyMapping();
+        // FIXME: err, why are we resetting this?
+        keys = KeyMapping.of();
         return f;
     }
 
@@ -103,7 +104,7 @@ public class PCEPDispatcherImpl implements PCEPDispatcher, Closeable {
         b.childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             protected void initChannel(final SocketChannel ch) {
-                initializer.initializeChannel(ch, new DefaultPromise<>(PCEPDispatcherImpl.this.executor));
+                initializer.initializeChannel(ch, new DefaultPromise<>(executor));
             }
         });
         b.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE);
@@ -116,9 +117,9 @@ public class PCEPDispatcherImpl implements PCEPDispatcher, Closeable {
         } else {
             b.channel(NioServerSocketChannel.class);
         }
-        if (!this.keys.isEmpty()) {
+        if (!keys.isEmpty()) {
             if (Epoll.isAvailable()) {
-                b.option(EpollChannelOption.TCP_MD5SIG, this.keys);
+                b.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
             } else {
                 throw new UnsupportedOperationException("Setting TCP-MD5 signatures is not supported",
                         Epoll.unavailabilityCause().getCause());
@@ -129,7 +130,7 @@ public class PCEPDispatcherImpl implements PCEPDispatcher, Closeable {
         b.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1));
 
         if (b.config().group() == null) {
-            b.group(this.bossGroup, this.workerGroup);
+            b.group(bossGroup, workerGroup);
         }
 
         return b;
@@ -138,14 +139,14 @@ public class PCEPDispatcherImpl implements PCEPDispatcher, Closeable {
     @Override
     public final void close() {
         if (Epoll.isAvailable()) {
-            this.workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
-            this.bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+            workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+            bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
         }
     }
 
     @Override
     public final PCEPSessionNegotiatorFactory<PCEPSessionImpl> getPCEPSessionNegotiatorFactory() {
-        return this.snf;
+        return snf;
     }
 
     protected interface ChannelPipelineInitializer {
index 4716bdde720d808cbe42ad10af2d2e73b354415a..0d8224ba1f74fe3608529711d350a24e9251fa2e 100644 (file)
@@ -30,6 +30,7 @@ import io.netty.util.concurrent.GlobalEventExecutor;
 import java.net.InetSocketAddress;
 import java.nio.channels.Channel;
 import java.util.List;
+import java.util.Map;
 import java.util.concurrent.ExecutionException;
 import org.junit.After;
 import org.junit.Assert;
@@ -77,19 +78,19 @@ public class PCEPDispatcherImplTest {
             eventLoopGroup = new NioEventLoopGroup();
         }
         final MessageRegistry msgReg = new DefaultPCEPExtensionConsumerContext().getMessageHandlerRegistry();
-        this.dispatcher = new PCEPDispatcherImpl(msgReg,
+        dispatcher = new PCEPDispatcherImpl(msgReg,
                 new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
                 eventLoopGroup, eventLoopGroup);
 
-        doReturn(KeyMapping.getKeyMapping()).when(this.dispatcherDependencies).getKeys();
-        doReturn(null).when(this.dispatcherDependencies).getPeerProposal();
+        doReturn(KeyMapping.of()).when(dispatcherDependencies).getKeys();
+        doReturn(null).when(dispatcherDependencies).getPeerProposal();
 
         final PCEPDispatcherImpl dispatcher2 = new PCEPDispatcherImpl(msgReg,
                 new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
                 eventLoopGroup, eventLoopGroup);
-        this.disp2Spy = spy(dispatcher2);
+        disp2Spy = spy(dispatcher2);
 
-        this.pccMock = new PCCMock(new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
+        pccMock = new PCCMock(new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
                 new PCEPHandlerFactory(msgReg));
     }
 
@@ -100,15 +101,15 @@ public class PCEPDispatcherImplTest {
         final InetSocketAddress clientAddr1 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
         final InetSocketAddress clientAddr2 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
 
-        doReturn(serverAddr).when(this.dispatcherDependencies).getAddress();
-        doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
-        doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
-        final ChannelFuture futureChannel = this.dispatcher.createServer(this.dispatcherDependencies);
+        doReturn(serverAddr).when(dispatcherDependencies).getAddress();
+        doReturn(listenerFactory).when(dispatcherDependencies).getListenerFactory();
+        doReturn(new SimpleSessionListener()).when(listenerFactory).getSessionListener();
+        final ChannelFuture futureChannel = dispatcher.createServer(dispatcherDependencies);
         futureChannel.sync();
-        final PCEPSessionImpl session1 = this.pccMock.createClient(clientAddr1,
+        final PCEPSessionImpl session1 = pccMock.createClient(clientAddr1,
                 RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
 
-        final PCEPSessionImpl session2 = this.pccMock.createClient(clientAddr2,
+        final PCEPSessionImpl session2 = pccMock.createClient(clientAddr2,
                 RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
 
         Assert.assertTrue(futureChannel.channel().isActive());
@@ -131,17 +132,17 @@ public class PCEPDispatcherImplTest {
         final InetSocketAddress serverAddr = new InetSocketAddress("0.0.0.0", port);
         final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
 
-        doReturn(serverAddr).when(this.dispatcherDependencies).getAddress();
-        doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
-        doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
+        doReturn(serverAddr).when(dispatcherDependencies).getAddress();
+        doReturn(listenerFactory).when(dispatcherDependencies).getListenerFactory();
+        doReturn(new SimpleSessionListener()).when(listenerFactory).getSessionListener();
 
-        this.dispatcher.createServer(this.dispatcherDependencies).sync();
-        final Future<PCEPSessionImpl> futureClient = this.pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
+        dispatcher.createServer(dispatcherDependencies).sync();
+        final Future<PCEPSessionImpl> futureClient = pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
                 SimpleSessionListener::new);
         futureClient.sync();
 
         try (PCEPSessionImpl ignored = futureClient.get()) {
-            this.pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
+            pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
                     SimpleSessionListener::new).get();
             Assert.fail();
         } catch (final ExecutionException e) {
@@ -154,11 +155,11 @@ public class PCEPDispatcherImplTest {
         final int port = InetSocketAddressUtil.getRandomPort();
         final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
 
-        doReturn(new InetSocketAddress("0.0.0.0", port)).when(this.dispatcherDependencies).getAddress();
-        doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
-        doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
-        this.dispatcher.createServer(this.dispatcherDependencies).sync();
-        final PCEPSessionImpl session1 = this.pccMock.createClient(clientAddr,
+        doReturn(new InetSocketAddress("0.0.0.0", port)).when(dispatcherDependencies).getAddress();
+        doReturn(listenerFactory).when(dispatcherDependencies).getListenerFactory();
+        doReturn(new SimpleSessionListener()).when(listenerFactory).getSessionListener();
+        dispatcher.createServer(dispatcherDependencies).sync();
+        final PCEPSessionImpl session1 = pccMock.createClient(clientAddr,
                 RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
 
         assertEquals(clientAddr.getAddress(), session1.getRemoteAddress());
@@ -166,7 +167,7 @@ public class PCEPDispatcherImplTest {
         assertEquals(KEEP_ALIVE, session1.getKeepAliveTimerValue().shortValue());
         session1.closeChannel().sync();
 
-        final PCEPSessionImpl session2 = this.pccMock.createClient(clientAddr,
+        final PCEPSessionImpl session2 = pccMock.createClient(clientAddr,
                 RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
 
         assertEquals(clientAddr.getAddress(), session1.getRemoteAddress());
@@ -181,20 +182,21 @@ public class PCEPDispatcherImplTest {
         final int port = InetSocketAddressUtil.getRandomPort();
         final InetSocketAddress clientAddr1 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
         final InetSocketAddress clientAddr2 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
-        final KeyMapping keys = KeyMapping.getKeyMapping(clientAddr1.getAddress(), "CLIENT1_ADDRESS");
-        keys.put(clientAddr2.getAddress(), "CLIENT2_ADDRESS".getBytes());
+        final KeyMapping keys = KeyMapping.of(Map.of(
+            clientAddr1.getAddress(), "CLIENT1_ADDRESS",
+            clientAddr2.getAddress(), "CLIENT2_ADDRESS"));
 
-        doReturn(new InetSocketAddress("0.0.0.0", port)).when(this.dispatcherDependencies).getAddress();
+        doReturn(new InetSocketAddress("0.0.0.0", port)).when(dispatcherDependencies).getAddress();
 
-        final ChannelFuture futureChannel = this.disp2Spy.createServer(this.dispatcherDependencies);
+        final ChannelFuture futureChannel = disp2Spy.createServer(dispatcherDependencies);
         futureChannel.sync();
-        verify(this.disp2Spy).createServerBootstrap(any(PCEPDispatcherImpl.ChannelPipelineInitializer.class));
+        verify(disp2Spy).createServerBootstrap(any(PCEPDispatcherImpl.ChannelPipelineInitializer.class));
     }
 
     @After
     public void tearDown() {
-        this.dispatcher.close();
-        this.disp2Spy.close();
+        dispatcher.close();
+        disp2Spy.close();
     }
 
     private static class PCCMock {
@@ -205,26 +207,26 @@ public class PCEPDispatcherImplTest {
 
         PCCMock(final PCEPSessionNegotiatorFactory<PCEPSessionImpl> negotiatorFactory,
                 final PCEPHandlerFactory factory) {
-            this.workerGroup = new NioEventLoopGroup();
+            workerGroup = new NioEventLoopGroup();
             this.negotiatorFactory = requireNonNull(negotiatorFactory);
             this.factory = requireNonNull(factory);
-            this.executor = requireNonNull(GlobalEventExecutor.INSTANCE);
+            executor = requireNonNull(GlobalEventExecutor.INSTANCE);
         }
 
         Future<PCEPSessionImpl> createClient(final InetSocketAddress address, final int retryTimer,
                 final int connectTimeout, final PCEPSessionListenerFactory listenerFactory) {
             return createClient(address, retryTimer, connectTimeout, (ch, promise) -> {
-                ch.pipeline().addLast(this.factory.getDecoders());
-                ch.pipeline().addLast("negotiator", this.negotiatorFactory.getSessionNegotiator(
+                ch.pipeline().addLast(factory.getDecoders());
+                ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(
                     () -> listenerFactory, ch, promise));
-                ch.pipeline().addLast(this.factory.getEncoders());
+                ch.pipeline().addLast(factory.getEncoders());
             });
         }
 
         Future<PCEPSessionImpl> createClient(final InetSocketAddress address, final int retryTimer,
                 final int connectTimeout, final PCEPDispatcherImpl.ChannelPipelineInitializer initializer) {
             final Bootstrap b = new Bootstrap();
-            final PCEPProtocolSessionPromise<PCEPSessionImpl> p = new PCEPProtocolSessionPromise<>(this.executor,
+            final PCEPProtocolSessionPromise<PCEPSessionImpl> p = new PCEPProtocolSessionPromise<>(executor,
                     address, retryTimer, connectTimeout, b);
             b.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE).handler(new ChannelInitializer<SocketChannel>() {
                 @Override
@@ -249,7 +251,7 @@ public class PCEPDispatcherImplTest {
 
         private void setWorkerGroup(final Bootstrap bootstrap) {
             if (bootstrap.config().group() == null) {
-                bootstrap.group(this.workerGroup);
+                bootstrap.group(workerGroup);
             }
         }
     }
index b9981425ccfcce1e638d4abc80014df66fb0fcb0..ce6e978ac1f9028085ab03fbdbf9fb11b6dc10f8 100644 (file)
@@ -46,8 +46,6 @@ final class PCCsBuilder {
     private final Timer timer = new HashedWheelTimer();
     private final MessageRegistry registry;
 
-    private PCCDispatcherImpl pccDispatcher;
-
     PCCsBuilder(final int lsps, final boolean pcError, final int pccCount,
             final @NonNull InetSocketAddress localAddress, final @NonNull List<InetSocketAddress> remoteAddress,
             final short keepAlive, final short deadTimer, final @Nullable String password, final long reconnectTime,
@@ -65,37 +63,39 @@ final class PCCsBuilder {
         this.stateTimeout = stateTimeout;
         this.pcepCapabilities = pcepCapabilities;
 
-        this.registry = new DefaultPCEPExtensionConsumerContext().getMessageHandlerRegistry();
+        registry = new DefaultPCEPExtensionConsumerContext().getMessageHandlerRegistry();
     }
 
     void createPCCs(final Uint64 initialDBVersion, final Optional<TimerHandler> timerHandler) {
-        InetAddress currentAddress = this.localAddress.getAddress();
-        this.pccDispatcher = new PCCDispatcherImpl(registry);
+        InetAddress currentAddress = localAddress.getAddress();
+        PCCDispatcherImpl pccDispatcher = new PCCDispatcherImpl(registry);
+
         if (timerHandler.isPresent()) {
-            timerHandler.get().setPCCDispatcher(this.pccDispatcher);
+            timerHandler.get().setPCCDispatcher(pccDispatcher);
         }
-        for (int i = 0; i < this.pccCount; i++) {
-            final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(this.lsps, currentAddress,
-                this.redelegationTimeout, this.stateTimeout, this.timer, timerHandler);
-            createPCC(new InetSocketAddress(currentAddress, this.localAddress.getPort()), tunnelManager,
-                    initialDBVersion);
+        for (int i = 0; i < pccCount; i++) {
+            final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(lsps, currentAddress,
+                redelegationTimeout, stateTimeout, timer, timerHandler);
+            createPCC(pccDispatcher, new InetSocketAddress(currentAddress, localAddress.getPort()), tunnelManager,
+                initialDBVersion);
             currentAddress = InetAddresses.increment(currentAddress);
         }
     }
 
-    private void createPCC(final @NonNull InetSocketAddress plocalAddress,
+    private void createPCC(final PCCDispatcherImpl pccDispatcher, final @NonNull InetSocketAddress plocalAddress,
             final PCCTunnelManager tunnelManager, final Uint64 initialDBVersion) {
         final PCEPSessionNegotiatorFactory<PCEPSessionImpl> snf = getSessionNegotiatorFactory();
-        for (final InetSocketAddress pceAddress : this.remoteAddress) {
-            this.pccDispatcher.createClient(pceAddress, this.reconnectTime, () -> new PCCSessionListener(
-                            this.remoteAddress.indexOf(pceAddress), tunnelManager, this.pcError), snf,
-                    KeyMapping.getKeyMapping(pceAddress.getAddress(), this.password), plocalAddress, initialDBVersion);
+        for (final InetSocketAddress pceAddress : remoteAddress) {
+            pccDispatcher.createClient(pceAddress, reconnectTime,
+                () -> new PCCSessionListener(remoteAddress.indexOf(pceAddress), tunnelManager, pcError), snf,
+                    password == null ? KeyMapping.of() : KeyMapping.of(pceAddress.getAddress(), password),
+                        plocalAddress, initialDBVersion);
         }
     }
 
     private PCEPSessionNegotiatorFactory<PCEPSessionImpl> getSessionNegotiatorFactory() {
-        final List<PCEPCapability> capabilities = Lists.newArrayList(this.pcepCapabilities);
-        return new DefaultPCEPSessionNegotiatorFactory(new BasePCEPSessionProposalFactory(this.deadTimer,
-            this.keepAlive, capabilities), 0);
+        final List<PCEPCapability> capabilities = Lists.newArrayList(pcepCapabilities);
+        return new DefaultPCEPSessionNegotiatorFactory(new BasePCEPSessionProposalFactory(deadTimer,
+            keepAlive, capabilities), 0);
     }
 }
index 0a940c198ee49950207610ca5c66db3199f464a9..0164c57ec650602ace523a9f66e5c55ad6b3fa85 100755 (executable)
@@ -50,11 +50,11 @@ public final class PCCDispatcherImpl implements PCCDispatcher, AutoCloseable {
 
     public PCCDispatcherImpl(final @NonNull MessageRegistry registry) {
         if (Epoll.isAvailable()) {
-            this.workerGroup = new EpollEventLoopGroup();
+            workerGroup = new EpollEventLoopGroup();
         } else {
-            this.workerGroup = new NioEventLoopGroup();
+            workerGroup = new NioEventLoopGroup();
         }
-        this.factory = new PCEPHandlerFactory(registry);
+        factory = new PCEPHandlerFactory(registry);
     }
 
     @Override
@@ -72,7 +72,7 @@ public final class PCCDispatcherImpl implements PCCDispatcher, AutoCloseable {
             final PCEPSessionListenerFactory listenerFactory, final PCEPSessionNegotiatorFactory negotiatorFactory,
             final KeyMapping keys, final InetSocketAddress localAddress, final Uint64 dbVersion) {
         final Bootstrap b = new Bootstrap();
-        b.group(this.workerGroup);
+        b.group(workerGroup);
         b.localAddress(localAddress);
         setChannelFactory(b, keys);
         b.option(ChannelOption.SO_KEEPALIVE, true);
@@ -84,7 +84,7 @@ public final class PCCDispatcherImpl implements PCCDispatcher, AutoCloseable {
         final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<>() {
             @Override
             protected void initChannel(final SocketChannel ch) {
-                ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
+                ch.pipeline().addLast(factory.getDecoders());
                 ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(
                         new PCEPSessionNegotiatorFactoryDependencies() {
                             @Override
@@ -97,7 +97,7 @@ public final class PCCDispatcherImpl implements PCCDispatcher, AutoCloseable {
                                 return new PCCPeerProposal(dbVersion);
                             }
                         }, ch, promise));
-                ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
+                ch.pipeline().addLast(factory.getEncoders());
                 ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                     @Override
                     public void channelInactive(final ChannelHandlerContext ctx) {
@@ -136,7 +136,7 @@ public final class PCCDispatcherImpl implements PCCDispatcher, AutoCloseable {
         }
         if (!keys.isEmpty()) {
             if (Epoll.isAvailable()) {
-                bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
+                bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
             } else {
                 throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
             }
@@ -146,7 +146,7 @@ public final class PCCDispatcherImpl implements PCCDispatcher, AutoCloseable {
     @Override
     public void close() {
         try {
-            this.workerGroup.shutdownGracefully().get();
+            workerGroup.shutdownGracefully().get();
         } catch (final InterruptedException | ExecutionException e) {
             LOG.warn("Failed to properly close dispatcher.", e);
         }
index fea04ef9250ba8fb8a3392cd587b58d3920d003a..ede2a40d3178047b8aec522d9d3874019217d934 100644 (file)
@@ -68,7 +68,7 @@ public class PCCDispatcherImplTest {
         pcepDispatcher = new PCEPDispatcherImpl(registry, nf, bossGroup, workerGroup);
         serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
         clientAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(0);
-        doReturn(KeyMapping.getKeyMapping()).when(dispatcherDependencies).getKeys();
+        doReturn(KeyMapping.of()).when(dispatcherDependencies).getKeys();
         doReturn(serverAddress).when(dispatcherDependencies).getAddress();
         doReturn(null).when(dispatcherDependencies).getPeerProposal();
     }
@@ -87,7 +87,7 @@ public class PCCDispatcherImplTest {
     @Test(timeout = 20000)
     public void testClientReconnect() throws Exception {
         final Future<PCEPSession> futureSession = dispatcher.createClient(serverAddress, 1,
-            new TestingSessionListenerFactory(), nf, KeyMapping.getKeyMapping(), clientAddress);
+            new TestingSessionListenerFactory(), nf, KeyMapping.of(), clientAddress);
         final TestingSessionListenerFactory slf = new TestingSessionListenerFactory();
         doReturn(slf).when(dispatcherDependencies).getListenerFactory();
 
index 172d34cf824906a2c3e3ca765efd32953c857ed4..3af3a83faaea6a74ee5efe22f45e8585825cab81 100644 (file)
@@ -220,7 +220,7 @@ public abstract class PCCMockCommon {
         return pccDispatcher.createClient(remoteAddress, -1, () -> {
             pccSessionListener = new PCCSessionListener(1, tunnelManager, false);
             return pccSessionListener;
-        }, snf, KeyMapping.getKeyMapping(), localAddress, dbVersion);
+        }, snf, KeyMapping.of(), localAddress, dbVersion);
     }
 
     private PCEPSessionNegotiatorFactory<PCEPSessionImpl> getSessionNegotiatorFactory() {
@@ -233,7 +233,7 @@ public abstract class PCCMockCommon {
     }
 
     private static class DispatcherDependencies implements PCEPDispatcherDependencies {
-        final KeyMapping keys = KeyMapping.getKeyMapping();
+        private final KeyMapping keys = KeyMapping.of();
         private final InetSocketAddress address;
         private final TestingSessionListenerFactory listenerFactory;
         private final PCEPPeerProposal peerProposal;
index 5369402ffbd0533388d55df9424f859649178df9..70aa5fb3912667dd1c263b0911b7fb300821b5f0 100644 (file)
@@ -16,7 +16,6 @@ import org.opendaylight.protocol.pcep.SpeakerIdMapping;
 public final class TestToolPCEPDispatcherDependencies implements PCEPDispatcherDependencies {
     private final PCEPSessionListenerFactory listenerFactory = new TestingSessionListenerFactory();
     private final InetSocketAddress address;
-    private final KeyMapping keys = KeyMapping.getKeyMapping();
 
     TestToolPCEPDispatcherDependencies(final InetSocketAddress address) {
         this.address = address;
@@ -29,7 +28,7 @@ public final class TestToolPCEPDispatcherDependencies implements PCEPDispatcherD
 
     @Override
     public KeyMapping getKeys() {
-        return keys;
+        return KeyMapping.of();
     }
 
     @Override
index 15221e51fc0d5ee876f74c2d51acfb0ac28ae310..a7a97e438d9620fdccd98ff7245f6c8413b70191 100644 (file)
@@ -42,8 +42,8 @@ public final class PCCMock {
 
         try (PCCDispatcherImpl pccDispatcher = new PCCDispatcherImpl(
                 new DefaultPCEPExtensionConsumerContext().getMessageHandlerRegistry())) {
-            pccDispatcher.createClient(serverAddr, -1, SimpleSessionListener::new, snf,
-                    KeyMapping.getKeyMapping(), clientAddr).get();
+            pccDispatcher.createClient(serverAddr, -1, SimpleSessionListener::new, snf, KeyMapping.of(), clientAddr)
+                .get();
         }
     }
 }
index cef1cab4c98795ac0b7adbc565f444f724309040..698c7d05842f107e400eaf5425849128578d632d 100644 (file)
@@ -13,11 +13,15 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.net.InetAddresses;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
+import java.util.HashMap;
 import java.util.Map;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.protocol.concepts.KeyMapping;
 import org.opendaylight.protocol.pcep.SpeakerIdMapping;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.config.rev200120.pcep.config.SessionConfig;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.config.rev181109.PcepNodeConfig;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.sync.optimizations.config.rev181109.PcepNodeSyncConfig;
@@ -27,33 +31,30 @@ import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
+import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
 
-public final class PCEPTopologyConfiguration {
-    private final InetSocketAddress address;
-    private final KeyMapping keys;
-    private final TopologyId topologyId;
+public final class PCEPTopologyConfiguration implements Immutable {
+    private final @NonNull InetSocketAddress address;
+    private final @NonNull KeyMapping keys;
     private final short rpcTimeout;
     private final @NonNull SpeakerIdMapping speakerIds;
-    private final InstanceIdentifier<Topology> topology;
+    private final @NonNull KeyedInstanceIdentifier<Topology, TopologyKey> topology;
 
     public PCEPTopologyConfiguration(final @NonNull SessionConfig config, final @NonNull Topology topology) {
-        requireNonNull(topology);
-        address = PCEPTopologyProviderUtil.getInetSocketAddress(requireNonNull(config.getListenAddress()),
-                requireNonNull(config.getListenPort()));
-        keys = requireNonNull(PCEPTopologyProviderUtil.contructKeys(topology));
+        this.topology = InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, topology.key());
+        address = getInetSocketAddress(config.getListenAddress(), config.getListenPort());
+        keys = constructKeys(topology.getNode());
         speakerIds = contructSpeakersId(topology.getNode());
-        topologyId = requireNonNull(topology.getTopologyId());
         rpcTimeout = config.getRpcTimeout();
-        this.topology = InstanceIdentifier.builder(NetworkTopology.class)
-                .child(Topology.class, new TopologyKey(topologyId)).build();
     }
 
     public @NonNull TopologyId getTopologyId() {
-        return topologyId;
+        return topology.getKey().getTopologyId();
     }
 
-    public @NonNull InstanceIdentifier<Topology> getTopology() {
+    public @NonNull KeyedInstanceIdentifier<Topology, TopologyKey> getTopology() {
         return topology;
     }
 
@@ -73,6 +74,33 @@ public final class PCEPTopologyConfiguration {
         return speakerIds;
     }
 
+    private static @NonNull KeyMapping constructKeys(final @Nullable Map<NodeKey, Node> nodes) {
+        if (nodes == null) {
+            return KeyMapping.of();
+        }
+
+        final var passwords = new HashMap<InetAddress, String>();
+        for (var node : nodes.values()) {
+            if (node != null) {
+                final var nodeConfig = node.augmentation(PcepNodeConfig.class);
+                if (nodeConfig != null) {
+                    final var sessionConfig = nodeConfig.getSessionConfig();
+                    if (sessionConfig != null) {
+                        final var rfc2385KeyPassword = sessionConfig.getPassword();
+                        if (rfc2385KeyPassword != null) {
+                            final String password = rfc2385KeyPassword.getValue();
+                            if (!password.isEmpty()) {
+                                passwords.put(nodeAddress(node), password);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        return KeyMapping.of(passwords);
+    }
+
     private static @NonNull SpeakerIdMapping contructSpeakersId(final @Nullable Map<NodeKey, Node> nodes) {
         if (nodes == null) {
             return SpeakerIdMapping.of();
@@ -89,7 +117,7 @@ public final class PCEPTopologyConfiguration {
                         if (nodeSyncConfig != null) {
                             final var speakerEntityId = nodeSyncConfig.getSpeakerEntityIdValue();
                             if (speakerEntityId != null) {
-                                builder.put(InetAddresses.forString(node.getNodeId().getValue()), speakerEntityId);
+                                builder.put(nodeAddress(node), speakerEntityId);
                             }
                         }
                     }
@@ -99,4 +127,14 @@ public final class PCEPTopologyConfiguration {
 
         return SpeakerIdMapping.copyOf(builder.build());
     }
+
+    private static InetAddress nodeAddress(final Node node) {
+        return InetAddresses.forString(node.getNodeId().getValue());
+    }
+
+    private static @NonNull InetSocketAddress getInetSocketAddress(final IpAddressNoZone address,
+            final PortNumber port) {
+        return new InetSocketAddress(IetfInetUtil.INSTANCE.inetAddressForNoZone(requireNonNull(address)),
+            port.getValue().toJava());
+    }
 }
diff --git a/pcep/topology/topology-provider/src/main/java/org/opendaylight/bgpcep/pcep/topology/provider/config/PCEPTopologyProviderUtil.java b/pcep/topology/topology-provider/src/main/java/org/opendaylight/bgpcep/pcep/topology/provider/config/PCEPTopologyProviderUtil.java
deleted file mode 100644 (file)
index e1bcf35..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.bgpcep.pcep.topology.provider.config;
-
-import com.google.common.net.InetAddresses;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.nio.charset.StandardCharsets;
-import java.util.Objects;
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.protocol.concepts.KeyMapping;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.rfc2385.cfg.rev160324.Rfc2385Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.config.rev181109.PcepNodeConfig;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-
-final class PCEPTopologyProviderUtil {
-    private PCEPTopologyProviderUtil() {
-        // Hidden on purpose
-    }
-
-    static KeyMapping contructKeys(final @NonNull Topology topology) {
-        final KeyMapping ret = KeyMapping.getKeyMapping();
-        if (topology.getNode() == null) {
-            return ret;
-        }
-        topology.nonnullNode().values().stream()
-                .filter(Objects::nonNull)
-                .filter(node -> node.augmentation(PcepNodeConfig.class) != null)
-                .filter(node -> node.augmentation(PcepNodeConfig.class).getSessionConfig() != null)
-                .filter(node -> node.augmentation(PcepNodeConfig.class)
-                        .getSessionConfig().getPassword() != null)
-                .filter(node -> !node.augmentation(PcepNodeConfig.class)
-                        .getSessionConfig().getPassword().getValue().isEmpty())
-                .forEach(node -> {
-                    final PcepNodeConfig config = node.augmentation(PcepNodeConfig.class);
-                    final Rfc2385Key rfc2385KeyPassword = config.getSessionConfig().getPassword();
-                    final InetAddress address = InetAddresses.forString(node.getNodeId().getValue());
-                    ret.put(address, rfc2385KeyPassword.getValue().getBytes(StandardCharsets.US_ASCII));
-                });
-
-        return ret;
-    }
-
-    static InetSocketAddress getInetSocketAddress(final @NonNull IpAddressNoZone address,
-            final @NonNull PortNumber port) {
-        return new InetSocketAddress(IetfInetUtil.INSTANCE.inetAddressForNoZone(address), port.getValue().toJava());
-    }
-}
index 6cd42d04dd7716ef832b05f2f6243bba6766e25b..a453ae04f14f4165918a1d01f8d15e0ff1ded84b 100644 (file)
@@ -25,8 +25,8 @@ import io.netty.util.concurrent.Promise;
 import java.lang.reflect.ParameterizedType;
 import java.net.InetSocketAddress;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
+import java.util.Map;
 import java.util.concurrent.TimeUnit;
 import org.junit.After;
 import org.junit.Before;
@@ -77,9 +77,9 @@ public abstract class AbstractPCEPSessionTest<T extends TopologySessionListenerF
     static final short DEAD_TIMER = 30;
     static final short KEEP_ALIVE = 10;
     static final short RPC_TIMEOUT = 4;
-    private static final TopologyId TEST_TOPOLOGY_ID = new TopologyId("testtopo");
+    private static final TopologyKey TEST_TOPOLOGY_ID = new TopologyKey(new TopologyId("testtopo"));
     static final InstanceIdentifier<Topology> TOPO_IID = InstanceIdentifier.builder(NetworkTopology.class)
-            .child(Topology.class, new TopologyKey(TEST_TOPOLOGY_ID)).build();
+            .child(Topology.class, TEST_TOPOLOGY_ID).build();
     private static final String IPV4_MASK = "/32";
     final String testAddress = InetSocketAddressUtil.getRandomLoopbackIpAddress();
     final NodeId nodeId = new NodeId("pcc://" + this.testAddress);
@@ -151,9 +151,9 @@ public abstract class AbstractPCEPSessionTest<T extends TopologySessionListenerF
             .getListenAddress();
         doReturn(new PortNumber(Uint16.valueOf(4189))).when(this.sessionConfig).getListenPort();
         doReturn(RPC_TIMEOUT).when(this.sessionConfig).getRpcTimeout();
-        doReturn(TEST_TOPOLOGY_ID).when(this.topology).getTopologyId();
+        doReturn(TEST_TOPOLOGY_ID).when(this.topology).key();
         doCallRealMethod().when(this.topology).nonnullNode();
-        doReturn(Collections.emptyMap()).when(this.topology).getNode();
+        doReturn(Map.of()).when(this.topology).getNode();
         doReturn(null).when(this.topologyDependencies).getPceServerProvider();
 
         final PCEPTopologyConfiguration configDep = new PCEPTopologyConfiguration(this.sessionConfig, this.topology);