From: Tony Tkacik Date: Thu, 20 Nov 2014 08:52:29 +0000 (+0000) Subject: Merge "BUG-2218: Keep existing link augmentations during discovery process" X-Git-Tag: release/lithium~865 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=dd32d3d246ebad8b7c76afb93239a4462f329a6b;hp=c7551f594c34504fffa0055d3360132577938b38 Merge "BUG-2218: Keep existing link augmentations during discovery process" --- diff --git a/features/mdsal/src/main/resources/features.xml b/features/mdsal/src/main/resources/features.xml index fb524081e7..540cea1bbc 100644 --- a/features/mdsal/src/main/resources/features.xml +++ b/features/mdsal/src/main/resources/features.xml @@ -76,4 +76,13 @@ mvn:org.opendaylight.controller/sal-clustering-config/${project.version}/xml/moduleshardconf mvn:org.opendaylight.controller/sal-clustering-config/${project.version}/xml/moduleconf + + + odl-yangtools-models + odl-mdsal-broker + mvn:org.opendaylight.controller.samples/clustering-it-model/${project.version} + mvn:org.opendaylight.controller.samples/clustering-it-provider/${project.version} + mvn:org.opendaylight.controller.samples/clustering-it-config/${project.version}/xml/config + + diff --git a/features/netconf-connector/pom.xml b/features/netconf-connector/pom.xml index 03d6fed605..c69ee197be 100644 --- a/features/netconf-connector/pom.xml +++ b/features/netconf-connector/pom.xml @@ -162,6 +162,7 @@ Optional TODO: Remove TODO comments. --> + org.opendaylight.yangtools features-test diff --git a/features/netconf-connector/src/main/resources/features.xml b/features/netconf-connector/src/main/resources/features.xml index 6ae308eb0c..863833bcc0 100644 --- a/features/netconf-connector/src/main/resources/features.xml +++ b/features/netconf-connector/src/main/resources/features.xml @@ -25,6 +25,9 @@ mvn:org.opendaylight.controller/features-mdsal/${mdsal.version}/xml/features mvn:org.opendaylight.yangtools/features-yangtools/${yangtools.version}/xml/features mvn:org.opendaylight.controller/features-netconf/${netconf.version}/xml/features + mvn:org.opendaylight.aaa/features-aaa/${aaa.version}/xml/features + odl-aaa-netconf-plugin mvn:org.opendaylight.controller/netconf-ssh/${netconf.version} - mvn:org.bouncycastle/bcpkix-jdk15on/${bouncycastle.version} - mvn:org.bouncycastle/bcprov-jdk15on/${bouncycastle.version} odl-netconf-impl diff --git a/features/netconf/pom.xml b/features/netconf/pom.xml index a944bb4dec..028c16b02f 100644 --- a/features/netconf/pom.xml +++ b/features/netconf/pom.xml @@ -74,10 +74,6 @@ org.opendaylight.controller netconf-netty-util - - org.opendaylight.controller.thirdparty - ganymed - org.apache.sshd sshd-core diff --git a/features/netconf/src/main/resources/features.xml b/features/netconf/src/main/resources/features.xml index 444f20865b..9de15630c3 100644 --- a/features/netconf/src/main/resources/features.xml +++ b/features/netconf/src/main/resources/features.xml @@ -57,7 +57,8 @@ odl-netconf-mapping-api odl-netconf-util mvn:org.opendaylight.controller/netconf-netty-util/${project.version} - mvn:org.opendaylight.controller.thirdparty/ganymed/${ganymed.version} + mvn:org.bouncycastle/bcpkix-jdk15on/${bouncycastle.version} + mvn:org.bouncycastle/bcprov-jdk15on/${bouncycastle.version} mvn:org.apache.sshd/sshd-core/${sshd-core.version} mvn:org.openexi/nagasena/${exi.nagasena.version} mvn:io.netty/netty-codec/${netty.version} diff --git a/features/pom.xml b/features/pom.xml index 5270e3f5cd..ba938c6a6f 100644 --- a/features/pom.xml +++ b/features/pom.xml @@ -13,11 +13,6 @@ 3.0 - base - controller - adsal - nsf - extras config config-persister config-netty @@ -25,7 +20,6 @@ flow netconf protocol-framework - adsal-compatibility akka netconf-connector restconf diff --git a/features/restconf/src/main/resources/features.xml b/features/restconf/src/main/resources/features.xml index ab42330eac..123b00767e 100644 --- a/features/restconf/src/main/resources/features.xml +++ b/features/restconf/src/main/resources/features.xml @@ -38,7 +38,6 @@ --> odl-restconf odl-mdsal-apidocs - odl-clustering-test-app - ../implementation/target/jacoco.exec + ../../implementation/target/jacoco.exec @@ -92,7 +92,7 @@ org.jacoco jacoco-maven-plugin - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec org.opendaylight.controller.* diff --git a/opendaylight/clustering/integrationtest/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusteringServicesIT.java b/opendaylight/adsal/clustering/integrationtest/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusteringServicesIT.java similarity index 100% rename from opendaylight/clustering/integrationtest/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusteringServicesIT.java rename to opendaylight/adsal/clustering/integrationtest/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusteringServicesIT.java diff --git a/opendaylight/clustering/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/clustering/integrationtest/src/test/resources/logback.xml similarity index 100% rename from opendaylight/clustering/integrationtest/src/test/resources/logback.xml rename to opendaylight/adsal/clustering/integrationtest/src/test/resources/logback.xml diff --git a/opendaylight/clustering/services/pom.xml b/opendaylight/adsal/clustering/services/pom.xml similarity index 96% rename from opendaylight/clustering/services/pom.xml rename to opendaylight/adsal/clustering/services/pom.xml index 8c66e70cbe..550f580ebd 100644 --- a/opendaylight/clustering/services/pom.xml +++ b/opendaylight/adsal/clustering/services/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight clustering.services diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheConfigException.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheConfigException.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheConfigException.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheConfigException.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheExistException.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheExistException.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheExistException.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheExistException.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheListenerAddException.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheListenerAddException.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheListenerAddException.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheListenerAddException.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICacheUpdateAware.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICacheUpdateAware.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICacheUpdateAware.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICacheUpdateAware.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterContainerServices.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterContainerServices.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterContainerServices.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterContainerServices.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterGlobalServices.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterGlobalServices.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterGlobalServices.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterGlobalServices.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServices.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServices.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServices.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServices.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServicesCommon.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServicesCommon.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServicesCommon.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServicesCommon.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICoordinatorChangeAware.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICoordinatorChangeAware.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICoordinatorChangeAware.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICoordinatorChangeAware.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IGetUpdates.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IGetUpdates.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IGetUpdates.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IGetUpdates.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IListenRoleChange.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IListenRoleChange.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IListenRoleChange.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IListenRoleChange.java diff --git a/opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ListenRoleChangeAddException.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ListenRoleChangeAddException.java similarity index 100% rename from opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ListenRoleChangeAddException.java rename to opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ListenRoleChangeAddException.java diff --git a/opendaylight/clustering/services_implementation/pom.xml b/opendaylight/adsal/clustering/services_implementation/pom.xml similarity index 98% rename from opendaylight/clustering/services_implementation/pom.xml rename to opendaylight/adsal/clustering/services_implementation/pom.xml index f11f7a14c0..36cd35d891 100644 --- a/opendaylight/clustering/services_implementation/pom.xml +++ b/opendaylight/adsal/clustering/services_implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight clustering.services-implementation diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/Activator.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/Activator.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/Activator.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/Activator.java diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/CacheListenerContainer.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/CacheListenerContainer.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/CacheListenerContainer.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/CacheListenerContainer.java diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClassResolver.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClassResolver.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClassResolver.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClassResolver.java diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterContainerManager.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterContainerManager.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterContainerManager.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterContainerManager.java diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterGlobalManager.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterGlobalManager.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterGlobalManager.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterGlobalManager.java diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManager.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManager.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManager.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManager.java diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCLI.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCLI.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCLI.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCLI.java diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCommon.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCommon.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCommon.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCommon.java diff --git a/opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/GetUpdatesContainer.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/GetUpdatesContainer.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/GetUpdatesContainer.java rename to opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/GetUpdatesContainer.java diff --git a/opendaylight/clustering/services_implementation/src/main/resources/config/infinispan-config.xml b/opendaylight/adsal/clustering/services_implementation/src/main/resources/config/infinispan-config.xml similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/resources/config/infinispan-config.xml rename to opendaylight/adsal/clustering/services_implementation/src/main/resources/config/infinispan-config.xml diff --git a/opendaylight/clustering/services_implementation/src/main/resources/config/jgroups.xml b/opendaylight/adsal/clustering/services_implementation/src/main/resources/config/jgroups.xml similarity index 100% rename from opendaylight/clustering/services_implementation/src/main/resources/config/jgroups.xml rename to opendaylight/adsal/clustering/services_implementation/src/main/resources/config/jgroups.xml diff --git a/opendaylight/clustering/services_implementation/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerTest.java b/opendaylight/adsal/clustering/services_implementation/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerTest.java similarity index 100% rename from opendaylight/clustering/services_implementation/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerTest.java rename to opendaylight/adsal/clustering/services_implementation/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerTest.java diff --git a/opendaylight/clustering/stub/pom.xml b/opendaylight/adsal/clustering/stub/pom.xml similarity index 96% rename from opendaylight/clustering/stub/pom.xml rename to opendaylight/adsal/clustering/stub/pom.xml index 211dcc29d0..7ab30110f3 100644 --- a/opendaylight/clustering/stub/pom.xml +++ b/opendaylight/adsal/clustering/stub/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight clustering.stub diff --git a/opendaylight/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/Activator.java b/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/Activator.java similarity index 100% rename from opendaylight/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/Activator.java rename to opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/Activator.java diff --git a/opendaylight/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterContainerManager.java b/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterContainerManager.java similarity index 100% rename from opendaylight/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterContainerManager.java rename to opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterContainerManager.java diff --git a/opendaylight/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterGlobalManager.java b/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterGlobalManager.java similarity index 100% rename from opendaylight/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterGlobalManager.java rename to opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterGlobalManager.java diff --git a/opendaylight/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterManagerCommon.java b/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterManagerCommon.java similarity index 100% rename from opendaylight/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterManagerCommon.java rename to opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterManagerCommon.java diff --git a/opendaylight/clustering/stub/src/test/java/org/opendaylight/controller/clustering/stub/internal/TestClusteringStub.java b/opendaylight/adsal/clustering/stub/src/test/java/org/opendaylight/controller/clustering/stub/internal/TestClusteringStub.java similarity index 100% rename from opendaylight/clustering/stub/src/test/java/org/opendaylight/controller/clustering/stub/internal/TestClusteringStub.java rename to opendaylight/adsal/clustering/stub/src/test/java/org/opendaylight/controller/clustering/stub/internal/TestClusteringStub.java diff --git a/opendaylight/clustering/test/pom.xml b/opendaylight/adsal/clustering/test/pom.xml similarity index 98% rename from opendaylight/clustering/test/pom.xml rename to opendaylight/adsal/clustering/test/pom.xml index 93294f2290..93407ea3d7 100644 --- a/opendaylight/clustering/test/pom.xml +++ b/opendaylight/adsal/clustering/test/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight clustering.test diff --git a/opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/Activator.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/Activator.java similarity index 100% rename from opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/Activator.java rename to opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/Activator.java diff --git a/opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass.java similarity index 100% rename from opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass.java rename to opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass.java diff --git a/opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass1.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass1.java similarity index 100% rename from opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass1.java rename to opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass1.java diff --git a/opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexContainer.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexContainer.java similarity index 100% rename from opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexContainer.java rename to opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexContainer.java diff --git a/opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/IComplex.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/IComplex.java similarity index 100% rename from opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/IComplex.java rename to opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/IComplex.java diff --git a/opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/LoggingListener.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/LoggingListener.java similarity index 100% rename from opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/LoggingListener.java rename to opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/LoggingListener.java diff --git a/opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/SimpleClient.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/SimpleClient.java similarity index 100% rename from opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/SimpleClient.java rename to opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/SimpleClient.java diff --git a/opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/StringContainer.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/StringContainer.java similarity index 100% rename from opendaylight/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/StringContainer.java rename to opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/StringContainer.java diff --git a/opendaylight/clustering/test/src/test/java/org/opendaylight/controller/clustering/test/internal/TestClusteringTest.java b/opendaylight/adsal/clustering/test/src/test/java/org/opendaylight/controller/clustering/test/internal/TestClusteringTest.java similarity index 100% rename from opendaylight/clustering/test/src/test/java/org/opendaylight/controller/clustering/test/internal/TestClusteringTest.java rename to opendaylight/adsal/clustering/test/src/test/java/org/opendaylight/controller/clustering/test/internal/TestClusteringTest.java diff --git a/opendaylight/commons/httpclient/pom.xml b/opendaylight/adsal/commons/httpclient/pom.xml similarity index 96% rename from opendaylight/commons/httpclient/pom.xml rename to opendaylight/adsal/commons/httpclient/pom.xml index 39364cbcba..93a537c00c 100644 --- a/opendaylight/commons/httpclient/pom.xml +++ b/opendaylight/adsal/commons/httpclient/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight commons.httpclient @@ -62,7 +62,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - ${checkstyle.version} true controller/checkstyle.xml diff --git a/opendaylight/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPClient.java b/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPClient.java similarity index 100% rename from opendaylight/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPClient.java rename to opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPClient.java diff --git a/opendaylight/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPRequest.java b/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPRequest.java similarity index 100% rename from opendaylight/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPRequest.java rename to opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPRequest.java diff --git a/opendaylight/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPResponse.java b/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPResponse.java similarity index 100% rename from opendaylight/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPResponse.java rename to opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPResponse.java diff --git a/opendaylight/commons/integrationtest/pom.xml b/opendaylight/adsal/commons/integrationtest/pom.xml similarity index 96% rename from opendaylight/commons/integrationtest/pom.xml rename to opendaylight/adsal/commons/integrationtest/pom.xml index ad4e166cbd..1701964bf1 100644 --- a/opendaylight/commons/integrationtest/pom.xml +++ b/opendaylight/adsal/commons/integrationtest/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight commons.integrationtest @@ -80,7 +80,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - ${checkstyle.version} true controller/checkstyle.xml @@ -96,7 +95,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${surefire.version} true diff --git a/opendaylight/configuration/api/pom.xml b/opendaylight/adsal/configuration/api/pom.xml similarity index 96% rename from opendaylight/configuration/api/pom.xml rename to opendaylight/adsal/configuration/api/pom.xml index 50f19278c6..dec934bf6e 100644 --- a/opendaylight/configuration/api/pom.xml +++ b/opendaylight/adsal/configuration/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight configuration diff --git a/opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationEvent.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationEvent.java similarity index 100% rename from opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationEvent.java rename to opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationEvent.java diff --git a/opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationObject.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationObject.java similarity index 100% rename from opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationObject.java rename to opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationObject.java diff --git a/opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAware.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAware.java similarity index 100% rename from opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAware.java rename to opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAware.java diff --git a/opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAwareCommon.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAwareCommon.java similarity index 100% rename from opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAwareCommon.java rename to opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAwareCommon.java diff --git a/opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerAware.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerAware.java similarity index 100% rename from opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerAware.java rename to opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerAware.java diff --git a/opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerService.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerService.java similarity index 100% rename from opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerService.java rename to opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerService.java diff --git a/opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationService.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationService.java similarity index 100% rename from opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationService.java rename to opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationService.java diff --git a/opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationServiceCommon.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationServiceCommon.java similarity index 100% rename from opendaylight/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationServiceCommon.java rename to opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationServiceCommon.java diff --git a/opendaylight/configuration/implementation/pom.xml b/opendaylight/adsal/configuration/implementation/pom.xml similarity index 97% rename from opendaylight/configuration/implementation/pom.xml rename to opendaylight/adsal/configuration/implementation/pom.xml index 4387de70ea..a35d2e9406 100644 --- a/opendaylight/configuration/implementation/pom.xml +++ b/opendaylight/adsal/configuration/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight configuration.implementation diff --git a/opendaylight/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/Activator.java b/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/Activator.java similarity index 100% rename from opendaylight/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/Activator.java rename to opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/Activator.java diff --git a/opendaylight/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationService.java b/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationService.java similarity index 100% rename from opendaylight/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationService.java rename to opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationService.java diff --git a/opendaylight/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ContainerConfigurationService.java b/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ContainerConfigurationService.java similarity index 100% rename from opendaylight/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ContainerConfigurationService.java rename to opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ContainerConfigurationService.java diff --git a/opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationAwareTest.java b/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationAwareTest.java similarity index 100% rename from opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationAwareTest.java rename to opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationAwareTest.java diff --git a/opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerAwareTest.java b/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerAwareTest.java similarity index 100% rename from opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerAwareTest.java rename to opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerAwareTest.java diff --git a/opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImplTest.java b/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImplTest.java similarity index 100% rename from opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImplTest.java rename to opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImplTest.java diff --git a/opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationImplTest.java b/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationImplTest.java similarity index 100% rename from opendaylight/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationImplTest.java rename to opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationImplTest.java diff --git a/opendaylight/configuration/integrationtest/.gitignore b/opendaylight/adsal/configuration/integrationtest/.gitignore similarity index 100% rename from opendaylight/configuration/integrationtest/.gitignore rename to opendaylight/adsal/configuration/integrationtest/.gitignore diff --git a/opendaylight/configuration/integrationtest/pom.xml b/opendaylight/adsal/configuration/integrationtest/pom.xml similarity index 100% rename from opendaylight/configuration/integrationtest/pom.xml rename to opendaylight/adsal/configuration/integrationtest/pom.xml diff --git a/opendaylight/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java b/opendaylight/adsal/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java similarity index 100% rename from opendaylight/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java rename to opendaylight/adsal/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java diff --git a/opendaylight/configuration/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/configuration/integrationtest/src/test/resources/logback.xml similarity index 100% rename from opendaylight/configuration/integrationtest/src/test/resources/logback.xml rename to opendaylight/adsal/configuration/integrationtest/src/test/resources/logback.xml diff --git a/opendaylight/connectionmanager/api/pom.xml b/opendaylight/adsal/connectionmanager/api/pom.xml similarity index 96% rename from opendaylight/connectionmanager/api/pom.xml rename to opendaylight/adsal/connectionmanager/api/pom.xml index 2718ed1afe..aee485419c 100644 --- a/opendaylight/connectionmanager/api/pom.xml +++ b/opendaylight/adsal/connectionmanager/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight connectionmanager diff --git a/opendaylight/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/ConnectionMgmtScheme.java b/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/ConnectionMgmtScheme.java similarity index 100% rename from opendaylight/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/ConnectionMgmtScheme.java rename to opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/ConnectionMgmtScheme.java diff --git a/opendaylight/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/IConnectionManager.java b/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/IConnectionManager.java similarity index 100% rename from opendaylight/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/IConnectionManager.java rename to opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/IConnectionManager.java diff --git a/opendaylight/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/NodeAccessPermission.java b/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/NodeAccessPermission.java similarity index 100% rename from opendaylight/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/NodeAccessPermission.java rename to opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/NodeAccessPermission.java diff --git a/opendaylight/connectionmanager/implementation/pom.xml b/opendaylight/adsal/connectionmanager/implementation/pom.xml similarity index 97% rename from opendaylight/connectionmanager/implementation/pom.xml rename to opendaylight/adsal/connectionmanager/implementation/pom.xml index fe2514e58a..b8293609a2 100644 --- a/opendaylight/connectionmanager/implementation/pom.xml +++ b/opendaylight/adsal/connectionmanager/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight connectionmanager.implementation diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/Activator.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/Activator.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/Activator.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/Activator.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionManager.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionManager.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionManager.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionManager.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEvent.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEvent.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEvent.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEvent.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEventType.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEventType.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEventType.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEventType.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AbstractScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AbstractScheme.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AbstractScheme.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AbstractScheme.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AnyControllerScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AnyControllerScheme.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AnyControllerScheme.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AnyControllerScheme.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/ControllerConfig.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/ControllerConfig.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/ControllerConfig.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/ControllerConfig.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/LoadBalancedScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/LoadBalancedScheme.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/LoadBalancedScheme.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/LoadBalancedScheme.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/RoundRobinScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/RoundRobinScheme.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/RoundRobinScheme.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/RoundRobinScheme.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SchemeFactory.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SchemeFactory.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SchemeFactory.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SchemeFactory.java diff --git a/opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SingleControllerScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SingleControllerScheme.java similarity index 100% rename from opendaylight/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SingleControllerScheme.java rename to opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SingleControllerScheme.java diff --git a/opendaylight/containermanager/api/pom.xml b/opendaylight/adsal/containermanager/api/pom.xml similarity index 97% rename from opendaylight/containermanager/api/pom.xml rename to opendaylight/adsal/containermanager/api/pom.xml index c9b54a1b6c..31b209410d 100644 --- a/opendaylight/containermanager/api/pom.xml +++ b/opendaylight/adsal/containermanager/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight containermanager diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerChangeEvent.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerChangeEvent.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerChangeEvent.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerChangeEvent.java diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerConfig.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerConfig.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerConfig.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerConfig.java diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerData.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerData.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerData.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerData.java diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowChangeEvent.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowChangeEvent.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowChangeEvent.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowChangeEvent.java diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowConfig.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowConfig.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowConfig.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowConfig.java diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerAuthorization.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerAuthorization.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerAuthorization.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerAuthorization.java diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManager.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManager.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManager.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManager.java diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManagerShell.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManagerShell.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManagerShell.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManagerShell.java diff --git a/opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/NodeConnectorsChangeEvent.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/NodeConnectorsChangeEvent.java similarity index 100% rename from opendaylight/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/NodeConnectorsChangeEvent.java rename to opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/NodeConnectorsChangeEvent.java diff --git a/opendaylight/containermanager/implementation/pom.xml b/opendaylight/adsal/containermanager/implementation/pom.xml similarity index 98% rename from opendaylight/containermanager/implementation/pom.xml rename to opendaylight/adsal/containermanager/implementation/pom.xml index 013cd62576..b096ba6c01 100644 --- a/opendaylight/containermanager/implementation/pom.xml +++ b/opendaylight/adsal/containermanager/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight containermanager.implementation diff --git a/opendaylight/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java b/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java similarity index 100% rename from opendaylight/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java rename to opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java diff --git a/opendaylight/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java b/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java similarity index 100% rename from opendaylight/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java rename to opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java diff --git a/opendaylight/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java b/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java similarity index 100% rename from opendaylight/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java rename to opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java diff --git a/opendaylight/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/IContainerInternal.java b/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/IContainerInternal.java similarity index 100% rename from opendaylight/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/IContainerInternal.java rename to opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/IContainerInternal.java diff --git a/opendaylight/containermanager/it.implementation/pom.xml b/opendaylight/adsal/containermanager/it.implementation/pom.xml similarity index 97% rename from opendaylight/containermanager/it.implementation/pom.xml rename to opendaylight/adsal/containermanager/it.implementation/pom.xml index 8e0475d4a3..e5ad7a7508 100644 --- a/opendaylight/containermanager/it.implementation/pom.xml +++ b/opendaylight/adsal/containermanager/it.implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight containermanager.it.implementation diff --git a/opendaylight/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java b/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java similarity index 100% rename from opendaylight/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java rename to opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java diff --git a/opendaylight/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java b/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java similarity index 100% rename from opendaylight/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java rename to opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java diff --git a/opendaylight/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java b/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java similarity index 100% rename from opendaylight/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java rename to opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java diff --git a/opendaylight/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerImplTest.java b/opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerImplTest.java similarity index 100% rename from opendaylight/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerImplTest.java rename to opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerImplTest.java diff --git a/opendaylight/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerManagerTest.java b/opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerManagerTest.java similarity index 100% rename from opendaylight/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerManagerTest.java rename to opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerManagerTest.java diff --git a/opendaylight/containermanager/shell/pom.xml b/opendaylight/adsal/containermanager/shell/pom.xml similarity index 96% rename from opendaylight/containermanager/shell/pom.xml rename to opendaylight/adsal/containermanager/shell/pom.xml index c1c2d2055b..065df2c829 100644 --- a/opendaylight/containermanager/shell/pom.xml +++ b/opendaylight/adsal/containermanager/shell/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight containermanager.shell ${containermanager.shell.version} diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainer.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainer.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainer.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainer.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerEntry.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerEntry.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerEntry.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerEntry.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerFlow.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerFlow.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerFlow.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerFlow.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedGroups.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedGroups.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedGroups.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedGroups.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedResources.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedResources.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedResources.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedResources.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetResourcesForGroup.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetResourcesForGroup.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetResourcesForGroup.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetResourcesForGroup.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetRoles.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetRoles.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetRoles.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetRoles.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserLevel.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserLevel.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserLevel.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserLevel.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserResources.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserResources.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserResources.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserResources.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/CreateContainer.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/CreateContainer.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/CreateContainer.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/CreateContainer.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Pfc.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Pfc.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Pfc.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Pfc.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psc.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psc.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psc.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psc.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psd.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psd.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psd.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psd.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psm.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psm.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psm.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psm.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psp.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psp.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psp.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psp.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainer.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainer.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainer.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainer.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerEntry.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerEntry.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerEntry.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerEntry.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerFlow.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerFlow.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerFlow.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerFlow.java diff --git a/opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/SaveConfig.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/SaveConfig.java similarity index 100% rename from opendaylight/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/SaveConfig.java rename to opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/SaveConfig.java diff --git a/opendaylight/containermanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/adsal/containermanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml similarity index 100% rename from opendaylight/containermanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml rename to opendaylight/adsal/containermanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml diff --git a/opendaylight/containermanager/shell/src/test/java/org/opendaylight/controller/containermanager/shell/ContainerManagerShellTest.java b/opendaylight/adsal/containermanager/shell/src/test/java/org/opendaylight/controller/containermanager/shell/ContainerManagerShellTest.java similarity index 100% rename from opendaylight/containermanager/shell/src/test/java/org/opendaylight/controller/containermanager/shell/ContainerManagerShellTest.java rename to opendaylight/adsal/containermanager/shell/src/test/java/org/opendaylight/controller/containermanager/shell/ContainerManagerShellTest.java diff --git a/opendaylight/dummy-console/README b/opendaylight/adsal/dummy-console/README similarity index 100% rename from opendaylight/dummy-console/README rename to opendaylight/adsal/dummy-console/README diff --git a/opendaylight/dummy-console/pom.xml b/opendaylight/adsal/dummy-console/pom.xml similarity index 95% rename from opendaylight/dummy-console/pom.xml rename to opendaylight/adsal/dummy-console/pom.xml index 4195e53310..c8a1a22ae7 100644 --- a/opendaylight/dummy-console/pom.xml +++ b/opendaylight/adsal/dummy-console/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../commons/opendaylight + ../../commons/opendaylight dummy-console 1.2.0-SNAPSHOT diff --git a/opendaylight/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandInterpreter.java b/opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandInterpreter.java similarity index 100% rename from opendaylight/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandInterpreter.java rename to opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandInterpreter.java diff --git a/opendaylight/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandProvider.java b/opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandProvider.java similarity index 100% rename from opendaylight/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandProvider.java rename to opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandProvider.java diff --git a/features/adsal-compatibility/pom.xml b/opendaylight/adsal/features/adsal-compatibility/pom.xml similarity index 96% rename from features/adsal-compatibility/pom.xml rename to opendaylight/adsal/features/adsal-compatibility/pom.xml index 7b8af64445..d8d1888ba3 100644 --- a/features/adsal-compatibility/pom.xml +++ b/opendaylight/adsal/features/adsal-compatibility/pom.xml @@ -11,7 +11,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../opendaylight/commons/opendaylight + ../../../../opendaylight/commons/opendaylight features-adsal-compatibility jar diff --git a/features/adsal-compatibility/src/main/resources/features.xml b/opendaylight/adsal/features/adsal-compatibility/src/main/resources/features.xml similarity index 100% rename from features/adsal-compatibility/src/main/resources/features.xml rename to opendaylight/adsal/features/adsal-compatibility/src/main/resources/features.xml diff --git a/features/adsal/pom.xml b/opendaylight/adsal/features/adsal/pom.xml similarity index 98% rename from features/adsal/pom.xml rename to opendaylight/adsal/features/adsal/pom.xml index 429edf828f..57fa1e2c3f 100644 --- a/features/adsal/pom.xml +++ b/opendaylight/adsal/features/adsal/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../opendaylight/commons/opendaylight + ../../../../opendaylight/commons/opendaylight features-adsal ${sal.version} diff --git a/features/adsal/src/main/resources/features.xml b/opendaylight/adsal/features/adsal/src/main/resources/features.xml similarity index 100% rename from features/adsal/src/main/resources/features.xml rename to opendaylight/adsal/features/adsal/src/main/resources/features.xml diff --git a/features/base/pom.xml b/opendaylight/adsal/features/base/pom.xml similarity index 98% rename from features/base/pom.xml rename to opendaylight/adsal/features/base/pom.xml index b7ab3ca757..795a323cc1 100644 --- a/features/base/pom.xml +++ b/opendaylight/adsal/features/base/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../opendaylight/commons/opendaylight + ../../../../opendaylight/commons/opendaylight features-base jar @@ -31,10 +31,6 @@ org.opendaylight.controller karaf-tomcat-security - - org.opendaylight.controller.thirdparty - ganymed - com.fasterxml.jackson.core jackson-annotations @@ -447,7 +443,6 @@ org.opendaylight.yangtools features-test - 0.7.0-SNAPSHOT diff --git a/features/base/src/main/resources/features.xml b/opendaylight/adsal/features/base/src/main/resources/features.xml similarity index 99% rename from features/base/src/main/resources/features.xml rename to opendaylight/adsal/features/base/src/main/resources/features.xml index d7d8e0ddac..d6802acd0e 100644 --- a/features/base/src/main/resources/features.xml +++ b/opendaylight/adsal/features/base/src/main/resources/features.xml @@ -36,7 +36,6 @@ wrap:mvn:io.netty/netty-common/${netty.version} wrap:mvn:io.netty/netty-handler/${netty.version} wrap:mvn:io.netty/netty-codec-http/${netty.version} - mvn:org.opendaylight.controller.thirdparty/ganymed/1.2.0-SNAPSHOT odl-base-gemini-web diff --git a/features/controller/pom.xml b/opendaylight/adsal/features/controller/pom.xml similarity index 95% rename from features/controller/pom.xml rename to opendaylight/adsal/features/controller/pom.xml index 5dd2bd4a2a..34be32ff7f 100644 --- a/features/controller/pom.xml +++ b/opendaylight/adsal/features/controller/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../opendaylight/commons/opendaylight + ../../../../opendaylight/commons/opendaylight controller-features pom diff --git a/features/controller/src/main/resources/features.xml b/opendaylight/adsal/features/controller/src/main/resources/features.xml similarity index 100% rename from features/controller/src/main/resources/features.xml rename to opendaylight/adsal/features/controller/src/main/resources/features.xml diff --git a/features/extras/pom.xml b/opendaylight/adsal/features/extras/pom.xml similarity index 97% rename from features/extras/pom.xml rename to opendaylight/adsal/features/extras/pom.xml index e4356e6b49..103fbefad4 100644 --- a/features/extras/pom.xml +++ b/opendaylight/adsal/features/extras/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../opendaylight/commons/opendaylight + ../../../../opendaylight/commons/opendaylight extras-features kar diff --git a/features/extras/src/main/resources/features.xml b/opendaylight/adsal/features/extras/src/main/resources/features.xml similarity index 100% rename from features/extras/src/main/resources/features.xml rename to opendaylight/adsal/features/extras/src/main/resources/features.xml diff --git a/features/nsf/pom.xml b/opendaylight/adsal/features/nsf/pom.xml similarity index 99% rename from features/nsf/pom.xml rename to opendaylight/adsal/features/nsf/pom.xml index 00dc219b39..0c8e838009 100644 --- a/features/nsf/pom.xml +++ b/opendaylight/adsal/features/nsf/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../opendaylight/commons/opendaylight + ../../../../opendaylight/commons/opendaylight features-nsf ${nsf.version} diff --git a/features/nsf/src/main/resources/features.xml b/opendaylight/adsal/features/nsf/src/main/resources/features.xml similarity index 100% rename from features/nsf/src/main/resources/features.xml rename to opendaylight/adsal/features/nsf/src/main/resources/features.xml diff --git a/opendaylight/forwarding/staticrouting/pom.xml b/opendaylight/adsal/forwarding/staticrouting/pom.xml similarity index 97% rename from opendaylight/forwarding/staticrouting/pom.xml rename to opendaylight/adsal/forwarding/staticrouting/pom.xml index b006cece40..526c384750 100644 --- a/opendaylight/forwarding/staticrouting/pom.xml +++ b/opendaylight/adsal/forwarding/staticrouting/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight forwarding.staticrouting diff --git a/opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IForwardingStaticRouting.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IForwardingStaticRouting.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IForwardingStaticRouting.java rename to opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IForwardingStaticRouting.java diff --git a/opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IStaticRoutingAware.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IStaticRoutingAware.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IStaticRoutingAware.java rename to opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IStaticRoutingAware.java diff --git a/opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRoute.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRoute.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRoute.java rename to opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRoute.java diff --git a/opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfig.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfig.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfig.java rename to opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfig.java diff --git a/opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/Activator.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/Activator.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/Activator.java rename to opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/Activator.java diff --git a/opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementation.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementation.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementation.java rename to opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementation.java diff --git a/opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfigTest.java b/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfigTest.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfigTest.java rename to opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfigTest.java diff --git a/opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteTest.java b/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteTest.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteTest.java rename to opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteTest.java diff --git a/opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementationTest.java b/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementationTest.java similarity index 100% rename from opendaylight/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementationTest.java rename to opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementationTest.java diff --git a/opendaylight/forwardingrulesmanager/api/pom.xml b/opendaylight/adsal/forwardingrulesmanager/api/pom.xml similarity index 97% rename from opendaylight/forwardingrulesmanager/api/pom.xml rename to opendaylight/adsal/forwardingrulesmanager/api/pom.xml index 3f667e16f0..fc3549a597 100644 --- a/opendaylight/forwardingrulesmanager/api/pom.xml +++ b/opendaylight/adsal/forwardingrulesmanager/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight forwardingrulesmanager diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowConfig.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowConfig.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowConfig.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowConfig.java diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntry.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntry.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntry.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntry.java diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntryInstall.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntryInstall.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntryInstall.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntryInstall.java diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManager.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManager.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManager.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManager.java diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManagerAware.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManagerAware.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManagerAware.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManagerAware.java diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroup.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroup.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroup.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroup.java diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupChangeListener.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupChangeListener.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupChangeListener.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupChangeListener.java diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupConfig.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupConfig.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupConfig.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupConfig.java diff --git a/opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupProvider.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupProvider.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupProvider.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupProvider.java diff --git a/opendaylight/forwardingrulesmanager/api/src/test/java/org/opendaylight/controller/forwardingrulesmanager/frmTest.java b/opendaylight/adsal/forwardingrulesmanager/api/src/test/java/org/opendaylight/controller/forwardingrulesmanager/frmTest.java similarity index 100% rename from opendaylight/forwardingrulesmanager/api/src/test/java/org/opendaylight/controller/forwardingrulesmanager/frmTest.java rename to opendaylight/adsal/forwardingrulesmanager/api/src/test/java/org/opendaylight/controller/forwardingrulesmanager/frmTest.java diff --git a/opendaylight/forwardingrulesmanager/implementation/pom.xml b/opendaylight/adsal/forwardingrulesmanager/implementation/pom.xml similarity index 98% rename from opendaylight/forwardingrulesmanager/implementation/pom.xml rename to opendaylight/adsal/forwardingrulesmanager/implementation/pom.xml index 959b71f855..80a275c03c 100644 --- a/opendaylight/forwardingrulesmanager/implementation/pom.xml +++ b/opendaylight/adsal/forwardingrulesmanager/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight forwardingrulesmanager.implementation diff --git a/opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/implementation/data/FlowEntryDistributionOrder.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/implementation/data/FlowEntryDistributionOrder.java similarity index 100% rename from opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/implementation/data/FlowEntryDistributionOrder.java rename to opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/implementation/data/FlowEntryDistributionOrder.java diff --git a/opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/Activator.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/Activator.java similarity index 100% rename from opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/Activator.java rename to opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/Activator.java diff --git a/opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/FlowEntryDistributionOrderFutureTask.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/FlowEntryDistributionOrderFutureTask.java similarity index 100% rename from opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/FlowEntryDistributionOrderFutureTask.java rename to opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/FlowEntryDistributionOrderFutureTask.java diff --git a/opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java similarity index 100% rename from opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java rename to opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java diff --git a/opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerCLI.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerCLI.java similarity index 100% rename from opendaylight/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerCLI.java rename to opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerCLI.java diff --git a/opendaylight/forwardingrulesmanager/integrationtest/pom.xml b/opendaylight/adsal/forwardingrulesmanager/integrationtest/pom.xml similarity index 95% rename from opendaylight/forwardingrulesmanager/integrationtest/pom.xml rename to opendaylight/adsal/forwardingrulesmanager/integrationtest/pom.xml index 60b934a492..0f9b3caea9 100644 --- a/opendaylight/forwardingrulesmanager/integrationtest/pom.xml +++ b/opendaylight/adsal/forwardingrulesmanager/integrationtest/pom.xml @@ -11,9 +11,9 @@ forwardingrulesmanager.integrationtest 0.5.0-SNAPSHOT - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec - ../implementation/target/jacoco.exec + ../../implementation/target/jacoco.exec @@ -141,7 +141,7 @@ org.jacoco jacoco-maven-plugin - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec org.opendaylight.controller.* diff --git a/opendaylight/forwardingrulesmanager/integrationtest/src/test/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerIT.java b/opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerIT.java similarity index 100% rename from opendaylight/forwardingrulesmanager/integrationtest/src/test/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerIT.java rename to opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerIT.java diff --git a/opendaylight/forwardingrulesmanager/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/resources/logback.xml similarity index 100% rename from opendaylight/forwardingrulesmanager/integrationtest/src/test/resources/logback.xml rename to opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/resources/logback.xml diff --git a/opendaylight/hosttracker/api/pom.xml b/opendaylight/adsal/hosttracker/api/pom.xml similarity index 97% rename from opendaylight/hosttracker/api/pom.xml rename to opendaylight/adsal/hosttracker/api/pom.xml index 10532baa6e..6bc28f03c3 100644 --- a/opendaylight/hosttracker/api/pom.xml +++ b/opendaylight/adsal/hosttracker/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight hosttracker 0.6.0-SNAPSHOT diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/HostIdFactory.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/HostIdFactory.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/HostIdFactory.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/HostIdFactory.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostId.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostId.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostId.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostId.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPHostId.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPHostId.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPHostId.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPHostId.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPMacHostId.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPMacHostId.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPMacHostId.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPMacHostId.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java similarity index 100% rename from opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java rename to opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java diff --git a/opendaylight/hosttracker/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java b/opendaylight/adsal/hosttracker/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java similarity index 100% rename from opendaylight/hosttracker/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java rename to opendaylight/adsal/hosttracker/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java diff --git a/opendaylight/hosttracker/implementation/pom.xml b/opendaylight/adsal/hosttracker/implementation/pom.xml similarity index 98% rename from opendaylight/hosttracker/implementation/pom.xml rename to opendaylight/adsal/hosttracker/implementation/pom.xml index 370f88defa..64254e8b92 100644 --- a/opendaylight/hosttracker/implementation/pom.xml +++ b/opendaylight/adsal/hosttracker/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight hosttracker.implementation 0.6.0-SNAPSHOT diff --git a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java b/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java similarity index 100% rename from opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java rename to opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java diff --git a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java b/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java similarity index 100% rename from opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java rename to opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java diff --git a/opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTrackerCallable.java b/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTrackerCallable.java similarity index 100% rename from opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTrackerCallable.java rename to opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTrackerCallable.java diff --git a/opendaylight/hosttracker/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerTest.java b/opendaylight/adsal/hosttracker/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerTest.java similarity index 100% rename from opendaylight/hosttracker/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerTest.java rename to opendaylight/adsal/hosttracker/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerTest.java diff --git a/opendaylight/hosttracker/integrationtest/pom.xml b/opendaylight/adsal/hosttracker/integrationtest/pom.xml similarity index 95% rename from opendaylight/hosttracker/integrationtest/pom.xml rename to opendaylight/adsal/hosttracker/integrationtest/pom.xml index dabccf3f71..63610cc3e3 100644 --- a/opendaylight/hosttracker/integrationtest/pom.xml +++ b/opendaylight/adsal/hosttracker/integrationtest/pom.xml @@ -11,9 +11,9 @@ hosttracker.integrationtest 0.6.0-SNAPSHOT - ../implementaiton/target/jacoco-it.exec + ../../implementaiton/target/jacoco-it.exec - ../implementation/target/jacoco.exec + ../../implementation/target/jacoco.exec @@ -134,7 +134,7 @@ org.jacoco jacoco-maven-plugin - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec org.opendaylight.controller.* diff --git a/opendaylight/hosttracker/integrationtest/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerIT.java b/opendaylight/adsal/hosttracker/integrationtest/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerIT.java similarity index 100% rename from opendaylight/hosttracker/integrationtest/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerIT.java rename to opendaylight/adsal/hosttracker/integrationtest/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerIT.java diff --git a/opendaylight/hosttracker/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/hosttracker/integrationtest/src/test/resources/logback.xml similarity index 100% rename from opendaylight/hosttracker/integrationtest/src/test/resources/logback.xml rename to opendaylight/adsal/hosttracker/integrationtest/src/test/resources/logback.xml diff --git a/opendaylight/hosttracker/shell/pom.xml b/opendaylight/adsal/hosttracker/shell/pom.xml similarity index 96% rename from opendaylight/hosttracker/shell/pom.xml rename to opendaylight/adsal/hosttracker/shell/pom.xml index 9088ae359b..0292e113ee 100644 --- a/opendaylight/hosttracker/shell/pom.xml +++ b/opendaylight/adsal/hosttracker/shell/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight hosttracker.shell ${hosttracker.shell.version} diff --git a/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java b/opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java similarity index 100% rename from opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java rename to opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java diff --git a/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java b/opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java similarity index 100% rename from opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java rename to opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java diff --git a/opendaylight/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/adsal/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml similarity index 100% rename from opendaylight/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml rename to opendaylight/adsal/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml diff --git a/opendaylight/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java b/opendaylight/adsal/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java similarity index 100% rename from opendaylight/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java rename to opendaylight/adsal/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java diff --git a/opendaylight/hosttracker_new/api/pom.xml b/opendaylight/adsal/hosttracker_new/api/pom.xml similarity index 97% rename from opendaylight/hosttracker_new/api/pom.xml rename to opendaylight/adsal/hosttracker_new/api/pom.xml index db27345d18..cdb3fd95b6 100644 --- a/opendaylight/hosttracker_new/api/pom.xml +++ b/opendaylight/adsal/hosttracker_new/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight hosttracker_new 0.5.0-SNAPSHOT diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java diff --git a/opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java rename to opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java diff --git a/opendaylight/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java b/opendaylight/adsal/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java similarity index 100% rename from opendaylight/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java rename to opendaylight/adsal/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java diff --git a/opendaylight/hosttracker_new/implementation/pom.xml b/opendaylight/adsal/hosttracker_new/implementation/pom.xml similarity index 98% rename from opendaylight/hosttracker_new/implementation/pom.xml rename to opendaylight/adsal/hosttracker_new/implementation/pom.xml index d3661a12c8..268465eed3 100644 --- a/opendaylight/hosttracker_new/implementation/pom.xml +++ b/opendaylight/adsal/hosttracker_new/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight hosttracker_new.implementation 0.5.0-SNAPSHOT diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java diff --git a/opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java rename to opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java rename to opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java rename to opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java rename to opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java rename to opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java rename to opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java rename to opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java diff --git a/opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java similarity index 100% rename from opendaylight/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java rename to opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java diff --git a/opendaylight/karaf-tomcat-security/pom.xml b/opendaylight/adsal/karaf-tomcat-security/pom.xml similarity index 96% rename from opendaylight/karaf-tomcat-security/pom.xml rename to opendaylight/adsal/karaf-tomcat-security/pom.xml index 30d57d048a..d2dc040bba 100644 --- a/opendaylight/karaf-tomcat-security/pom.xml +++ b/opendaylight/adsal/karaf-tomcat-security/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../commons/opendaylight + ../../commons/opendaylight karaf-tomcat-security diff --git a/opendaylight/karaf-tomcat-security/src/main/java/org/opendaylight/controller/karafsecurity/ControllerCustomRealm.java b/opendaylight/adsal/karaf-tomcat-security/src/main/java/org/opendaylight/controller/karafsecurity/ControllerCustomRealm.java similarity index 100% rename from opendaylight/karaf-tomcat-security/src/main/java/org/opendaylight/controller/karafsecurity/ControllerCustomRealm.java rename to opendaylight/adsal/karaf-tomcat-security/src/main/java/org/opendaylight/controller/karafsecurity/ControllerCustomRealm.java diff --git a/opendaylight/logging/bridge/pom.xml b/opendaylight/adsal/logging/bridge/pom.xml similarity index 97% rename from opendaylight/logging/bridge/pom.xml rename to opendaylight/adsal/logging/bridge/pom.xml index dc37e30179..5ebbe4564b 100644 --- a/opendaylight/logging/bridge/pom.xml +++ b/opendaylight/adsal/logging/bridge/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight logging.bridge diff --git a/opendaylight/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/Activator.java b/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/Activator.java similarity index 100% rename from opendaylight/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/Activator.java rename to opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/Activator.java diff --git a/opendaylight/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImpl.java b/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImpl.java similarity index 100% rename from opendaylight/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImpl.java rename to opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImpl.java diff --git a/opendaylight/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/UncaughtExceptionPolicy.java b/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/UncaughtExceptionPolicy.java similarity index 100% rename from opendaylight/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/UncaughtExceptionPolicy.java rename to opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/UncaughtExceptionPolicy.java diff --git a/opendaylight/logging/bridge/src/test/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImplTest.java b/opendaylight/adsal/logging/bridge/src/test/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImplTest.java similarity index 100% rename from opendaylight/logging/bridge/src/test/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImplTest.java rename to opendaylight/adsal/logging/bridge/src/test/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImplTest.java diff --git a/opendaylight/northbound/archetype-app-northbound/pom.xml b/opendaylight/adsal/northbound/archetype-app-northbound/pom.xml similarity index 100% rename from opendaylight/northbound/archetype-app-northbound/pom.xml rename to opendaylight/adsal/northbound/archetype-app-northbound/pom.xml diff --git a/opendaylight/northbound/archetype-app-northbound/src/main/resources/META-INF/maven/archetype-metadata.xml b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/META-INF/maven/archetype-metadata.xml similarity index 100% rename from opendaylight/northbound/archetype-app-northbound/src/main/resources/META-INF/maven/archetype-metadata.xml rename to opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/META-INF/maven/archetype-metadata.xml diff --git a/opendaylight/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml similarity index 97% rename from opendaylight/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml rename to opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml index adb0c98705..73bdf0921b 100644 --- a/opendaylight/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml +++ b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml @@ -6,7 +6,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight ${artifactId} diff --git a/opendaylight/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/java/Northbound.java b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/java/Northbound.java similarity index 100% rename from opendaylight/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/java/Northbound.java rename to opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/java/Northbound.java diff --git a/opendaylight/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/archetype-app-northbound/src/test/resources/projects/basic/archetype.properties b/opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/archetype.properties similarity index 100% rename from opendaylight/northbound/archetype-app-northbound/src/test/resources/projects/basic/archetype.properties rename to opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/archetype.properties diff --git a/opendaylight/northbound/archetype-app-northbound/src/test/resources/projects/basic/goal.txt b/opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/goal.txt similarity index 100% rename from opendaylight/northbound/archetype-app-northbound/src/test/resources/projects/basic/goal.txt rename to opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/goal.txt diff --git a/opendaylight/northbound/bundlescanner/api/pom.xml b/opendaylight/adsal/northbound/bundlescanner/api/pom.xml similarity index 96% rename from opendaylight/northbound/bundlescanner/api/pom.xml rename to opendaylight/adsal/northbound/bundlescanner/api/pom.xml index 78bfd38579..d94272b342 100644 --- a/opendaylight/northbound/bundlescanner/api/pom.xml +++ b/opendaylight/adsal/northbound/bundlescanner/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../commons/opendaylight + ../../../../commons/opendaylight bundlescanner diff --git a/opendaylight/northbound/bundlescanner/api/src/main/java/org/opendaylight/controller/northbound/bundlescanner/IBundleScanService.java b/opendaylight/adsal/northbound/bundlescanner/api/src/main/java/org/opendaylight/controller/northbound/bundlescanner/IBundleScanService.java similarity index 100% rename from opendaylight/northbound/bundlescanner/api/src/main/java/org/opendaylight/controller/northbound/bundlescanner/IBundleScanService.java rename to opendaylight/adsal/northbound/bundlescanner/api/src/main/java/org/opendaylight/controller/northbound/bundlescanner/IBundleScanService.java diff --git a/opendaylight/northbound/bundlescanner/implementation/pom.xml b/opendaylight/adsal/northbound/bundlescanner/implementation/pom.xml similarity index 97% rename from opendaylight/northbound/bundlescanner/implementation/pom.xml rename to opendaylight/adsal/northbound/bundlescanner/implementation/pom.xml index 5694b2adcf..d4d57a1be9 100644 --- a/opendaylight/northbound/bundlescanner/implementation/pom.xml +++ b/opendaylight/adsal/northbound/bundlescanner/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../commons/opendaylight + ../../../../commons/opendaylight bundlescanner.implementation diff --git a/opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/Activator.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/Activator.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/Activator.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/Activator.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleInfo.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleInfo.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleInfo.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleInfo.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanServiceImpl.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanServiceImpl.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanServiceImpl.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanServiceImpl.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java similarity index 98% rename from opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java index c590da4dbc..2fee2720c2 100644 --- a/opendaylight/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java +++ b/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java @@ -294,8 +294,8 @@ import org.slf4j.LoggerFactory; if (classes == null || classes.size() == 0) return; Map names = new HashMap(); StringBuilder conflictsMsg = new StringBuilder(); - for (Class c : classes) { - XmlRootElement root = (XmlRootElement) c.getAnnotation(XmlRootElement.class); + for (Class c : classes) { + XmlRootElement root = c.getAnnotation(XmlRootElement.class); if (root == null) continue; String rootName = root.name(); if ("##default".equals(rootName)) { diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/Animal.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Animal.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/Animal.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Animal.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/BasePerson.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/BasePerson.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/BasePerson.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/BasePerson.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/Mammal.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Mammal.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/Mammal.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Mammal.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/NoAnnotation.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NoAnnotation.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/NoAnnotation.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NoAnnotation.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/NonRelevantAnnotation.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NonRelevantAnnotation.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/NonRelevantAnnotation.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NonRelevantAnnotation.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/Person.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Person.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_base/Person.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Person.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_misc/Misc.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_misc/Misc.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_misc/Misc.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_misc/Misc.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/NoAnnotation.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/NoAnnotation.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/NoAnnotation.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/NoAnnotation.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/Zoo.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/Zoo.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/Zoo.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/Zoo.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Agent.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Agent.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Agent.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Agent.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Customer.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Customer.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Customer.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Customer.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/NoAnnotation.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/NoAnnotation.java similarity index 100% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/NoAnnotation.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/NoAnnotation.java diff --git a/opendaylight/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java similarity index 98% rename from opendaylight/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java rename to opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java index 1c35404c80..c2efbe67a9 100644 --- a/opendaylight/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java +++ b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java @@ -7,8 +7,6 @@ */ package org.opendaylight.controller.northbound.bundlescanner.internal; - - import java.io.File; import java.io.FileFilter; import java.net.MalformedURLException; @@ -37,8 +35,8 @@ import org.osgi.framework.Constants; import org.springframework.osgi.mock.MockBundle; import org.springframework.osgi.mock.MockBundleContext; -import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class BundleScannerTest { @@ -218,7 +216,7 @@ public class BundleScannerTest { } @Override - public Enumeration findEntries(String path, String filePattern, boolean recurse) { + public Enumeration findEntries(String path, String filePattern, boolean recurse) { return Collections.enumeration(classes); } diff --git a/opendaylight/northbound/commons/pom.xml b/opendaylight/adsal/northbound/commons/pom.xml similarity index 98% rename from opendaylight/northbound/commons/pom.xml rename to opendaylight/adsal/northbound/commons/pom.xml index 9d229e4e70..8290bcdf38 100644 --- a/opendaylight/northbound/commons/pom.xml +++ b/opendaylight/adsal/northbound/commons/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight commons.northbound diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/JacksonJsonProcessingExceptionMapper.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/JacksonJsonProcessingExceptionMapper.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/JacksonJsonProcessingExceptionMapper.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/JacksonJsonProcessingExceptionMapper.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/NorthboundApplication.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/NorthboundApplication.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/NorthboundApplication.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/NorthboundApplication.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/RestMessages.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/RestMessages.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/RestMessages.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/RestMessages.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/BadRequestException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/BadRequestException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/BadRequestException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/BadRequestException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/InternalServerErrorException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/InternalServerErrorException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/InternalServerErrorException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/InternalServerErrorException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowed.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowed.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowed.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowed.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowedException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowedException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowedException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowedException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotAcceptableException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotAcceptableException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotAcceptableException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotAcceptableException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplemented.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplemented.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplemented.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplemented.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplementedException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplementedException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplementedException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplementedException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceConflictException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceConflictException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceConflictException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceConflictException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceForbiddenException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceForbiddenException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceForbiddenException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceForbiddenException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceGoneException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceGoneException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceGoneException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceGoneException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceNotFoundException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceNotFoundException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceNotFoundException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceNotFoundException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ServiceUnavailableException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ServiceUnavailableException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ServiceUnavailableException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ServiceUnavailableException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnauthorizedException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnauthorizedException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnauthorizedException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnauthorizedException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnsupportedMediaTypeException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnsupportedMediaTypeException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnsupportedMediaTypeException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnsupportedMediaTypeException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/package-info.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/package-info.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/package-info.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/package-info.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Expression.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Expression.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Expression.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Expression.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/types/StringList.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/types/StringList.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/types/StringList.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/types/StringList.java diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java similarity index 100% rename from opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java rename to opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java diff --git a/opendaylight/northbound/commons/src/main/javacc/fiql.jj b/opendaylight/adsal/northbound/commons/src/main/javacc/fiql.jj similarity index 100% rename from opendaylight/northbound/commons/src/main/javacc/fiql.jj rename to opendaylight/adsal/northbound/commons/src/main/javacc/fiql.jj diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/CommonsNorthboundTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/CommonsNorthboundTest.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/CommonsNorthboundTest.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/CommonsNorthboundTest.java diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/exception/CommonsNorthboundExceptionTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/exception/CommonsNorthboundExceptionTest.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/exception/CommonsNorthboundExceptionTest.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/exception/CommonsNorthboundExceptionTest.java diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java similarity index 100% rename from opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java rename to opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java diff --git a/opendaylight/northbound/commons/src/test/resources/logback.xml b/opendaylight/adsal/northbound/commons/src/test/resources/logback.xml similarity index 100% rename from opendaylight/northbound/commons/src/test/resources/logback.xml rename to opendaylight/adsal/northbound/commons/src/test/resources/logback.xml diff --git a/opendaylight/northbound/connectionmanager/enunciate.xml b/opendaylight/adsal/northbound/connectionmanager/enunciate.xml similarity index 100% rename from opendaylight/northbound/connectionmanager/enunciate.xml rename to opendaylight/adsal/northbound/connectionmanager/enunciate.xml diff --git a/opendaylight/northbound/connectionmanager/pom.xml b/opendaylight/adsal/northbound/connectionmanager/pom.xml similarity index 98% rename from opendaylight/northbound/connectionmanager/pom.xml rename to opendaylight/adsal/northbound/connectionmanager/pom.xml index 893dcd14f3..b68bc25545 100644 --- a/opendaylight/northbound/connectionmanager/pom.xml +++ b/opendaylight/adsal/northbound/connectionmanager/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight connectionmanager.northbound diff --git a/opendaylight/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/ConnectionManagerNorthbound.java b/opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/ConnectionManagerNorthbound.java similarity index 100% rename from opendaylight/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/ConnectionManagerNorthbound.java rename to opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/ConnectionManagerNorthbound.java diff --git a/opendaylight/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/Nodes.java b/opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/Nodes.java similarity index 100% rename from opendaylight/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/Nodes.java rename to opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/Nodes.java diff --git a/opendaylight/northbound/connectionmanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/connectionmanager/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/connectionmanager/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/connectionmanager/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/containermanager/enunciate.xml b/opendaylight/adsal/northbound/containermanager/enunciate.xml similarity index 100% rename from opendaylight/northbound/containermanager/enunciate.xml rename to opendaylight/adsal/northbound/containermanager/enunciate.xml diff --git a/opendaylight/northbound/containermanager/pom.xml b/opendaylight/adsal/northbound/containermanager/pom.xml similarity index 98% rename from opendaylight/northbound/containermanager/pom.xml rename to opendaylight/adsal/northbound/containermanager/pom.xml index 74fd115dee..8898a06f64 100644 --- a/opendaylight/northbound/containermanager/pom.xml +++ b/opendaylight/adsal/northbound/containermanager/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight containermanager.northbound diff --git a/opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerConfigs.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerConfigs.java similarity index 100% rename from opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerConfigs.java rename to opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerConfigs.java diff --git a/opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthbound.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthbound.java similarity index 100% rename from opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthbound.java rename to opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthbound.java diff --git a/opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthboundRSApplication.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthboundRSApplication.java similarity index 100% rename from opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthboundRSApplication.java rename to opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthboundRSApplication.java diff --git a/opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/FlowSpecConfigs.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/FlowSpecConfigs.java similarity index 100% rename from opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/FlowSpecConfigs.java rename to opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/FlowSpecConfigs.java diff --git a/opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/StringList.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/StringList.java similarity index 100% rename from opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/StringList.java rename to opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/StringList.java diff --git a/opendaylight/northbound/containermanager/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/northbound/containermanager/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/northbound/containermanager/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/northbound/containermanager/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/northbound/containermanager/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/northbound/containermanager/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/northbound/containermanager/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/northbound/containermanager/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/northbound/containermanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/containermanager/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/containermanager/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/containermanager/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/controllermanager/enunciate.xml b/opendaylight/adsal/northbound/controllermanager/enunciate.xml similarity index 100% rename from opendaylight/northbound/controllermanager/enunciate.xml rename to opendaylight/adsal/northbound/controllermanager/enunciate.xml diff --git a/opendaylight/northbound/controllermanager/pom.xml b/opendaylight/adsal/northbound/controllermanager/pom.xml similarity index 98% rename from opendaylight/northbound/controllermanager/pom.xml rename to opendaylight/adsal/northbound/controllermanager/pom.xml index 33f9a06246..395dd2dc29 100644 --- a/opendaylight/northbound/controllermanager/pom.xml +++ b/opendaylight/adsal/northbound/controllermanager/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight controllermanager.northbound 0.1.0-SNAPSHOT diff --git a/opendaylight/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthbound.java b/opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthbound.java similarity index 100% rename from opendaylight/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthbound.java rename to opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthbound.java diff --git a/opendaylight/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerProperties.java b/opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerProperties.java similarity index 100% rename from opendaylight/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerProperties.java rename to opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerProperties.java diff --git a/opendaylight/northbound/controllermanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/controllermanager/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/controllermanager/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/controllermanager/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/controllermanager/src/test/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthboundTest.java b/opendaylight/adsal/northbound/controllermanager/src/test/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthboundTest.java similarity index 100% rename from opendaylight/northbound/controllermanager/src/test/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthboundTest.java rename to opendaylight/adsal/northbound/controllermanager/src/test/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthboundTest.java diff --git a/opendaylight/northbound/flowprogrammer/enunciate.xml b/opendaylight/adsal/northbound/flowprogrammer/enunciate.xml similarity index 100% rename from opendaylight/northbound/flowprogrammer/enunciate.xml rename to opendaylight/adsal/northbound/flowprogrammer/enunciate.xml diff --git a/opendaylight/northbound/flowprogrammer/pom.xml b/opendaylight/adsal/northbound/flowprogrammer/pom.xml similarity index 98% rename from opendaylight/northbound/flowprogrammer/pom.xml rename to opendaylight/adsal/northbound/flowprogrammer/pom.xml index 083a7a2cb8..fdc7340a35 100644 --- a/opendaylight/northbound/flowprogrammer/pom.xml +++ b/opendaylight/adsal/northbound/flowprogrammer/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight flowprogrammer.northbound diff --git a/opendaylight/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowConfigs.java b/opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowConfigs.java similarity index 100% rename from opendaylight/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowConfigs.java rename to opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowConfigs.java diff --git a/opendaylight/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java b/opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java similarity index 100% rename from opendaylight/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java rename to opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java diff --git a/opendaylight/northbound/flowprogrammer/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/northbound/flowprogrammer/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/northbound/flowprogrammer/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/northbound/flowprogrammer/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/northbound/flowprogrammer/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/northbound/flowprogrammer/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/northbound/flowprogrammer/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/northbound/flowprogrammer/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/northbound/flowprogrammer/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/flowprogrammer/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/flowprogrammer/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/flowprogrammer/src/test/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthboundTest.java b/opendaylight/adsal/northbound/flowprogrammer/src/test/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthboundTest.java similarity index 100% rename from opendaylight/northbound/flowprogrammer/src/test/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthboundTest.java rename to opendaylight/adsal/northbound/flowprogrammer/src/test/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthboundTest.java diff --git a/opendaylight/northbound/hosttracker/enunciate.xml b/opendaylight/adsal/northbound/hosttracker/enunciate.xml similarity index 100% rename from opendaylight/northbound/hosttracker/enunciate.xml rename to opendaylight/adsal/northbound/hosttracker/enunciate.xml diff --git a/opendaylight/northbound/hosttracker/pom.xml b/opendaylight/adsal/northbound/hosttracker/pom.xml similarity index 98% rename from opendaylight/northbound/hosttracker/pom.xml rename to opendaylight/adsal/northbound/hosttracker/pom.xml index 3cd3f36be0..778125af28 100644 --- a/opendaylight/northbound/hosttracker/pom.xml +++ b/opendaylight/adsal/northbound/hosttracker/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight hosttracker.northbound 0.5.0-SNAPSHOT diff --git a/opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostConfig.java b/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostConfig.java similarity index 100% rename from opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostConfig.java rename to opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostConfig.java diff --git a/opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java b/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java similarity index 100% rename from opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java rename to opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java diff --git a/opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/Hosts.java b/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/Hosts.java similarity index 100% rename from opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/Hosts.java rename to opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/Hosts.java diff --git a/opendaylight/northbound/hosttracker/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/northbound/hosttracker/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/northbound/hosttracker/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/northbound/hosttracker/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/northbound/hosttracker/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/northbound/hosttracker/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/northbound/hosttracker/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/northbound/hosttracker/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/northbound/hosttracker/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/hosttracker/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/hosttracker/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/hosttracker/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/hosttracker/src/test/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthboundTest.java b/opendaylight/adsal/northbound/hosttracker/src/test/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthboundTest.java similarity index 100% rename from opendaylight/northbound/hosttracker/src/test/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthboundTest.java rename to opendaylight/adsal/northbound/hosttracker/src/test/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthboundTest.java diff --git a/opendaylight/northbound/httpservice-bridge/pom.xml b/opendaylight/adsal/northbound/httpservice-bridge/pom.xml similarity index 95% rename from opendaylight/northbound/httpservice-bridge/pom.xml rename to opendaylight/adsal/northbound/httpservice-bridge/pom.xml index deeabd9d00..12ee95c983 100644 --- a/opendaylight/northbound/httpservice-bridge/pom.xml +++ b/opendaylight/adsal/northbound/httpservice-bridge/pom.xml @@ -6,7 +6,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight httpservice-bridge diff --git a/opendaylight/northbound/httpservice-bridge/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/httpservice-bridge/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/httpservice-bridge/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/httpservice-bridge/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/integrationtest/pom.xml b/opendaylight/adsal/northbound/integrationtest/pom.xml similarity index 100% rename from opendaylight/northbound/integrationtest/pom.xml rename to opendaylight/adsal/northbound/integrationtest/pom.xml diff --git a/opendaylight/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java b/opendaylight/adsal/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java similarity index 100% rename from opendaylight/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java rename to opendaylight/adsal/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java diff --git a/opendaylight/northbound/integrationtest/src/test/resources/exam.properties b/opendaylight/adsal/northbound/integrationtest/src/test/resources/exam.properties similarity index 100% rename from opendaylight/northbound/integrationtest/src/test/resources/exam.properties rename to opendaylight/adsal/northbound/integrationtest/src/test/resources/exam.properties diff --git a/opendaylight/northbound/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/northbound/integrationtest/src/test/resources/logback.xml similarity index 100% rename from opendaylight/northbound/integrationtest/src/test/resources/logback.xml rename to opendaylight/adsal/northbound/integrationtest/src/test/resources/logback.xml diff --git a/opendaylight/northbound/integrationtest/src/test/resources/tomcat-server.xml b/opendaylight/adsal/northbound/integrationtest/src/test/resources/tomcat-server.xml similarity index 100% rename from opendaylight/northbound/integrationtest/src/test/resources/tomcat-server.xml rename to opendaylight/adsal/northbound/integrationtest/src/test/resources/tomcat-server.xml diff --git a/opendaylight/northbound/java-client/enunciate.xml b/opendaylight/adsal/northbound/java-client/enunciate.xml similarity index 100% rename from opendaylight/northbound/java-client/enunciate.xml rename to opendaylight/adsal/northbound/java-client/enunciate.xml diff --git a/opendaylight/northbound/java-client/pom.xml b/opendaylight/adsal/northbound/java-client/pom.xml similarity index 99% rename from opendaylight/northbound/java-client/pom.xml rename to opendaylight/adsal/northbound/java-client/pom.xml index a4bcde461e..5a4c18e88c 100644 --- a/opendaylight/northbound/java-client/pom.xml +++ b/opendaylight/adsal/northbound/java-client/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight northbound.client diff --git a/opendaylight/northbound/jolokia/pom.xml b/opendaylight/adsal/northbound/jolokia/pom.xml similarity index 95% rename from opendaylight/northbound/jolokia/pom.xml rename to opendaylight/adsal/northbound/jolokia/pom.xml index 07e3a7d36b..b078e486a8 100644 --- a/opendaylight/northbound/jolokia/pom.xml +++ b/opendaylight/adsal/northbound/jolokia/pom.xml @@ -6,7 +6,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight jolokia-bridge diff --git a/opendaylight/northbound/jolokia/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/jolokia/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/jolokia/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/jolokia/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/networkconfiguration/bridgedomain/enunciate.xml b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/enunciate.xml similarity index 100% rename from opendaylight/northbound/networkconfiguration/bridgedomain/enunciate.xml rename to opendaylight/adsal/northbound/networkconfiguration/bridgedomain/enunciate.xml diff --git a/opendaylight/northbound/networkconfiguration/bridgedomain/pom.xml b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/pom.xml similarity index 98% rename from opendaylight/northbound/networkconfiguration/bridgedomain/pom.xml rename to opendaylight/adsal/northbound/networkconfiguration/bridgedomain/pom.xml index 8b552ba25a..f78ff96608 100644 --- a/opendaylight/northbound/networkconfiguration/bridgedomain/pom.xml +++ b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../commons/opendaylight + ../../../../commons/opendaylight networkconfig.bridgedomain.northbound diff --git a/opendaylight/northbound/networkconfiguration/bridgedomain/src/main/java/org/opendaylight/controller/networkconfig/bridgedomain/northbound/BridgeDomainNorthbound.java b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/java/org/opendaylight/controller/networkconfig/bridgedomain/northbound/BridgeDomainNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/bridgedomain/src/main/java/org/opendaylight/controller/networkconfig/bridgedomain/northbound/BridgeDomainNorthbound.java rename to opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/java/org/opendaylight/controller/networkconfig/bridgedomain/northbound/BridgeDomainNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/bridgedomain/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/networkconfiguration/bridgedomain/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/staticrouting/enunciate.xml b/opendaylight/adsal/northbound/staticrouting/enunciate.xml similarity index 100% rename from opendaylight/northbound/staticrouting/enunciate.xml rename to opendaylight/adsal/northbound/staticrouting/enunciate.xml diff --git a/opendaylight/northbound/staticrouting/pom.xml b/opendaylight/adsal/northbound/staticrouting/pom.xml similarity index 98% rename from opendaylight/northbound/staticrouting/pom.xml rename to opendaylight/adsal/northbound/staticrouting/pom.xml index 761f1f08e9..3a89369b18 100644 --- a/opendaylight/northbound/staticrouting/pom.xml +++ b/opendaylight/adsal/northbound/staticrouting/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight forwarding.staticrouting.northbound diff --git a/opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoute.java b/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoute.java similarity index 100% rename from opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoute.java rename to opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoute.java diff --git a/opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutes.java b/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutes.java similarity index 100% rename from opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutes.java rename to opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutes.java diff --git a/opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java b/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java similarity index 100% rename from opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java rename to opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java diff --git a/opendaylight/northbound/staticrouting/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/northbound/staticrouting/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/northbound/staticrouting/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/northbound/staticrouting/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/northbound/staticrouting/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/northbound/staticrouting/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/northbound/staticrouting/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/northbound/staticrouting/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/northbound/staticrouting/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/staticrouting/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/staticrouting/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/staticrouting/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthboundTest.java b/opendaylight/adsal/northbound/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthboundTest.java similarity index 100% rename from opendaylight/northbound/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthboundTest.java rename to opendaylight/adsal/northbound/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthboundTest.java diff --git a/opendaylight/northbound/statistics/enunciate.xml b/opendaylight/adsal/northbound/statistics/enunciate.xml similarity index 100% rename from opendaylight/northbound/statistics/enunciate.xml rename to opendaylight/adsal/northbound/statistics/enunciate.xml diff --git a/opendaylight/northbound/statistics/pom.xml b/opendaylight/adsal/northbound/statistics/pom.xml similarity index 98% rename from opendaylight/northbound/statistics/pom.xml rename to opendaylight/adsal/northbound/statistics/pom.xml index 4ae3d8746c..0d42ffbb80 100644 --- a/opendaylight/northbound/statistics/pom.xml +++ b/opendaylight/adsal/northbound/statistics/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight statistics.northbound diff --git a/opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllFlowStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllFlowStatistics.java similarity index 100% rename from opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllFlowStatistics.java rename to opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllFlowStatistics.java diff --git a/opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllPortStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllPortStatistics.java similarity index 100% rename from opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllPortStatistics.java rename to opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllPortStatistics.java diff --git a/opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllTableStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllTableStatistics.java similarity index 100% rename from opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllTableStatistics.java rename to opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllTableStatistics.java diff --git a/opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/FlowStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/FlowStatistics.java similarity index 100% rename from opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/FlowStatistics.java rename to opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/FlowStatistics.java diff --git a/opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/PortStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/PortStatistics.java similarity index 100% rename from opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/PortStatistics.java rename to opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/PortStatistics.java diff --git a/opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java similarity index 100% rename from opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java rename to opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java diff --git a/opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/TableStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/TableStatistics.java similarity index 100% rename from opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/TableStatistics.java rename to opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/TableStatistics.java diff --git a/opendaylight/northbound/statistics/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/northbound/statistics/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/northbound/statistics/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/northbound/statistics/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/northbound/statistics/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/northbound/statistics/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/northbound/statistics/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/northbound/statistics/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/northbound/statistics/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/statistics/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/statistics/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/statistics/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/statistics/src/test/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthboundTest.java b/opendaylight/adsal/northbound/statistics/src/test/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthboundTest.java similarity index 100% rename from opendaylight/northbound/statistics/src/test/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthboundTest.java rename to opendaylight/adsal/northbound/statistics/src/test/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthboundTest.java diff --git a/opendaylight/northbound/subnets/enunciate.xml b/opendaylight/adsal/northbound/subnets/enunciate.xml similarity index 100% rename from opendaylight/northbound/subnets/enunciate.xml rename to opendaylight/adsal/northbound/subnets/enunciate.xml diff --git a/opendaylight/northbound/subnets/pom.xml b/opendaylight/adsal/northbound/subnets/pom.xml similarity index 98% rename from opendaylight/northbound/subnets/pom.xml rename to opendaylight/adsal/northbound/subnets/pom.xml index 1efb974b51..1eaa45dddd 100644 --- a/opendaylight/northbound/subnets/pom.xml +++ b/opendaylight/adsal/northbound/subnets/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight subnets.northbound diff --git a/opendaylight/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetConfigs.java b/opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetConfigs.java similarity index 100% rename from opendaylight/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetConfigs.java rename to opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetConfigs.java diff --git a/opendaylight/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java b/opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java similarity index 100% rename from opendaylight/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java rename to opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java diff --git a/opendaylight/northbound/subnets/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/northbound/subnets/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/northbound/subnets/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/northbound/subnets/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/northbound/subnets/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/northbound/subnets/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/northbound/subnets/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/northbound/subnets/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/northbound/subnets/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/subnets/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/subnets/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/subnets/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/subnets/src/test/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthboundTest.java b/opendaylight/adsal/northbound/subnets/src/test/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthboundTest.java similarity index 100% rename from opendaylight/northbound/subnets/src/test/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthboundTest.java rename to opendaylight/adsal/northbound/subnets/src/test/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthboundTest.java diff --git a/opendaylight/northbound/swagger-ui/pom.xml b/opendaylight/adsal/northbound/swagger-ui/pom.xml similarity index 96% rename from opendaylight/northbound/swagger-ui/pom.xml rename to opendaylight/adsal/northbound/swagger-ui/pom.xml index bbb80a7811..ba1e5c0bc4 100644 --- a/opendaylight/northbound/swagger-ui/pom.xml +++ b/opendaylight/adsal/northbound/swagger-ui/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight swagger-ui @@ -71,6 +71,10 @@ org.opendaylight.controller usermanager.northbound + + org.opendaylight.controller + networkconfig.neutron.northbound + org.slf4j slf4j-api @@ -157,6 +161,7 @@ + diff --git a/opendaylight/northbound/swagger-ui/src/main/java/org/opendaylight/controller/swaggerui/BasePathModifierServlet.java b/opendaylight/adsal/northbound/swagger-ui/src/main/java/org/opendaylight/controller/swaggerui/BasePathModifierServlet.java similarity index 100% rename from opendaylight/northbound/swagger-ui/src/main/java/org/opendaylight/controller/swaggerui/BasePathModifierServlet.java rename to opendaylight/adsal/northbound/swagger-ui/src/main/java/org/opendaylight/controller/swaggerui/BasePathModifierServlet.java diff --git a/opendaylight/northbound/swagger-ui/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/swagger-ui/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/swagger-ui/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/swagger-ui/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/swagger-ui/src/main/resources/css/custom.css b/opendaylight/adsal/northbound/swagger-ui/src/main/resources/css/custom.css similarity index 100% rename from opendaylight/northbound/swagger-ui/src/main/resources/css/custom.css rename to opendaylight/adsal/northbound/swagger-ui/src/main/resources/css/custom.css diff --git a/opendaylight/northbound/swagger-ui/src/main/resources/images/logo.png b/opendaylight/adsal/northbound/swagger-ui/src/main/resources/images/logo.png similarity index 100% rename from opendaylight/northbound/swagger-ui/src/main/resources/images/logo.png rename to opendaylight/adsal/northbound/swagger-ui/src/main/resources/images/logo.png diff --git a/opendaylight/northbound/swagger-ui/src/main/resources/index.html b/opendaylight/adsal/northbound/swagger-ui/src/main/resources/index.html similarity index 100% rename from opendaylight/northbound/swagger-ui/src/main/resources/index.html rename to opendaylight/adsal/northbound/swagger-ui/src/main/resources/index.html diff --git a/opendaylight/northbound/switchmanager/enunciate.xml b/opendaylight/adsal/northbound/switchmanager/enunciate.xml similarity index 100% rename from opendaylight/northbound/switchmanager/enunciate.xml rename to opendaylight/adsal/northbound/switchmanager/enunciate.xml diff --git a/opendaylight/northbound/switchmanager/pom.xml b/opendaylight/adsal/northbound/switchmanager/pom.xml similarity index 98% rename from opendaylight/northbound/switchmanager/pom.xml rename to opendaylight/adsal/northbound/switchmanager/pom.xml index 1b876f4420..b7aaae58d0 100644 --- a/opendaylight/northbound/switchmanager/pom.xml +++ b/opendaylight/adsal/northbound/switchmanager/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight switchmanager.northbound 0.5.0-SNAPSHOT diff --git a/opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectorProperties.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectorProperties.java similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectorProperties.java rename to opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectorProperties.java diff --git a/opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectors.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectors.java similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectors.java rename to opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectors.java diff --git a/opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeProperties.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeProperties.java similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeProperties.java rename to opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeProperties.java diff --git a/opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/Nodes.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/Nodes.java similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/Nodes.java rename to opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/Nodes.java diff --git a/opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java rename to opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java diff --git a/opendaylight/northbound/switchmanager/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/northbound/switchmanager/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/northbound/switchmanager/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/northbound/switchmanager/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/northbound/switchmanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/switchmanager/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/switchmanager/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/switchmanager/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/switchmanager/src/test/java/org/opendaylight/controller/switchmanager/northbound/SwitchManagerNorthboundTest.java b/opendaylight/adsal/northbound/switchmanager/src/test/java/org/opendaylight/controller/switchmanager/northbound/SwitchManagerNorthboundTest.java similarity index 100% rename from opendaylight/northbound/switchmanager/src/test/java/org/opendaylight/controller/switchmanager/northbound/SwitchManagerNorthboundTest.java rename to opendaylight/adsal/northbound/switchmanager/src/test/java/org/opendaylight/controller/switchmanager/northbound/SwitchManagerNorthboundTest.java diff --git a/opendaylight/northbound/topology/enunciate.xml b/opendaylight/adsal/northbound/topology/enunciate.xml similarity index 100% rename from opendaylight/northbound/topology/enunciate.xml rename to opendaylight/adsal/northbound/topology/enunciate.xml diff --git a/opendaylight/northbound/topology/pom.xml b/opendaylight/adsal/northbound/topology/pom.xml similarity index 98% rename from opendaylight/northbound/topology/pom.xml rename to opendaylight/adsal/northbound/topology/pom.xml index 270148420c..60a12700aa 100644 --- a/opendaylight/northbound/topology/pom.xml +++ b/opendaylight/adsal/northbound/topology/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight topology.northbound diff --git a/opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/EdgeProperties.java b/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/EdgeProperties.java similarity index 100% rename from opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/EdgeProperties.java rename to opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/EdgeProperties.java diff --git a/opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/Topology.java b/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/Topology.java similarity index 100% rename from opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/Topology.java rename to opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/Topology.java diff --git a/opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java b/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java similarity index 100% rename from opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java rename to opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java diff --git a/opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyUserLinks.java b/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyUserLinks.java similarity index 100% rename from opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyUserLinks.java rename to opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyUserLinks.java diff --git a/opendaylight/northbound/topology/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/northbound/topology/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/northbound/topology/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/northbound/topology/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/northbound/topology/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/northbound/topology/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/northbound/topology/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/northbound/topology/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/northbound/topology/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/topology/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/topology/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/topology/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java b/opendaylight/adsal/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java similarity index 98% rename from opendaylight/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java rename to opendaylight/adsal/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java index 298f32877a..bcfa2a9ee9 100644 --- a/opendaylight/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java +++ b/opendaylight/adsal/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java @@ -7,8 +7,6 @@ */ package org.opendaylight.controller.topology.northbound; - - import org.junit.Test; import org.opendaylight.controller.sal.core.Bandwidth; import org.opendaylight.controller.sal.core.ConstructionException; @@ -28,7 +26,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import static junit.framework.Assert.assertEquals; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class TopologyTest { diff --git a/opendaylight/northbound/usermanager/enunciate.xml b/opendaylight/adsal/northbound/usermanager/enunciate.xml similarity index 100% rename from opendaylight/northbound/usermanager/enunciate.xml rename to opendaylight/adsal/northbound/usermanager/enunciate.xml diff --git a/opendaylight/northbound/usermanager/pom.xml b/opendaylight/adsal/northbound/usermanager/pom.xml similarity index 98% rename from opendaylight/northbound/usermanager/pom.xml rename to opendaylight/adsal/northbound/usermanager/pom.xml index fe32bcf5d3..e51ef2faa9 100644 --- a/opendaylight/northbound/usermanager/pom.xml +++ b/opendaylight/adsal/northbound/usermanager/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight usermanager.northbound diff --git a/opendaylight/northbound/usermanager/src/main/java/org/opendaylight/controller/usermanager/northbound/UserManagerNorthbound.java b/opendaylight/adsal/northbound/usermanager/src/main/java/org/opendaylight/controller/usermanager/northbound/UserManagerNorthbound.java similarity index 100% rename from opendaylight/northbound/usermanager/src/main/java/org/opendaylight/controller/usermanager/northbound/UserManagerNorthbound.java rename to opendaylight/adsal/northbound/usermanager/src/main/java/org/opendaylight/controller/usermanager/northbound/UserManagerNorthbound.java diff --git a/opendaylight/northbound/usermanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/usermanager/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/usermanager/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/northbound/usermanager/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/usermanager/src/test/java/org/opendaylight/controller/subnets/northbound/UserManagerNorthboundTest.java b/opendaylight/adsal/northbound/usermanager/src/test/java/org/opendaylight/controller/subnets/northbound/UserManagerNorthboundTest.java similarity index 100% rename from opendaylight/northbound/usermanager/src/test/java/org/opendaylight/controller/subnets/northbound/UserManagerNorthboundTest.java rename to opendaylight/adsal/northbound/usermanager/src/test/java/org/opendaylight/controller/subnets/northbound/UserManagerNorthboundTest.java diff --git a/opendaylight/northboundtest/unit_test_suite/pom.xml b/opendaylight/adsal/northboundtest/unit_test_suite/pom.xml similarity index 97% rename from opendaylight/northboundtest/unit_test_suite/pom.xml rename to opendaylight/adsal/northboundtest/unit_test_suite/pom.xml index 11c885db30..9f33a4db5d 100644 --- a/opendaylight/northboundtest/unit_test_suite/pom.xml +++ b/opendaylight/adsal/northboundtest/unit_test_suite/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../opendaylight/commons/opendaylight + ../../../../opendaylight/commons/opendaylight scm:git:ssh://git.opendaylight.org:29418/controller.git diff --git a/opendaylight/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/API3UnitTest.java b/opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/API3UnitTest.java similarity index 100% rename from opendaylight/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/API3UnitTest.java rename to opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/API3UnitTest.java diff --git a/opendaylight/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/Activator.java b/opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/Activator.java similarity index 100% rename from opendaylight/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/Activator.java rename to opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/Activator.java diff --git a/opendaylight/adsal/pom.xml b/opendaylight/adsal/pom.xml new file mode 100644 index 0000000000..23db4d56a6 --- /dev/null +++ b/opendaylight/adsal/pom.xml @@ -0,0 +1,140 @@ + + + 4.0.0 + + + org.opendaylight.controller + commons.parent + 1.1.0-SNAPSHOT + ../commons/parent + + + adsal-parent + pom + + forwarding/staticrouting + clustering/services + clustering/services_implementation + clustering/stub + clustering/test + configuration/api + configuration/implementation + routing/dijkstra_implementation + arphandler + forwardingrulesmanager/api + forwardingrulesmanager/implementation + hosttracker/api + hosttracker/implementation + hosttracker/shell + hosttracker_new/api + hosttracker_new/implementation + containermanager/api + containermanager/implementation + containermanager/shell + appauth + switchmanager/api + switchmanager/implementation + statisticsmanager/api + statisticsmanager/implementation + topologymanager/implementation + topologymanager/shell + usermanager/api + usermanager/implementation + connectionmanager/api + connectionmanager/implementation + security + karaf-tomcat-security + + + sal/api + sal/implementation + + + sal/connection/api + sal/connection/implementation + sal/networkconfiguration/api + sal/networkconfiguration/implementation + + + web/root + web/flows + web/devices + web/troubleshoot + web/topology + web/osgi-brandfragment + + + northbound/commons + northbound/bundlescanner/api + northbound/bundlescanner/implementation + northbound/topology + northbound/staticrouting + northbound/statistics + northbound/flowprogrammer + northbound/hosttracker + northbound/subnets + northbound/switchmanager + northbound/containermanager + northbound/networkconfiguration/bridgedomain + northbound/httpservice-bridge + northbound/jolokia + northbound/connectionmanager + northbound/usermanager + northbound/controllermanager + + + logging/bridge + + + protocol_plugins/openflow + protocol_plugins/stub + + + samples/simpleforwarding + samples/loadbalancer + samples/northbound/loadbalancer + + dummy-console + + + features/base + features/controller + features/adsal + features/nsf + features/extras + features/adsal-compatibility + + + + integrationtests + + false + + + clustering/integrationtest + configuration/integrationtest + forwardingrulesmanager/integrationtest + hosttracker/integrationtest + switchmanager/integrationtest + topologymanager/integrationtest + + northbound/integrationtest + statisticsmanager/integrationtest + containermanager/it.implementation + commons/integrationtest + + commons/httpclient + + + + docs + + false + + + northbound/java-client + northbound/swagger-ui + + + + diff --git a/opendaylight/protocol_plugins/openflow/pom.xml b/opendaylight/adsal/protocol_plugins/openflow/pom.xml similarity index 98% rename from opendaylight/protocol_plugins/openflow/pom.xml rename to opendaylight/adsal/protocol_plugins/openflow/pom.xml index 16fadee1cc..7cb7602d4f 100644 --- a/opendaylight/protocol_plugins/openflow/pom.xml +++ b/opendaylight/adsal/protocol_plugins/openflow/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight protocol_plugins.openflow diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketListen.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketListen.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketListen.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketListen.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketMux.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketMux.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketMux.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketMux.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDiscoveryListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDiscoveryListener.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDiscoveryListener.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDiscoveryListener.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IFlowProgrammerNotifier.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IFlowProgrammerNotifier.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IFlowProgrammerNotifier.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IFlowProgrammerNotifier.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryProvider.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryProvider.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryProvider.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryProvider.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimExternalListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimExternalListener.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimExternalListener.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimExternalListener.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimInternalListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimInternalListener.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimInternalListener.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimInternalListener.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsListener.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsListener.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsListener.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsManager.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsManager.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsManager.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsManager.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadFilterInternalListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadFilterInternalListener.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadFilterInternalListener.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadFilterInternalListener.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadServiceFilter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadServiceFilter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadServiceFilter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadServiceFilter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IRefreshInternalProvider.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IRefreshInternalProvider.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IRefreshInternalProvider.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IRefreshInternalProvider.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/ITopologyServiceShimListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/ITopologyServiceShimListener.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/ITopologyServiceShimListener.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/ITopologyServiceShimListener.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IController.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IController.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IController.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IController.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageListener.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageListener.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageListener.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageReadWrite.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageReadWrite.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageReadWrite.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageReadWrite.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitchStateListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitchStateListener.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitchStateListener.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitchStateListener.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/ControllerIO.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/ControllerIO.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/ControllerIO.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/ControllerIO.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/MessageReadWriteService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/MessageReadWriteService.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/MessageReadWriteService.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/MessageReadWriteService.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/PriorityMessage.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/PriorityMessage.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/PriorityMessage.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/PriorityMessage.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SecureMessageReadWriteService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SecureMessageReadWriteService.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SecureMessageReadWriteService.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SecureMessageReadWriteService.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/StatisticsCollector.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/StatisticsCollector.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/StatisticsCollector.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/StatisticsCollector.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchEvent.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchEvent.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchEvent.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchEvent.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchHandler.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchHandler.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchHandler.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchHandler.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SynchronousMessage.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SynchronousMessage.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SynchronousMessage.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SynchronousMessage.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Activator.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Activator.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Activator.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Activator.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketServices.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketServices.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketServices.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketServices.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DescStatisticsConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DescStatisticsConverter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DescStatisticsConverter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DescStatisticsConverter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowConverter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowConverter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowConverter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerNotifier.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerNotifier.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerNotifier.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerNotifier.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerService.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerService.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerService.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowStatisticsConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowStatisticsConverter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowStatisticsConverter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowStatisticsConverter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryService.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryService.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryService.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceHelper.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceHelper.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceHelper.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceHelper.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/OFStatisticsManager.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/OFStatisticsManager.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/OFStatisticsManager.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/OFStatisticsManager.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortConverter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortConverter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortConverter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortStatisticsConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortStatisticsConverter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortStatisticsConverter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortStatisticsConverter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadService.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadService.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadService.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadServiceFilter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadServiceFilter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadServiceFilter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadServiceFilter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableConverter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableConverter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableConverter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableStatisticsConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableStatisticsConverter.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableStatisticsConverter.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableStatisticsConverter.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServiceShim.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServiceShim.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServiceShim.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServiceShim.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServices.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServices.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServices.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServices.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Utils.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Utils.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Utils.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Utils.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Error.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Error.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Error.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Error.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6FlowMod.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6FlowMod.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6FlowMod.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6FlowMod.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Match.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Match.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Match.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Match.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsReply.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsReply.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsReply.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsReply.java diff --git a/opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsRequest.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsRequest.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsRequest.java rename to opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsRequest.java diff --git a/opendaylight/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerServiceTest.java b/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerServiceTest.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerServiceTest.java rename to opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerServiceTest.java diff --git a/opendaylight/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6ExtensionTest.java b/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6ExtensionTest.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6ExtensionTest.java rename to opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6ExtensionTest.java diff --git a/opendaylight/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6MatchTest.java b/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6MatchTest.java similarity index 100% rename from opendaylight/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6MatchTest.java rename to opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6MatchTest.java diff --git a/opendaylight/protocol_plugins/stub/pom.xml b/opendaylight/adsal/protocol_plugins/stub/pom.xml similarity index 97% rename from opendaylight/protocol_plugins/stub/pom.xml rename to opendaylight/adsal/protocol_plugins/stub/pom.xml index 4c7b8965fb..1fb84a51ed 100644 --- a/opendaylight/protocol_plugins/stub/pom.xml +++ b/opendaylight/adsal/protocol_plugins/stub/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight protocol_plugins.stub diff --git a/opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/Activator.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/Activator.java similarity index 100% rename from opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/Activator.java rename to opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/Activator.java diff --git a/opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/FlowProgrammerService.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/FlowProgrammerService.java similarity index 100% rename from opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/FlowProgrammerService.java rename to opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/FlowProgrammerService.java diff --git a/opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java similarity index 100% rename from opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java rename to opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java diff --git a/opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/ReadService.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/ReadService.java similarity index 100% rename from opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/ReadService.java rename to opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/ReadService.java diff --git a/opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeConnectorFactory.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeConnectorFactory.java similarity index 100% rename from opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeConnectorFactory.java rename to opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeConnectorFactory.java diff --git a/opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeFactory.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeFactory.java similarity index 100% rename from opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeFactory.java rename to opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeFactory.java diff --git a/opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/TopologyServices.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/TopologyServices.java similarity index 100% rename from opendaylight/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/TopologyServices.java rename to opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/TopologyServices.java diff --git a/opendaylight/routing/dijkstra_implementation/pom.xml b/opendaylight/adsal/routing/dijkstra_implementation/pom.xml similarity index 98% rename from opendaylight/routing/dijkstra_implementation/pom.xml rename to opendaylight/adsal/routing/dijkstra_implementation/pom.xml index b1b68b8cb7..7f429ff967 100644 --- a/opendaylight/routing/dijkstra_implementation/pom.xml +++ b/opendaylight/adsal/routing/dijkstra_implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight routing.dijkstra_implementation diff --git a/opendaylight/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/Activator.java b/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/Activator.java similarity index 100% rename from opendaylight/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/Activator.java rename to opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/Activator.java diff --git a/opendaylight/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementation.java b/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementation.java similarity index 100% rename from opendaylight/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementation.java rename to opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementation.java diff --git a/opendaylight/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementationCLI.java b/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementationCLI.java similarity index 100% rename from opendaylight/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementationCLI.java rename to opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementationCLI.java diff --git a/opendaylight/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/DijkstraTest.java b/opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/DijkstraTest.java similarity index 100% rename from opendaylight/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/DijkstraTest.java rename to opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/DijkstraTest.java diff --git a/opendaylight/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/MaxThruputTest.java b/opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/MaxThruputTest.java similarity index 100% rename from opendaylight/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/MaxThruputTest.java rename to opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/MaxThruputTest.java diff --git a/opendaylight/sal/api/pom.xml b/opendaylight/adsal/sal/api/pom.xml similarity index 97% rename from opendaylight/sal/api/pom.xml rename to opendaylight/adsal/sal/api/pom.xml index 50ac61fccb..d5d6256bc9 100644 --- a/opendaylight/sal/api/pom.xml +++ b/opendaylight/adsal/sal/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight sal diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Action.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Action.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Action.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Action.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/ActionType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/ActionType.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/ActionType.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/ActionType.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Controller.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Controller.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Controller.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Controller.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Drop.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Drop.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Drop.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Drop.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Enqueue.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Enqueue.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Enqueue.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Enqueue.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Flood.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Flood.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Flood.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Flood.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/FloodAll.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/FloodAll.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/FloodAll.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/FloodAll.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/HwPath.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/HwPath.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/HwPath.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/HwPath.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Loopback.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Loopback.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Loopback.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Loopback.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Output.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Output.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/Output.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Output.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/PopVlan.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PopVlan.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/PopVlan.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PopVlan.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/PushVlan.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PushVlan.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/PushVlan.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PushVlan.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlDst.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlDst.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlDst.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlSrc.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlSrc.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlSrc.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlType.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlType.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlType.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNextHop.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNextHop.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNextHop.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNextHop.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwDst.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwDst.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwDst.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwTos.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwTos.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwTos.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwTos.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpDst.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpDst.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpDst.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpSrc.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpSrc.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpSrc.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanCfi.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanCfi.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanCfi.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanCfi.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanId.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanId.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanId.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanId.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanPcp.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanPcp.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanPcp.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanPcp.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SupportedFlowActions.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SupportedFlowActions.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SupportedFlowActions.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SupportedFlowActions.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SwPath.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SwPath.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SwPath.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SwPath.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRole.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRole.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRole.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRole.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRoleLevel.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRoleLevel.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRoleLevel.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRoleLevel.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AuthResultEnum.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AuthResultEnum.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AuthResultEnum.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AuthResultEnum.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/IResourceAuthorization.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/IResourceAuthorization.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/IResourceAuthorization.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/IResourceAuthorization.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Privilege.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Privilege.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Privilege.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Privilege.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Resource.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Resource.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Resource.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Resource.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/ResourceGroup.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/ResourceGroup.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/ResourceGroup.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/ResourceGroup.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/UserLevel.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/UserLevel.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/UserLevel.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/UserLevel.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Actions.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Actions.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Actions.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Actions.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/AdvertisedBandwidth.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/AdvertisedBandwidth.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/AdvertisedBandwidth.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/AdvertisedBandwidth.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Bandwidth.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Bandwidth.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Bandwidth.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Bandwidth.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Buffers.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Buffers.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Buffers.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Buffers.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Capabilities.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Capabilities.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Capabilities.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Capabilities.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ComponentActivatorAbstractBase.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ComponentActivatorAbstractBase.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ComponentActivatorAbstractBase.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ComponentActivatorAbstractBase.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Config.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Config.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Config.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Config.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ConstructionException.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ConstructionException.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ConstructionException.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ConstructionException.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerFlow.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerFlow.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerFlow.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerFlow.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerServiceDependency.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerServiceDependency.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerServiceDependency.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerServiceDependency.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Description.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Description.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Description.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Description.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Edge.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Edge.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Edge.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Edge.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ForwardingMode.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ForwardingMode.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/ForwardingMode.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ForwardingMode.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Host.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Host.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Host.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Host.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainer.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainer.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainer.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainer.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerAware.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerAware.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerAware.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerAware.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerListener.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerListener.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerListener.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerLocalListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerLocalListener.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerLocalListener.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerLocalListener.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Latency.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Latency.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Latency.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Latency.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/MacAddress.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/MacAddress.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/MacAddress.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/MacAddress.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Name.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Name.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Name.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Name.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Node.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Node.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Node.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Node.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeConnector.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeConnector.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeConnector.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeConnector.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeTable.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeTable.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeTable.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeTable.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Path.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Path.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Path.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Path.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/PeerBandwidth.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/PeerBandwidth.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/PeerBandwidth.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/PeerBandwidth.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Property.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Property.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Property.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Property.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/State.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/State.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/State.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/State.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/SupportedBandwidth.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/SupportedBandwidth.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/SupportedBandwidth.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/SupportedBandwidth.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tables.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tables.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tables.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tables.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tier.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tier.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tier.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tier.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/TimeStamp.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/TimeStamp.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/TimeStamp.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/TimeStamp.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/UpdateType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/UpdateType.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/core/UpdateType.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/UpdateType.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/discovery/IDiscoveryService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/discovery/IDiscoveryService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/discovery/IDiscoveryService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/discovery/IDiscoveryService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/Flow.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/Flow.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/Flow.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/Flow.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerListener.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerListener.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerListener.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginInFlowProgrammerService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginInFlowProgrammerService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginInFlowProgrammerService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginInFlowProgrammerService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginOutFlowProgrammerService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginOutFlowProgrammerService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginOutFlowProgrammerService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginOutFlowProgrammerService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IInventoryService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IInventoryService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IInventoryService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IInventoryService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IListenInventoryUpdates.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IListenInventoryUpdates.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IListenInventoryUpdates.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IListenInventoryUpdates.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginInInventoryService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginInInventoryService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginInInventoryService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginInInventoryService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginOutInventoryService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginOutInventoryService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginOutInventoryService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginOutInventoryService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchField.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchField.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchField.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchField.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchType.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchType.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchType.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BufferException.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BufferException.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BufferException.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BufferException.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ICMP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ICMP.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ICMP.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ICMP.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IDataPacketService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IDataPacketService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IDataPacketService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IDataPacketService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IListenDataPacket.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IListenDataPacket.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IListenDataPacket.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IListenDataPacket.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginInDataPacketService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginInDataPacketService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginInDataPacketService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginInDataPacketService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginOutDataPacketService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginOutDataPacketService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginOutDataPacketService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginOutDataPacketService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LinkEncap.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LinkEncap.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LinkEncap.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LinkEncap.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketException.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketException.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketException.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketException.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketResult.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketResult.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketResult.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketResult.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/RawPacket.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/RawPacket.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/RawPacket.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/RawPacket.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/DataLinkAddress.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/DataLinkAddress.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/DataLinkAddress.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/DataLinkAddress.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/EthernetAddress.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/EthernetAddress.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/EthernetAddress.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/EthernetAddress.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/FlowOnNode.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/FlowOnNode.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/FlowOnNode.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/FlowOnNode.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginInReadService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginInReadService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginInReadService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginInReadService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginOutReadService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginOutReadService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginOutReadService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginOutReadService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadServiceListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadServiceListener.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadServiceListener.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadServiceListener.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeConnectorStatistics.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeConnectorStatistics.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeConnectorStatistics.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeConnectorStatistics.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeDescription.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeDescription.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeDescription.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeDescription.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeTableStatistics.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeTableStatistics.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeTableStatistics.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeTableStatistics.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IListenRoutingUpdates.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IListenRoutingUpdates.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IListenRoutingUpdates.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IListenRoutingUpdates.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IRouting.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IRouting.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IRouting.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IRouting.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IListenTopoUpdates.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IListenTopoUpdates.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IListenTopoUpdates.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IListenTopoUpdates.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginInTopologyService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginInTopologyService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginInTopologyService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginInTopologyService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/ITopologyService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/ITopologyService.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/ITopologyService.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/ITopologyService.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/TopoEdgeUpdate.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/TopoEdgeUpdate.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/topology/TopoEdgeUpdate.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/TopoEdgeUpdate.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ConfigurationObject.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ConfigurationObject.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ConfigurationObject.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ConfigurationObject.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Direction.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Direction.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Direction.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Direction.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/EtherTypes.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/EtherTypes.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/EtherTypes.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/EtherTypes.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GUIField.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GUIField.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GUIField.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GUIField.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GlobalConstants.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GlobalConstants.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GlobalConstants.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GlobalConstants.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/HexEncode.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/HexEncode.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/HexEncode.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/HexEncode.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeConnectorFactory.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeConnectorFactory.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeConnectorFactory.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeConnectorFactory.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeFactory.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeFactory.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeFactory.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeFactory.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IObjectReader.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IObjectReader.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IObjectReader.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IObjectReader.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NetUtils.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NetUtils.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NetUtils.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NetUtils.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeConnectorCreator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeConnectorCreator.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeConnectorCreator.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeConnectorCreator.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeCreator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeCreator.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeCreator.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeCreator.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeTableCreator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeTableCreator.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeTableCreator.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeTableCreator.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectReader.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectReader.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectReader.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectReader.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectWriter.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectWriter.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectWriter.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectWriter.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ReadFromFile.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ReadFromFile.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ReadFromFile.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ReadFromFile.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ServiceHelper.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ServiceHelper.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ServiceHelper.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ServiceHelper.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Status.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Status.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Status.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Status.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/StatusCode.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/StatusCode.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/StatusCode.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/StatusCode.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/TierHelper.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/TierHelper.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/TierHelper.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/TierHelper.java diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/WriteToFile.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/WriteToFile.java similarity index 100% rename from opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/WriteToFile.java rename to opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/WriteToFile.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/action/ActionTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/action/ActionTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/action/ActionTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/action/ActionTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/authorization/AuthorizationTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/authorization/AuthorizationTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/authorization/AuthorizationTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/authorization/AuthorizationTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/EdgeTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/EdgeTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/EdgeTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/EdgeTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeConnectorTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeConnectorTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeConnectorTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeConnectorTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTableTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTableTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTableTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTableTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/PathTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PathTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/PathTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PathTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/PropertyTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PropertyTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/core/PropertyTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PropertyTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/flowprogrammer/FlowTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/flowprogrammer/FlowTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/flowprogrammer/FlowTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/flowprogrammer/FlowTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/BitBufferHelperTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/BitBufferHelperTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/BitBufferHelperTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/BitBufferHelperTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ICMPTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ICMPTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ICMPTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ICMPTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/address/EthernetAddressTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/address/EthernetAddressTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/address/EthernetAddressTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/address/EthernetAddressTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/FlowOnNodeTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/FlowOnNodeTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/FlowOnNodeTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/FlowOnNodeTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeConnectorStatisticsTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeConnectorStatisticsTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeConnectorStatisticsTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeConnectorStatisticsTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeDescriptionTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeDescriptionTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeDescriptionTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeDescriptionTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeTableStatisticsTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeTableStatisticsTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeTableStatisticsTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeTableStatisticsTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/EtherTypesTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/EtherTypesTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/EtherTypesTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/EtherTypesTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/HexEncodeTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/HexEncodeTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/HexEncodeTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/HexEncodeTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/NetUtilsTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/NetUtilsTest.java similarity index 100% rename from opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/utils/NetUtilsTest.java rename to opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/NetUtilsTest.java diff --git a/opendaylight/sal/connection/api/pom.xml b/opendaylight/adsal/sal/connection/api/pom.xml similarity index 96% rename from opendaylight/sal/connection/api/pom.xml rename to opendaylight/adsal/sal/connection/api/pom.xml index 780631791d..fe07526960 100644 --- a/opendaylight/sal/connection/api/pom.xml +++ b/opendaylight/adsal/sal/connection/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../commons/opendaylight + ../../../../commons/opendaylight sal.connection diff --git a/opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionConstants.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionConstants.java similarity index 100% rename from opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionConstants.java rename to opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionConstants.java diff --git a/opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionLocality.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionLocality.java similarity index 100% rename from opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionLocality.java rename to opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionLocality.java diff --git a/opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionListener.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionListener.java similarity index 100% rename from opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionListener.java rename to opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionListener.java diff --git a/opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionService.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionService.java similarity index 100% rename from opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionService.java rename to opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionService.java diff --git a/opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginInConnectionService.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginInConnectionService.java similarity index 100% rename from opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginInConnectionService.java rename to opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginInConnectionService.java diff --git a/opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginOutConnectionService.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginOutConnectionService.java similarity index 100% rename from opendaylight/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginOutConnectionService.java rename to opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginOutConnectionService.java diff --git a/opendaylight/sal/connection/implementation/pom.xml b/opendaylight/adsal/sal/connection/implementation/pom.xml similarity index 97% rename from opendaylight/sal/connection/implementation/pom.xml rename to opendaylight/adsal/sal/connection/implementation/pom.xml index a7d5dfafb9..b3c99daee3 100644 --- a/opendaylight/sal/connection/implementation/pom.xml +++ b/opendaylight/adsal/sal/connection/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../commons/opendaylight + ../../../../commons/opendaylight sal.connection.implementation diff --git a/opendaylight/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/Activator.java b/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/Activator.java similarity index 100% rename from opendaylight/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/Activator.java rename to opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/Activator.java diff --git a/opendaylight/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java b/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java similarity index 97% rename from opendaylight/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java rename to opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java index 7bd15ff7f4..5a637b7999 100644 --- a/opendaylight/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java +++ b/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java @@ -11,7 +11,6 @@ package org.opendaylight.controller.sal.connection.implementation.internal; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; - import org.opendaylight.controller.sal.connection.ConnectionConstants; import org.opendaylight.controller.sal.connection.ConnectionLocality; import org.opendaylight.controller.sal.connection.IConnectionListener; @@ -32,7 +31,7 @@ public class ConnectionService implements IPluginOutConnectionService, IConnecti private ConcurrentMap pluginService = new ConcurrentHashMap(); - void setPluginService (Map props, IPluginInConnectionService s) { + void setPluginService (Map props, IPluginInConnectionService s) { String type = null; Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString()); if (value instanceof String) { @@ -46,7 +45,7 @@ public class ConnectionService implements IPluginOutConnectionService, IConnecti } } - void unsetPluginService(Map props, IPluginInConnectionService s) { + void unsetPluginService(Map props, IPluginInConnectionService s) { String type = null; Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString()); diff --git a/opendaylight/sal/implementation/pom.xml b/opendaylight/adsal/sal/implementation/pom.xml similarity index 97% rename from opendaylight/sal/implementation/pom.xml rename to opendaylight/adsal/sal/implementation/pom.xml index 3f1aa86be8..bce6e3b547 100644 --- a/opendaylight/sal/implementation/pom.xml +++ b/opendaylight/adsal/sal/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight sal.implementation diff --git a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Activator.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Activator.java similarity index 100% rename from opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Activator.java rename to opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Activator.java diff --git a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java similarity index 96% rename from opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java rename to opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java index 0c9ebab8c3..6f23cc735a 100644 --- a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java +++ b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java @@ -204,23 +204,22 @@ public class DataPacketService implements IPluginOutDataPacketService, } } - void setPluginInDataService(Map props, IPluginInDataPacketService s) { + void setPluginInDataService(Map props, IPluginInDataPacketService s) { ProtocolService.set(this.pluginInDataService, props, s, logger); } - void unsetPluginInDataService(Map props, IPluginInDataPacketService s) { + void unsetPluginInDataService(Map props, IPluginInDataPacketService s) { ProtocolService.unset(this.pluginInDataService, props, s, logger); } - void setListenDataPacket(Map props, IListenDataPacket s) { + void setListenDataPacket(Map props, IListenDataPacket s) { if (this.listenDataPacket == null || this.indexDataPacket == null) { logger.error("data structure to store data is NULL"); return; } logger.trace("Received setListenDataPacket request"); - for (Object e : props.entrySet()) { - Map.Entry entry = (Map.Entry) e; - logger.trace("Prop key:({}) value:({})",entry.getKey(), entry.getValue()); + for (Map.Entry e : props.entrySet()) { + logger.trace("Prop key:({}) value:({})",e.getKey(), e.getValue()); } String listenerName = null; @@ -295,15 +294,14 @@ public class DataPacketService implements IPluginOutDataPacketService, } } - void unsetListenDataPacket(Map props, IListenDataPacket s) { + void unsetListenDataPacket(Map props, IListenDataPacket s) { if (this.listenDataPacket == null || this.indexDataPacket == null) { logger.error("data structure to store data is NULL"); return; } logger.trace("Received UNsetListenDataPacket request"); - for (Object e : props.entrySet()) { - Map.Entry entry = (Map.Entry) e; - logger.trace("Prop key:({}) value:({})",entry.getKey(), entry.getValue()); + for (Map.Entry e : props.entrySet()) { + logger.trace("Prop key:({}) value:({})",e.getKey(), e.getValue()); } String listenerName = null; diff --git a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/FlowProgrammerService.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/FlowProgrammerService.java similarity index 100% rename from opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/FlowProgrammerService.java rename to opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/FlowProgrammerService.java diff --git a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Inventory.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Inventory.java similarity index 100% rename from opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Inventory.java rename to opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Inventory.java diff --git a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java similarity index 99% rename from opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java rename to opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java index e9dc2ad0ee..c0b61278a6 100644 --- a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java +++ b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java @@ -195,7 +195,7 @@ public final class ProtocolService { return false; } - ProtocolService plugin = (ProtocolService)o; + ProtocolService plugin = (ProtocolService)o; return (service.equals(plugin.service) && priority == plugin.priority); } diff --git a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ReadService.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ReadService.java similarity index 100% rename from opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ReadService.java rename to opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ReadService.java diff --git a/opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Topology.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Topology.java similarity index 100% rename from opendaylight/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Topology.java rename to opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Topology.java diff --git a/opendaylight/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/DataPacketServiceTest.java b/opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/DataPacketServiceTest.java similarity index 100% rename from opendaylight/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/DataPacketServiceTest.java rename to opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/DataPacketServiceTest.java diff --git a/opendaylight/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/ProtocolServiceTest.java b/opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/ProtocolServiceTest.java similarity index 100% rename from opendaylight/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/ProtocolServiceTest.java rename to opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/ProtocolServiceTest.java diff --git a/opendaylight/sal/networkconfiguration/api/pom.xml b/opendaylight/adsal/sal/networkconfiguration/api/pom.xml similarity index 96% rename from opendaylight/sal/networkconfiguration/api/pom.xml rename to opendaylight/adsal/sal/networkconfiguration/api/pom.xml index 4b18349745..bbeb2969d6 100644 --- a/opendaylight/sal/networkconfiguration/api/pom.xml +++ b/opendaylight/adsal/sal/networkconfiguration/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../commons/opendaylight + ../../../../commons/opendaylight sal.networkconfiguration diff --git a/opendaylight/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/BridgeDomainConfigServiceException.java b/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/BridgeDomainConfigServiceException.java similarity index 100% rename from opendaylight/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/BridgeDomainConfigServiceException.java rename to opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/BridgeDomainConfigServiceException.java diff --git a/opendaylight/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/ConfigConstants.java b/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/ConfigConstants.java similarity index 100% rename from opendaylight/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/ConfigConstants.java rename to opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/ConfigConstants.java diff --git a/opendaylight/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IBridgeDomainConfigService.java b/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IBridgeDomainConfigService.java similarity index 100% rename from opendaylight/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IBridgeDomainConfigService.java rename to opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IBridgeDomainConfigService.java diff --git a/opendaylight/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IPluginInBridgeDomainConfigService.java b/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IPluginInBridgeDomainConfigService.java similarity index 100% rename from opendaylight/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IPluginInBridgeDomainConfigService.java rename to opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IPluginInBridgeDomainConfigService.java diff --git a/opendaylight/sal/networkconfiguration/implementation/pom.xml b/opendaylight/adsal/sal/networkconfiguration/implementation/pom.xml similarity index 96% rename from opendaylight/sal/networkconfiguration/implementation/pom.xml rename to opendaylight/adsal/sal/networkconfiguration/implementation/pom.xml index bf476a924a..df8c6d2169 100644 --- a/opendaylight/sal/networkconfiguration/implementation/pom.xml +++ b/opendaylight/adsal/sal/networkconfiguration/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../commons/opendaylight + ../../../../commons/opendaylight sal.networkconfiguration.implementation diff --git a/opendaylight/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/internal/BridgeDomainConfigService.java b/opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/internal/BridgeDomainConfigService.java similarity index 100% rename from opendaylight/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/internal/BridgeDomainConfigService.java rename to opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/internal/BridgeDomainConfigService.java diff --git a/opendaylight/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/internal/Activator.java b/opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/internal/Activator.java similarity index 100% rename from opendaylight/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/internal/Activator.java rename to opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/internal/Activator.java diff --git a/opendaylight/samples/clustersession/pom.xml b/opendaylight/adsal/samples/clustersession/pom.xml similarity index 98% rename from opendaylight/samples/clustersession/pom.xml rename to opendaylight/adsal/samples/clustersession/pom.xml index 10ae20ca63..2a5e07af84 100644 --- a/opendaylight/samples/clustersession/pom.xml +++ b/opendaylight/adsal/samples/clustersession/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight org.opendaylight.controller clustersession diff --git a/opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSession.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSession.java similarity index 100% rename from opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSession.java rename to opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSession.java diff --git a/opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionData.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionData.java similarity index 100% rename from opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionData.java rename to opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionData.java diff --git a/opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionManager.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionManager.java similarity index 100% rename from opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionManager.java rename to opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionManager.java diff --git a/opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionUtil.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionUtil.java similarity index 100% rename from opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionUtil.java rename to opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionUtil.java diff --git a/opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/impl/ClusterSessionServiceImpl.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/impl/ClusterSessionServiceImpl.java similarity index 100% rename from opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/impl/ClusterSessionServiceImpl.java rename to opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/impl/ClusterSessionServiceImpl.java diff --git a/opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/service/ClusterSessionService.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/service/ClusterSessionService.java similarity index 100% rename from opendaylight/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/service/ClusterSessionService.java rename to opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/service/ClusterSessionService.java diff --git a/opendaylight/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionManagerTest.java b/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionManagerTest.java similarity index 100% rename from opendaylight/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionManagerTest.java rename to opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionManagerTest.java diff --git a/opendaylight/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionServiceImplTest.java b/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionServiceImplTest.java similarity index 100% rename from opendaylight/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionServiceImplTest.java rename to opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionServiceImplTest.java diff --git a/opendaylight/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionUtilTest.java b/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionUtilTest.java similarity index 100% rename from opendaylight/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionUtilTest.java rename to opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionUtilTest.java diff --git a/opendaylight/samples/loadbalancer/pom.xml b/opendaylight/adsal/samples/loadbalancer/pom.xml similarity index 98% rename from opendaylight/samples/loadbalancer/pom.xml rename to opendaylight/adsal/samples/loadbalancer/pom.xml index a7b41096d7..e1b480771b 100644 --- a/opendaylight/samples/loadbalancer/pom.xml +++ b/opendaylight/adsal/samples/loadbalancer/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight samples.loadbalancer diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/ConfigManager.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/ConfigManager.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/ConfigManager.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/ConfigManager.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/IConfigManager.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/IConfigManager.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/IConfigManager.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/IConfigManager.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBConst.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBConst.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBConst.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBConst.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBUtil.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBUtil.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBUtil.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBUtil.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Client.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Client.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Client.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Client.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Pool.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Pool.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Pool.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Pool.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/PoolMember.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/PoolMember.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/PoolMember.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/PoolMember.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/VIP.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/VIP.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/VIP.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/VIP.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/Activator.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/Activator.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/Activator.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/Activator.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerService.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerService.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerService.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerService.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/ILoadBalancingPolicy.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/ILoadBalancingPolicy.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/ILoadBalancingPolicy.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/ILoadBalancingPolicy.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RandomLBPolicy.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RandomLBPolicy.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RandomLBPolicy.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RandomLBPolicy.java diff --git a/opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RoundRobinLBPolicy.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RoundRobinLBPolicy.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RoundRobinLBPolicy.java rename to opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RoundRobinLBPolicy.java diff --git a/opendaylight/samples/loadbalancer/src/test/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerTest.java b/opendaylight/adsal/samples/loadbalancer/src/test/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerTest.java similarity index 100% rename from opendaylight/samples/loadbalancer/src/test/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerTest.java rename to opendaylight/adsal/samples/loadbalancer/src/test/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerTest.java diff --git a/opendaylight/samples/northbound/loadbalancer/enunciate.xml b/opendaylight/adsal/samples/northbound/loadbalancer/enunciate.xml similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/enunciate.xml rename to opendaylight/adsal/samples/northbound/loadbalancer/enunciate.xml diff --git a/opendaylight/samples/northbound/loadbalancer/pom.xml b/opendaylight/adsal/samples/northbound/loadbalancer/pom.xml similarity index 98% rename from opendaylight/samples/northbound/loadbalancer/pom.xml rename to opendaylight/adsal/samples/northbound/loadbalancer/pom.xml index 18aa4e1d62..e63e992b3f 100644 --- a/opendaylight/samples/northbound/loadbalancer/pom.xml +++ b/opendaylight/adsal/samples/northbound/loadbalancer/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../../commons/opendaylight + ../../../../commons/opendaylight samples.loadbalancer.northbound diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/LoadBalancerNorthbound.java b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/LoadBalancerNorthbound.java similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/LoadBalancerNorthbound.java rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/LoadBalancerNorthbound.java diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/NBConst.java b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/NBConst.java similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/NBConst.java rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/NBConst.java diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/Pools.java b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/Pools.java similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/Pools.java rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/Pools.java diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/VIPs.java b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/VIPs.java similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/VIPs.java rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/VIPs.java diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/samples/northbound/loadbalancer/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/samples/northbound/loadbalancer/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/samples/simpleforwarding/pom.xml b/opendaylight/adsal/samples/simpleforwarding/pom.xml similarity index 98% rename from opendaylight/samples/simpleforwarding/pom.xml rename to opendaylight/adsal/samples/simpleforwarding/pom.xml index 50410f85af..4d7af2b8fd 100644 --- a/opendaylight/samples/simpleforwarding/pom.xml +++ b/opendaylight/adsal/samples/simpleforwarding/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight samples.simpleforwarding diff --git a/opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/HostNodePair.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/HostNodePair.java similarity index 100% rename from opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/HostNodePair.java rename to opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/HostNodePair.java diff --git a/opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastHandler.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastHandler.java similarity index 100% rename from opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastHandler.java rename to opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastHandler.java diff --git a/opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastPortSelector.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastPortSelector.java similarity index 100% rename from opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastPortSelector.java rename to opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastPortSelector.java diff --git a/opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/Activator.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/Activator.java similarity index 100% rename from opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/Activator.java rename to opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/Activator.java diff --git a/opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleBroadcastHandlerImpl.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleBroadcastHandlerImpl.java similarity index 100% rename from opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleBroadcastHandlerImpl.java rename to opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleBroadcastHandlerImpl.java diff --git a/opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleForwardingImpl.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleForwardingImpl.java similarity index 100% rename from opendaylight/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleForwardingImpl.java rename to opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleForwardingImpl.java diff --git a/opendaylight/samples/simpleforwarding/src/test/java/org/opendaylight/controller/samples/simpleforwarding/internal/HostSwitchTest.java b/opendaylight/adsal/samples/simpleforwarding/src/test/java/org/opendaylight/controller/samples/simpleforwarding/internal/HostSwitchTest.java similarity index 100% rename from opendaylight/samples/simpleforwarding/src/test/java/org/opendaylight/controller/samples/simpleforwarding/internal/HostSwitchTest.java rename to opendaylight/adsal/samples/simpleforwarding/src/test/java/org/opendaylight/controller/samples/simpleforwarding/internal/HostSwitchTest.java diff --git a/opendaylight/security/pom.xml b/opendaylight/adsal/security/pom.xml similarity index 97% rename from opendaylight/security/pom.xml rename to opendaylight/adsal/security/pom.xml index 49889de7f1..436fda24da 100644 --- a/opendaylight/security/pom.xml +++ b/opendaylight/adsal/security/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../commons/opendaylight + ../../commons/opendaylight security diff --git a/opendaylight/security/src/main/java/org/opendaylight/controller/security/ControllerCustomRealm.java b/opendaylight/adsal/security/src/main/java/org/opendaylight/controller/security/ControllerCustomRealm.java similarity index 100% rename from opendaylight/security/src/main/java/org/opendaylight/controller/security/ControllerCustomRealm.java rename to opendaylight/adsal/security/src/main/java/org/opendaylight/controller/security/ControllerCustomRealm.java diff --git a/opendaylight/statisticsmanager/api/pom.xml b/opendaylight/adsal/statisticsmanager/api/pom.xml similarity index 96% rename from opendaylight/statisticsmanager/api/pom.xml rename to opendaylight/adsal/statisticsmanager/api/pom.xml index 23edfa3991..00e23e0f5a 100644 --- a/opendaylight/statisticsmanager/api/pom.xml +++ b/opendaylight/adsal/statisticsmanager/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight statisticsmanager diff --git a/opendaylight/statisticsmanager/api/src/main/java/org/opendaylight/controller/statisticsmanager/IStatisticsManager.java b/opendaylight/adsal/statisticsmanager/api/src/main/java/org/opendaylight/controller/statisticsmanager/IStatisticsManager.java similarity index 100% rename from opendaylight/statisticsmanager/api/src/main/java/org/opendaylight/controller/statisticsmanager/IStatisticsManager.java rename to opendaylight/adsal/statisticsmanager/api/src/main/java/org/opendaylight/controller/statisticsmanager/IStatisticsManager.java diff --git a/opendaylight/statisticsmanager/implementation/pom.xml b/opendaylight/adsal/statisticsmanager/implementation/pom.xml similarity index 98% rename from opendaylight/statisticsmanager/implementation/pom.xml rename to opendaylight/adsal/statisticsmanager/implementation/pom.xml index 08db43a0f0..aa009fbf23 100644 --- a/opendaylight/statisticsmanager/implementation/pom.xml +++ b/opendaylight/adsal/statisticsmanager/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight statisticsmanager.implementation diff --git a/opendaylight/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/Activator.java b/opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/Activator.java similarity index 100% rename from opendaylight/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/Activator.java rename to opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/Activator.java diff --git a/opendaylight/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManager.java b/opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManager.java similarity index 100% rename from opendaylight/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManager.java rename to opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManager.java diff --git a/opendaylight/statisticsmanager/implementation/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerTest.java b/opendaylight/adsal/statisticsmanager/implementation/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerTest.java similarity index 100% rename from opendaylight/statisticsmanager/implementation/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerTest.java rename to opendaylight/adsal/statisticsmanager/implementation/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerTest.java diff --git a/opendaylight/statisticsmanager/integrationtest/pom.xml b/opendaylight/adsal/statisticsmanager/integrationtest/pom.xml similarity index 95% rename from opendaylight/statisticsmanager/integrationtest/pom.xml rename to opendaylight/adsal/statisticsmanager/integrationtest/pom.xml index 22696b71e6..857921f14b 100644 --- a/opendaylight/statisticsmanager/integrationtest/pom.xml +++ b/opendaylight/adsal/statisticsmanager/integrationtest/pom.xml @@ -11,9 +11,9 @@ statisticsmanager.integrationtest 0.5.0-SNAPSHOT - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec - ../implementation/target/jacoco.exec + ../../implementation/target/jacoco.exec @@ -141,7 +141,7 @@ org.jacoco jacoco-maven-plugin - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec org.opendaylight.controller.* diff --git a/opendaylight/statisticsmanager/integrationtest/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerIT.java b/opendaylight/adsal/statisticsmanager/integrationtest/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerIT.java similarity index 100% rename from opendaylight/statisticsmanager/integrationtest/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerIT.java rename to opendaylight/adsal/statisticsmanager/integrationtest/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerIT.java diff --git a/opendaylight/statisticsmanager/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/statisticsmanager/integrationtest/src/test/resources/logback.xml similarity index 100% rename from opendaylight/statisticsmanager/integrationtest/src/test/resources/logback.xml rename to opendaylight/adsal/statisticsmanager/integrationtest/src/test/resources/logback.xml diff --git a/opendaylight/switchmanager/api/pom.xml b/opendaylight/adsal/switchmanager/api/pom.xml similarity index 98% rename from opendaylight/switchmanager/api/pom.xml rename to opendaylight/adsal/switchmanager/api/pom.xml index a29341ee6f..3c23e29131 100644 --- a/opendaylight/switchmanager/api/pom.xml +++ b/opendaylight/adsal/switchmanager/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight switchmanager diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/IInventoryListener.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/IInventoryListener.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/IInventoryListener.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/IInventoryListener.java diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISpanAware.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISpanAware.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISpanAware.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISpanAware.java diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManager.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManager.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManager.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManager.java diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManagerAware.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManagerAware.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManagerAware.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManagerAware.java diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SpanConfig.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SpanConfig.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SpanConfig.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SpanConfig.java diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Subnet.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Subnet.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Subnet.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Subnet.java diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SubnetConfig.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SubnetConfig.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SubnetConfig.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SubnetConfig.java diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Switch.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Switch.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Switch.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Switch.java diff --git a/opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SwitchConfig.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SwitchConfig.java similarity index 100% rename from opendaylight/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SwitchConfig.java rename to opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SwitchConfig.java diff --git a/opendaylight/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetConfigTest.java b/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetConfigTest.java similarity index 100% rename from opendaylight/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetConfigTest.java rename to opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetConfigTest.java diff --git a/opendaylight/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetTest.java b/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetTest.java similarity index 100% rename from opendaylight/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetTest.java rename to opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetTest.java diff --git a/opendaylight/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SwitchTest.java b/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SwitchTest.java similarity index 100% rename from opendaylight/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SwitchTest.java rename to opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SwitchTest.java diff --git a/opendaylight/switchmanager/implementation/pom.xml b/opendaylight/adsal/switchmanager/implementation/pom.xml similarity index 98% rename from opendaylight/switchmanager/implementation/pom.xml rename to opendaylight/adsal/switchmanager/implementation/pom.xml index fe7a0c0bcb..911d5dd71f 100644 --- a/opendaylight/switchmanager/implementation/pom.xml +++ b/opendaylight/adsal/switchmanager/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight switchmanager.implementation diff --git a/opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/Activator.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/Activator.java similarity index 100% rename from opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/Activator.java rename to opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/Activator.java diff --git a/opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/ControllerProperties.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/ControllerProperties.java similarity index 100% rename from opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/ControllerProperties.java rename to opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/ControllerProperties.java diff --git a/opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/IControllerProperties.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/IControllerProperties.java similarity index 100% rename from opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/IControllerProperties.java rename to opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/IControllerProperties.java diff --git a/opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManager.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManager.java similarity index 100% rename from opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManager.java rename to opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManager.java diff --git a/opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerCLI.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerCLI.java similarity index 100% rename from opendaylight/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerCLI.java rename to opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerCLI.java diff --git a/opendaylight/switchmanager/implementation/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerTest.java b/opendaylight/adsal/switchmanager/implementation/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerTest.java similarity index 100% rename from opendaylight/switchmanager/implementation/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerTest.java rename to opendaylight/adsal/switchmanager/implementation/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerTest.java diff --git a/opendaylight/switchmanager/integrationtest/pom.xml b/opendaylight/adsal/switchmanager/integrationtest/pom.xml similarity index 94% rename from opendaylight/switchmanager/integrationtest/pom.xml rename to opendaylight/adsal/switchmanager/integrationtest/pom.xml index 708ac32763..158cd2ca82 100644 --- a/opendaylight/switchmanager/integrationtest/pom.xml +++ b/opendaylight/adsal/switchmanager/integrationtest/pom.xml @@ -11,9 +11,9 @@ switchmanager.integrationtest 0.5.0-SNAPSHOT - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec - ../implementation/target/jacoco.exec + ../../implementation/target/jacoco.exec @@ -118,7 +118,7 @@ org.jacoco jacoco-maven-plugin - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec org.opendaylight.controller.* diff --git a/opendaylight/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java b/opendaylight/adsal/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java similarity index 99% rename from opendaylight/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java rename to opendaylight/adsal/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java index 64098ec515..3963abf265 100644 --- a/opendaylight/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java +++ b/opendaylight/adsal/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java @@ -155,7 +155,7 @@ public class SwitchManagerIT { assertFalse(debugit); // Now lets create a hosttracker for testing purpose - ServiceReference s = bc.getServiceReference(ISwitchManager.class + ServiceReference s = bc.getServiceReference(ISwitchManager.class .getName()); if (s != null) { this.switchManager = (ISwitchManager) bc.getService(s); diff --git a/opendaylight/switchmanager/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/switchmanager/integrationtest/src/test/resources/logback.xml similarity index 100% rename from opendaylight/switchmanager/integrationtest/src/test/resources/logback.xml rename to opendaylight/adsal/switchmanager/integrationtest/src/test/resources/logback.xml diff --git a/opendaylight/topologymanager/implementation/pom.xml b/opendaylight/adsal/topologymanager/implementation/pom.xml similarity index 96% rename from opendaylight/topologymanager/implementation/pom.xml rename to opendaylight/adsal/topologymanager/implementation/pom.xml index 430dfca74d..c7a6444e1e 100644 --- a/opendaylight/topologymanager/implementation/pom.xml +++ b/opendaylight/adsal/topologymanager/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight topologymanager @@ -44,7 +44,6 @@ org.apache.felix maven-bundle-plugin - ${bundle.plugin.version} true diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManager.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManager.java similarity index 100% rename from opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManager.java rename to opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManager.java diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerAware.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerAware.java similarity index 100% rename from opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerAware.java rename to opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerAware.java diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerClusterWideAware.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerClusterWideAware.java similarity index 100% rename from opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerClusterWideAware.java rename to opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerClusterWideAware.java diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java similarity index 100% rename from opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java rename to opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/TopologyUserLinkConfig.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/TopologyUserLinkConfig.java similarity index 100% rename from opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/TopologyUserLinkConfig.java rename to opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/TopologyUserLinkConfig.java diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java similarity index 100% rename from opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java rename to opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java similarity index 100% rename from opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java rename to opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java diff --git a/opendaylight/topologymanager/implementation/src/test/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImplTest.java b/opendaylight/adsal/topologymanager/implementation/src/test/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImplTest.java similarity index 100% rename from opendaylight/topologymanager/implementation/src/test/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImplTest.java rename to opendaylight/adsal/topologymanager/implementation/src/test/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImplTest.java diff --git a/opendaylight/topologymanager/integrationtest/pom.xml b/opendaylight/adsal/topologymanager/integrationtest/pom.xml similarity index 93% rename from opendaylight/topologymanager/integrationtest/pom.xml rename to opendaylight/adsal/topologymanager/integrationtest/pom.xml index ce6422c8c1..028e775ee0 100644 --- a/opendaylight/topologymanager/integrationtest/pom.xml +++ b/opendaylight/adsal/topologymanager/integrationtest/pom.xml @@ -11,9 +11,9 @@ topologymanager.integrationtest 0.5.0-SNAPSHOT - ../implementaiton/target/jacoco-it.exec + ../../implementaiton/target/jacoco-it.exec - ../implementation/target/jacoco.exec + ../../implementation/target/jacoco.exec @@ -92,7 +92,7 @@ org.jacoco jacoco-maven-plugin - ../implementation/target/jacoco-it.exec + ../../implementation/target/jacoco-it.exec org.opendaylight.controller.* diff --git a/opendaylight/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java b/opendaylight/adsal/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java similarity index 98% rename from opendaylight/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java rename to opendaylight/adsal/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java index 08934f32c7..c2fc8aaa8e 100644 --- a/opendaylight/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java +++ b/opendaylight/adsal/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java @@ -159,7 +159,7 @@ public class TopologyManagerIT { Set properties = new HashSet(); - ServiceReference r = bc.getServiceReference(IPluginInTopologyService.class + ServiceReference r = bc.getServiceReference(IPluginInTopologyService.class .getName()); TopologyServices topologyServices = null; if (r != null) { diff --git a/opendaylight/topologymanager/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/topologymanager/integrationtest/src/test/resources/logback.xml similarity index 100% rename from opendaylight/topologymanager/integrationtest/src/test/resources/logback.xml rename to opendaylight/adsal/topologymanager/integrationtest/src/test/resources/logback.xml diff --git a/opendaylight/topologymanager/shell/pom.xml b/opendaylight/adsal/topologymanager/shell/pom.xml similarity index 90% rename from opendaylight/topologymanager/shell/pom.xml rename to opendaylight/adsal/topologymanager/shell/pom.xml index 2de8c5c26c..a5b21f6224 100644 --- a/opendaylight/topologymanager/shell/pom.xml +++ b/opendaylight/adsal/topologymanager/shell/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight topologymanager.shell ${topologymanager.shell.version} @@ -27,7 +27,6 @@ org.opendaylight.controller topologymanager - ${topologymanager.version} @@ -36,7 +35,6 @@ org.apache.felix maven-bundle-plugin - ${bundle.plugin.version} org.apache.felix.service.command, diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java b/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java similarity index 100% rename from opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java rename to opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java b/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java similarity index 100% rename from opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java rename to opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java b/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java similarity index 100% rename from opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java rename to opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java b/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java similarity index 100% rename from opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java rename to opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java diff --git a/opendaylight/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/adsal/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml similarity index 100% rename from opendaylight/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml rename to opendaylight/adsal/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml diff --git a/opendaylight/usermanager/api/pom.xml b/opendaylight/adsal/usermanager/api/pom.xml similarity index 98% rename from opendaylight/usermanager/api/pom.xml rename to opendaylight/adsal/usermanager/api/pom.xml index e21337242a..76f293b197 100644 --- a/opendaylight/usermanager/api/pom.xml +++ b/opendaylight/adsal/usermanager/api/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight usermanager diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthenticatedUser.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthenticatedUser.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthenticatedUser.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthenticatedUser.java diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java diff --git a/opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java similarity index 100% rename from opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java rename to opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java diff --git a/opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java b/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java similarity index 100% rename from opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java rename to opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java diff --git a/opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthenticatedUserTest.java b/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthenticatedUserTest.java similarity index 100% rename from opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthenticatedUserTest.java rename to opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthenticatedUserTest.java diff --git a/opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthorizationUserConfigTest.java b/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthorizationUserConfigTest.java similarity index 100% rename from opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthorizationUserConfigTest.java rename to opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthorizationUserConfigTest.java diff --git a/opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/ServerConfigTest.java b/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/ServerConfigTest.java similarity index 100% rename from opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/ServerConfigTest.java rename to opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/ServerConfigTest.java diff --git a/opendaylight/usermanager/implementation/pom.xml b/opendaylight/adsal/usermanager/implementation/pom.xml similarity index 98% rename from opendaylight/usermanager/implementation/pom.xml rename to opendaylight/adsal/usermanager/implementation/pom.xml index d973f670b2..fd8a397837 100644 --- a/opendaylight/usermanager/implementation/pom.xml +++ b/opendaylight/adsal/usermanager/implementation/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight usermanager.implementation diff --git a/opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java b/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java similarity index 100% rename from opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java rename to opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java diff --git a/opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManager.java b/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManager.java similarity index 100% rename from opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManager.java rename to opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManager.java diff --git a/opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java b/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java similarity index 100% rename from opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java rename to opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java diff --git a/opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java b/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java similarity index 100% rename from opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java rename to opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java diff --git a/opendaylight/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java b/opendaylight/adsal/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java similarity index 100% rename from opendaylight/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java rename to opendaylight/adsal/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java diff --git a/opendaylight/web/brandfragment/pom.xml b/opendaylight/adsal/web/brandfragment/pom.xml similarity index 95% rename from opendaylight/web/brandfragment/pom.xml rename to opendaylight/adsal/web/brandfragment/pom.xml index 25f62f059e..0c76146c50 100644 --- a/opendaylight/web/brandfragment/pom.xml +++ b/opendaylight/adsal/web/brandfragment/pom.xml @@ -7,7 +7,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight scm:git:ssh://git.opendaylight.org:29418/controller.git diff --git a/opendaylight/web/brandfragment/src/main/resources/WEB-INF/jsp/customerror.jsp b/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customerror.jsp similarity index 100% rename from opendaylight/web/brandfragment/src/main/resources/WEB-INF/jsp/customerror.jsp rename to opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customerror.jsp diff --git a/opendaylight/web/brandfragment/src/main/resources/WEB-INF/jsp/customlogin.jsp b/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customlogin.jsp similarity index 100% rename from opendaylight/web/brandfragment/src/main/resources/WEB-INF/jsp/customlogin.jsp rename to opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customlogin.jsp diff --git a/opendaylight/web/brandfragment/src/main/resources/WEB-INF/jsp/custommain.jsp b/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/custommain.jsp similarity index 100% rename from opendaylight/web/brandfragment/src/main/resources/WEB-INF/jsp/custommain.jsp rename to opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/custommain.jsp diff --git a/opendaylight/web/brandfragment/src/main/resources/css/customlogin.less b/opendaylight/adsal/web/brandfragment/src/main/resources/css/customlogin.less similarity index 100% rename from opendaylight/web/brandfragment/src/main/resources/css/customlogin.less rename to opendaylight/adsal/web/brandfragment/src/main/resources/css/customlogin.less diff --git a/opendaylight/web/brandfragment/src/main/resources/css/custommain.less b/opendaylight/adsal/web/brandfragment/src/main/resources/css/custommain.less similarity index 100% rename from opendaylight/web/brandfragment/src/main/resources/css/custommain.less rename to opendaylight/adsal/web/brandfragment/src/main/resources/css/custommain.less diff --git a/opendaylight/web/brandfragment/src/main/resources/img/logo.png b/opendaylight/adsal/web/brandfragment/src/main/resources/img/logo.png similarity index 100% rename from opendaylight/web/brandfragment/src/main/resources/img/logo.png rename to opendaylight/adsal/web/brandfragment/src/main/resources/img/logo.png diff --git a/opendaylight/web/devices/pom.xml b/opendaylight/adsal/web/devices/pom.xml similarity index 98% rename from opendaylight/web/devices/pom.xml rename to opendaylight/adsal/web/devices/pom.xml index 8e7c9248dd..062812b867 100644 --- a/opendaylight/web/devices/pom.xml +++ b/opendaylight/adsal/web/devices/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight devices.web diff --git a/opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java similarity index 100% rename from opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java rename to opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java diff --git a/opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/DevicesJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/DevicesJsonBean.java similarity index 100% rename from opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/DevicesJsonBean.java rename to opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/DevicesJsonBean.java diff --git a/opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/NodeJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/NodeJsonBean.java similarity index 100% rename from opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/NodeJsonBean.java rename to opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/NodeJsonBean.java diff --git a/opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/PortJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/PortJsonBean.java similarity index 100% rename from opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/PortJsonBean.java rename to opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/PortJsonBean.java diff --git a/opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/SpanPortJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SpanPortJsonBean.java similarity index 100% rename from opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/SpanPortJsonBean.java rename to opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SpanPortJsonBean.java diff --git a/opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/StatusJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/StatusJsonBean.java similarity index 100% rename from opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/StatusJsonBean.java rename to opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/StatusJsonBean.java diff --git a/opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/SubnetGatewayPortBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SubnetGatewayPortBean.java similarity index 100% rename from opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/SubnetGatewayPortBean.java rename to opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SubnetGatewayPortBean.java diff --git a/opendaylight/web/devices/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/web/devices/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/web/devices/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/web/devices/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/web/devices/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/web/devices/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/web/devices/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/web/devices/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/web/devices/src/main/resources/WEB-INF/Devices-servlet.xml b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/Devices-servlet.xml similarity index 100% rename from opendaylight/web/devices/src/main/resources/WEB-INF/Devices-servlet.xml rename to opendaylight/adsal/web/devices/src/main/resources/WEB-INF/Devices-servlet.xml diff --git a/opendaylight/web/devices/src/main/resources/WEB-INF/jsp/autherror.jsp b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/autherror.jsp similarity index 100% rename from opendaylight/web/devices/src/main/resources/WEB-INF/jsp/autherror.jsp rename to opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/autherror.jsp diff --git a/opendaylight/web/devices/src/main/resources/WEB-INF/jsp/error.jsp b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/error.jsp similarity index 100% rename from opendaylight/web/devices/src/main/resources/WEB-INF/jsp/error.jsp rename to opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/error.jsp diff --git a/opendaylight/web/devices/src/main/resources/WEB-INF/jsp/login.jsp b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/login.jsp similarity index 100% rename from opendaylight/web/devices/src/main/resources/WEB-INF/jsp/login.jsp rename to opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/login.jsp diff --git a/opendaylight/web/devices/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/web/devices/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/web/devices/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/web/devices/src/main/resources/js/page.js b/opendaylight/adsal/web/devices/src/main/resources/js/page.js similarity index 100% rename from opendaylight/web/devices/src/main/resources/js/page.js rename to opendaylight/adsal/web/devices/src/main/resources/js/page.js diff --git a/opendaylight/web/flows/pom.xml b/opendaylight/adsal/web/flows/pom.xml similarity index 98% rename from opendaylight/web/flows/pom.xml rename to opendaylight/adsal/web/flows/pom.xml index 99238c6aad..4b1d54781a 100644 --- a/opendaylight/web/flows/pom.xml +++ b/opendaylight/adsal/web/flows/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight flows.web diff --git a/opendaylight/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java b/opendaylight/adsal/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java similarity index 100% rename from opendaylight/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java rename to opendaylight/adsal/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java diff --git a/opendaylight/web/flows/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/web/flows/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/web/flows/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/web/flows/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/web/flows/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/web/flows/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/web/flows/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/web/flows/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/web/flows/src/main/resources/WEB-INF/Flows-servlet.xml b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/Flows-servlet.xml similarity index 100% rename from opendaylight/web/flows/src/main/resources/WEB-INF/Flows-servlet.xml rename to opendaylight/adsal/web/flows/src/main/resources/WEB-INF/Flows-servlet.xml diff --git a/opendaylight/web/flows/src/main/resources/WEB-INF/jsp/autherror.jsp b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/autherror.jsp similarity index 100% rename from opendaylight/web/flows/src/main/resources/WEB-INF/jsp/autherror.jsp rename to opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/autherror.jsp diff --git a/opendaylight/web/flows/src/main/resources/WEB-INF/jsp/error.jsp b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/error.jsp similarity index 100% rename from opendaylight/web/flows/src/main/resources/WEB-INF/jsp/error.jsp rename to opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/error.jsp diff --git a/opendaylight/web/flows/src/main/resources/WEB-INF/jsp/login.jsp b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/login.jsp similarity index 100% rename from opendaylight/web/flows/src/main/resources/WEB-INF/jsp/login.jsp rename to opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/login.jsp diff --git a/opendaylight/web/flows/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/web/flows/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/web/flows/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/web/flows/src/main/resources/js/page.js b/opendaylight/adsal/web/flows/src/main/resources/js/page.js similarity index 100% rename from opendaylight/web/flows/src/main/resources/js/page.js rename to opendaylight/adsal/web/flows/src/main/resources/js/page.js diff --git a/opendaylight/web/osgi-brandfragment/pom.xml b/opendaylight/adsal/web/osgi-brandfragment/pom.xml similarity index 94% rename from opendaylight/web/osgi-brandfragment/pom.xml rename to opendaylight/adsal/web/osgi-brandfragment/pom.xml index adea8ace62..78ad3f24c7 100644 --- a/opendaylight/web/osgi-brandfragment/pom.xml +++ b/opendaylight/adsal/web/osgi-brandfragment/pom.xml @@ -6,7 +6,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight osgi-brandfragment.web diff --git a/opendaylight/web/osgi-brandfragment/src/main/resources/META-INF/webconsole.properties b/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/META-INF/webconsole.properties similarity index 100% rename from opendaylight/web/osgi-brandfragment/src/main/resources/META-INF/webconsole.properties rename to opendaylight/adsal/web/osgi-brandfragment/src/main/resources/META-INF/webconsole.properties diff --git a/opendaylight/web/osgi-brandfragment/src/main/resources/res/imgs/odl/favicon.ico b/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/favicon.ico similarity index 100% rename from opendaylight/web/osgi-brandfragment/src/main/resources/res/imgs/odl/favicon.ico rename to opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/favicon.ico diff --git a/opendaylight/web/osgi-brandfragment/src/main/resources/res/imgs/odl/logo.png b/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/logo.png similarity index 100% rename from opendaylight/web/osgi-brandfragment/src/main/resources/res/imgs/odl/logo.png rename to opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/logo.png diff --git a/opendaylight/web/root/pom.xml b/opendaylight/adsal/web/root/pom.xml similarity index 98% rename from opendaylight/web/root/pom.xml rename to opendaylight/adsal/web/root/pom.xml index cd82f8b07f..faede10e2d 100644 --- a/opendaylight/web/root/pom.xml +++ b/opendaylight/adsal/web/root/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight web diff --git a/opendaylight/web/root/src/main/java/org/opendaylight/controller/web/ClusterNodeBean.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ClusterNodeBean.java similarity index 100% rename from opendaylight/web/root/src/main/java/org/opendaylight/controller/web/ClusterNodeBean.java rename to opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ClusterNodeBean.java diff --git a/opendaylight/web/root/src/main/java/org/opendaylight/controller/web/ControllerUISessionManager.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ControllerUISessionManager.java similarity index 100% rename from opendaylight/web/root/src/main/java/org/opendaylight/controller/web/ControllerUISessionManager.java rename to opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ControllerUISessionManager.java diff --git a/opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWeb.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWeb.java similarity index 100% rename from opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWeb.java rename to opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWeb.java diff --git a/opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java similarity index 100% rename from opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java rename to opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java diff --git a/opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java similarity index 100% rename from opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java rename to opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java diff --git a/opendaylight/web/root/src/main/java/org/opendaylight/controller/web/IDaylightWeb.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/IDaylightWeb.java similarity index 100% rename from opendaylight/web/root/src/main/java/org/opendaylight/controller/web/IDaylightWeb.java rename to opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/IDaylightWeb.java diff --git a/opendaylight/web/root/src/main/java/org/opendaylight/controller/web/NodeBean.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/NodeBean.java similarity index 100% rename from opendaylight/web/root/src/main/java/org/opendaylight/controller/web/NodeBean.java rename to opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/NodeBean.java diff --git a/opendaylight/web/root/src/main/java/org/opendaylight/controller/web/UserBean.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/UserBean.java similarity index 100% rename from opendaylight/web/root/src/main/java/org/opendaylight/controller/web/UserBean.java rename to opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/UserBean.java diff --git a/opendaylight/web/root/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/web/root/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/web/root/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/web/root/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/web/root/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/web/root/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/web/root/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/web/root/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/web/root/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/web/root/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/web/root/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/web/root/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/web/root/src/main/resources/WEB-INF/RootGUI-servlet.xml b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/RootGUI-servlet.xml similarity index 100% rename from opendaylight/web/root/src/main/resources/WEB-INF/RootGUI-servlet.xml rename to opendaylight/adsal/web/root/src/main/resources/WEB-INF/RootGUI-servlet.xml diff --git a/opendaylight/web/root/src/main/resources/WEB-INF/jsp/autherror.jsp b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/autherror.jsp similarity index 100% rename from opendaylight/web/root/src/main/resources/WEB-INF/jsp/autherror.jsp rename to opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/autherror.jsp diff --git a/opendaylight/web/root/src/main/resources/WEB-INF/jsp/error.jsp b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/error.jsp similarity index 100% rename from opendaylight/web/root/src/main/resources/WEB-INF/jsp/error.jsp rename to opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/error.jsp diff --git a/opendaylight/web/root/src/main/resources/WEB-INF/jsp/login.jsp b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/login.jsp similarity index 100% rename from opendaylight/web/root/src/main/resources/WEB-INF/jsp/login.jsp rename to opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/login.jsp diff --git a/opendaylight/web/root/src/main/resources/WEB-INF/jsp/main.jsp b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/main.jsp similarity index 100% rename from opendaylight/web/root/src/main/resources/WEB-INF/jsp/main.jsp rename to opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/main.jsp diff --git a/opendaylight/web/root/src/main/resources/WEB-INF/spring/servlet/security.xml b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/spring/servlet/security.xml similarity index 100% rename from opendaylight/web/root/src/main/resources/WEB-INF/spring/servlet/security.xml rename to opendaylight/adsal/web/root/src/main/resources/WEB-INF/spring/servlet/security.xml diff --git a/opendaylight/web/root/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/web/root/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/web/root/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/web/root/src/main/resources/css/bootstrap.min.css b/opendaylight/adsal/web/root/src/main/resources/css/bootstrap.min.css similarity index 100% rename from opendaylight/web/root/src/main/resources/css/bootstrap.min.css rename to opendaylight/adsal/web/root/src/main/resources/css/bootstrap.min.css diff --git a/opendaylight/web/root/src/main/resources/css/fuelux-responsive.min.css b/opendaylight/adsal/web/root/src/main/resources/css/fuelux-responsive.min.css similarity index 100% rename from opendaylight/web/root/src/main/resources/css/fuelux-responsive.min.css rename to opendaylight/adsal/web/root/src/main/resources/css/fuelux-responsive.min.css diff --git a/opendaylight/web/root/src/main/resources/css/fuelux.min.css b/opendaylight/adsal/web/root/src/main/resources/css/fuelux.min.css similarity index 100% rename from opendaylight/web/root/src/main/resources/css/fuelux.min.css rename to opendaylight/adsal/web/root/src/main/resources/css/fuelux.min.css diff --git a/opendaylight/web/root/src/main/resources/css/login.less b/opendaylight/adsal/web/root/src/main/resources/css/login.less similarity index 100% rename from opendaylight/web/root/src/main/resources/css/login.less rename to opendaylight/adsal/web/root/src/main/resources/css/login.less diff --git a/opendaylight/web/root/src/main/resources/css/one.less b/opendaylight/adsal/web/root/src/main/resources/css/one.less similarity index 100% rename from opendaylight/web/root/src/main/resources/css/one.less rename to opendaylight/adsal/web/root/src/main/resources/css/one.less diff --git a/opendaylight/web/root/src/main/resources/css/opendaylight.css b/opendaylight/adsal/web/root/src/main/resources/css/opendaylight.css similarity index 100% rename from opendaylight/web/root/src/main/resources/css/opendaylight.css rename to opendaylight/adsal/web/root/src/main/resources/css/opendaylight.css diff --git a/opendaylight/web/root/src/main/resources/img/Device_pc_3045_default_64.png b/opendaylight/adsal/web/root/src/main/resources/img/Device_pc_3045_default_64.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/Device_pc_3045_default_64.png rename to opendaylight/adsal/web/root/src/main/resources/img/Device_pc_3045_default_64.png diff --git a/opendaylight/web/root/src/main/resources/img/Device_switch_3062_unknown_64.png b/opendaylight/adsal/web/root/src/main/resources/img/Device_switch_3062_unknown_64.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/Device_switch_3062_unknown_64.png rename to opendaylight/adsal/web/root/src/main/resources/img/Device_switch_3062_unknown_64.png diff --git a/opendaylight/web/root/src/main/resources/img/Expand16T.png b/opendaylight/adsal/web/root/src/main/resources/img/Expand16T.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/Expand16T.png rename to opendaylight/adsal/web/root/src/main/resources/img/Expand16T.png diff --git a/opendaylight/web/root/src/main/resources/img/Key_0024_16.png b/opendaylight/adsal/web/root/src/main/resources/img/Key_0024_16.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/Key_0024_16.png rename to opendaylight/adsal/web/root/src/main/resources/img/Key_0024_16.png diff --git a/opendaylight/web/root/src/main/resources/img/alert_unreachable_2008_128.png b/opendaylight/adsal/web/root/src/main/resources/img/alert_unreachable_2008_128.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/alert_unreachable_2008_128.png rename to opendaylight/adsal/web/root/src/main/resources/img/alert_unreachable_2008_128.png diff --git a/opendaylight/web/root/src/main/resources/img/form.png b/opendaylight/adsal/web/root/src/main/resources/img/form.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/form.png rename to opendaylight/adsal/web/root/src/main/resources/img/form.png diff --git a/opendaylight/web/root/src/main/resources/img/logo.png b/opendaylight/adsal/web/root/src/main/resources/img/logo.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/logo.png rename to opendaylight/adsal/web/root/src/main/resources/img/logo.png diff --git a/opendaylight/web/root/src/main/resources/img/logo_16.png b/opendaylight/adsal/web/root/src/main/resources/img/logo_16.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/logo_16.png rename to opendaylight/adsal/web/root/src/main/resources/img/logo_16.png diff --git a/opendaylight/web/root/src/main/resources/img/nextpageleft.png b/opendaylight/adsal/web/root/src/main/resources/img/nextpageleft.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/nextpageleft.png rename to opendaylight/adsal/web/root/src/main/resources/img/nextpageleft.png diff --git a/opendaylight/web/root/src/main/resources/img/nextpageright.png b/opendaylight/adsal/web/root/src/main/resources/img/nextpageright.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/nextpageright.png rename to opendaylight/adsal/web/root/src/main/resources/img/nextpageright.png diff --git a/opendaylight/web/root/src/main/resources/img/open_1054_16.png b/opendaylight/adsal/web/root/src/main/resources/img/open_1054_16.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/open_1054_16.png rename to opendaylight/adsal/web/root/src/main/resources/img/open_1054_16.png diff --git a/opendaylight/web/root/src/main/resources/img/open_1054_24.png b/opendaylight/adsal/web/root/src/main/resources/img/open_1054_24.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/open_1054_24.png rename to opendaylight/adsal/web/root/src/main/resources/img/open_1054_24.png diff --git a/opendaylight/web/root/src/main/resources/img/save_as_0106_16.png b/opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_16.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/save_as_0106_16.png rename to opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_16.png diff --git a/opendaylight/web/root/src/main/resources/img/save_as_0106_24.png b/opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_24.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/save_as_0106_24.png rename to opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_24.png diff --git a/opendaylight/web/root/src/main/resources/img/search.png b/opendaylight/adsal/web/root/src/main/resources/img/search.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/search.png rename to opendaylight/adsal/web/root/src/main/resources/img/search.png diff --git a/opendaylight/web/root/src/main/resources/img/searchremove.png b/opendaylight/adsal/web/root/src/main/resources/img/searchremove.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/searchremove.png rename to opendaylight/adsal/web/root/src/main/resources/img/searchremove.png diff --git a/opendaylight/web/root/src/main/resources/img/sort_down.png b/opendaylight/adsal/web/root/src/main/resources/img/sort_down.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/sort_down.png rename to opendaylight/adsal/web/root/src/main/resources/img/sort_down.png diff --git a/opendaylight/web/root/src/main/resources/img/sort_up.png b/opendaylight/adsal/web/root/src/main/resources/img/sort_up.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/sort_up.png rename to opendaylight/adsal/web/root/src/main/resources/img/sort_up.png diff --git a/opendaylight/web/root/src/main/resources/img/topology_view_1033_128.png b/opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_128.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/topology_view_1033_128.png rename to opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_128.png diff --git a/opendaylight/web/root/src/main/resources/img/topology_view_1033_16.png b/opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_16.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/topology_view_1033_16.png rename to opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_16.png diff --git a/opendaylight/web/root/src/main/resources/img/user_0020_16.png b/opendaylight/adsal/web/root/src/main/resources/img/user_0020_16.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/user_0020_16.png rename to opendaylight/adsal/web/root/src/main/resources/img/user_0020_16.png diff --git a/opendaylight/web/root/src/main/resources/img/user_0020_24.png b/opendaylight/adsal/web/root/src/main/resources/img/user_0020_24.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/user_0020_24.png rename to opendaylight/adsal/web/root/src/main/resources/img/user_0020_24.png diff --git a/opendaylight/web/root/src/main/resources/img/user_group_0107_16.png b/opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_16.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/user_group_0107_16.png rename to opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_16.png diff --git a/opendaylight/web/root/src/main/resources/img/user_group_0107_24.png b/opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_24.png similarity index 100% rename from opendaylight/web/root/src/main/resources/img/user_group_0107_24.png rename to opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_24.png diff --git a/opendaylight/web/root/src/main/resources/js/bootstrap.min.js b/opendaylight/adsal/web/root/src/main/resources/js/bootstrap.min.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/bootstrap.min.js rename to opendaylight/adsal/web/root/src/main/resources/js/bootstrap.min.js diff --git a/opendaylight/web/root/src/main/resources/js/datasource.js b/opendaylight/adsal/web/root/src/main/resources/js/datasource.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/datasource.js rename to opendaylight/adsal/web/root/src/main/resources/js/datasource.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/COPYING b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/COPYING similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/COPYING rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/COPYING diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/all.min.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/all.min.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/all.min.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/all.min.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/checkbox.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/checkbox.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/checkbox.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/checkbox.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/combobox.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/combobox.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/combobox.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/combobox.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/datagrid.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/datagrid.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/datagrid.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/datagrid.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/loader.min.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/loader.min.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/loader.min.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/loader.min.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/pillbox.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/pillbox.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/pillbox.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/pillbox.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/radio.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/radio.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/radio.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/radio.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/search.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/search.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/search.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/search.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/select.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/select.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/select.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/select.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/spinner.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/spinner.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/spinner.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/spinner.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/tree.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/tree.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/tree.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/tree.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/util.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/util.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/util.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/util.js diff --git a/opendaylight/web/root/src/main/resources/js/fuelux/wizard.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/wizard.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/fuelux/wizard.js rename to opendaylight/adsal/web/root/src/main/resources/js/fuelux/wizard.js diff --git a/opendaylight/web/root/src/main/resources/js/jit.js b/opendaylight/adsal/web/root/src/main/resources/js/jit.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/jit.js rename to opendaylight/adsal/web/root/src/main/resources/js/jit.js diff --git a/opendaylight/web/root/src/main/resources/js/jquery-1.9.1.min.js b/opendaylight/adsal/web/root/src/main/resources/js/jquery-1.9.1.min.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/jquery-1.9.1.min.js rename to opendaylight/adsal/web/root/src/main/resources/js/jquery-1.9.1.min.js diff --git a/opendaylight/web/root/src/main/resources/js/less-1.3.3.min.js b/opendaylight/adsal/web/root/src/main/resources/js/less-1.3.3.min.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/less-1.3.3.min.js rename to opendaylight/adsal/web/root/src/main/resources/js/less-1.3.3.min.js diff --git a/opendaylight/web/root/src/main/resources/js/lib.js b/opendaylight/adsal/web/root/src/main/resources/js/lib.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/lib.js rename to opendaylight/adsal/web/root/src/main/resources/js/lib.js diff --git a/opendaylight/web/root/src/main/resources/js/open-topology.js b/opendaylight/adsal/web/root/src/main/resources/js/open-topology.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/open-topology.js rename to opendaylight/adsal/web/root/src/main/resources/js/open-topology.js diff --git a/opendaylight/web/root/src/main/resources/js/open.js b/opendaylight/adsal/web/root/src/main/resources/js/open.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/open.js rename to opendaylight/adsal/web/root/src/main/resources/js/open.js diff --git a/opendaylight/web/root/src/main/resources/js/underscore-min.js b/opendaylight/adsal/web/root/src/main/resources/js/underscore-min.js similarity index 100% rename from opendaylight/web/root/src/main/resources/js/underscore-min.js rename to opendaylight/adsal/web/root/src/main/resources/js/underscore-min.js diff --git a/opendaylight/web/topology/pom.xml b/opendaylight/adsal/web/topology/pom.xml similarity index 98% rename from opendaylight/web/topology/pom.xml rename to opendaylight/adsal/web/topology/pom.xml index 24b53db767..0afe038086 100644 --- a/opendaylight/web/topology/pom.xml +++ b/opendaylight/adsal/web/topology/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight topology.web diff --git a/opendaylight/web/topology/src/main/java/org/opendaylight/controller/topology/web/Topology.java b/opendaylight/adsal/web/topology/src/main/java/org/opendaylight/controller/topology/web/Topology.java similarity index 100% rename from opendaylight/web/topology/src/main/java/org/opendaylight/controller/topology/web/Topology.java rename to opendaylight/adsal/web/topology/src/main/java/org/opendaylight/controller/topology/web/Topology.java diff --git a/opendaylight/web/topology/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/web/topology/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/web/topology/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/web/topology/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/web/topology/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/web/topology/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/web/topology/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/web/topology/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/web/topology/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/web/topology/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/web/topology/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/web/topology/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/web/topology/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/web/topology/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/web/topology/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/web/topology/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/web/topology/src/main/resources/WEB-INF/Topology-servlet.xml b/opendaylight/adsal/web/topology/src/main/resources/WEB-INF/Topology-servlet.xml similarity index 100% rename from opendaylight/web/topology/src/main/resources/WEB-INF/Topology-servlet.xml rename to opendaylight/adsal/web/topology/src/main/resources/WEB-INF/Topology-servlet.xml diff --git a/opendaylight/web/topology/src/main/resources/WEB-INF/jsp/autherror.jsp b/opendaylight/adsal/web/topology/src/main/resources/WEB-INF/jsp/autherror.jsp similarity index 100% rename from opendaylight/web/topology/src/main/resources/WEB-INF/jsp/autherror.jsp rename to opendaylight/adsal/web/topology/src/main/resources/WEB-INF/jsp/autherror.jsp diff --git a/opendaylight/web/topology/src/main/resources/WEB-INF/jsp/error.jsp b/opendaylight/adsal/web/topology/src/main/resources/WEB-INF/jsp/error.jsp similarity index 100% rename from opendaylight/web/topology/src/main/resources/WEB-INF/jsp/error.jsp rename to opendaylight/adsal/web/topology/src/main/resources/WEB-INF/jsp/error.jsp diff --git a/opendaylight/web/topology/src/main/resources/WEB-INF/jsp/login.jsp b/opendaylight/adsal/web/topology/src/main/resources/WEB-INF/jsp/login.jsp similarity index 100% rename from opendaylight/web/topology/src/main/resources/WEB-INF/jsp/login.jsp rename to opendaylight/adsal/web/topology/src/main/resources/WEB-INF/jsp/login.jsp diff --git a/opendaylight/web/topology/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/web/topology/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/web/topology/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/web/topology/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/web/topology/src/main/resources/js/page.js b/opendaylight/adsal/web/topology/src/main/resources/js/page.js similarity index 100% rename from opendaylight/web/topology/src/main/resources/js/page.js rename to opendaylight/adsal/web/topology/src/main/resources/js/page.js diff --git a/opendaylight/web/topology/src/test/java/org/opendaylight/controller/topology/web/TopologyTest.java b/opendaylight/adsal/web/topology/src/test/java/org/opendaylight/controller/topology/web/TopologyTest.java similarity index 100% rename from opendaylight/web/topology/src/test/java/org/opendaylight/controller/topology/web/TopologyTest.java rename to opendaylight/adsal/web/topology/src/test/java/org/opendaylight/controller/topology/web/TopologyTest.java diff --git a/opendaylight/web/troubleshoot/pom.xml b/opendaylight/adsal/web/troubleshoot/pom.xml similarity index 98% rename from opendaylight/web/troubleshoot/pom.xml rename to opendaylight/adsal/web/troubleshoot/pom.xml index 14817bd186..1ef5de11c4 100644 --- a/opendaylight/web/troubleshoot/pom.xml +++ b/opendaylight/adsal/web/troubleshoot/pom.xml @@ -5,7 +5,7 @@ org.opendaylight.controller commons.opendaylight 1.5.0-SNAPSHOT - ../../commons/opendaylight + ../../../commons/opendaylight troubleshoot.web diff --git a/opendaylight/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/Troubleshoot.java b/opendaylight/adsal/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/Troubleshoot.java similarity index 100% rename from opendaylight/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/Troubleshoot.java rename to opendaylight/adsal/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/Troubleshoot.java diff --git a/opendaylight/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/TroubleshootingJsonBean.java b/opendaylight/adsal/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/TroubleshootingJsonBean.java similarity index 100% rename from opendaylight/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/TroubleshootingJsonBean.java rename to opendaylight/adsal/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/TroubleshootingJsonBean.java diff --git a/opendaylight/web/troubleshoot/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/web/troubleshoot/src/main/resources/META-INF/spring.factories similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/META-INF/spring.factories rename to opendaylight/adsal/web/troubleshoot/src/main/resources/META-INF/spring.factories diff --git a/opendaylight/web/troubleshoot/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/web/troubleshoot/src/main/resources/META-INF/spring.handlers similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/META-INF/spring.handlers rename to opendaylight/adsal/web/troubleshoot/src/main/resources/META-INF/spring.handlers diff --git a/opendaylight/web/troubleshoot/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/web/troubleshoot/src/main/resources/META-INF/spring.schemas similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/META-INF/spring.schemas rename to opendaylight/adsal/web/troubleshoot/src/main/resources/META-INF/spring.schemas diff --git a/opendaylight/web/troubleshoot/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/web/troubleshoot/src/main/resources/META-INF/spring.tooling similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/META-INF/spring.tooling rename to opendaylight/adsal/web/troubleshoot/src/main/resources/META-INF/spring.tooling diff --git a/opendaylight/web/troubleshoot/src/main/resources/WEB-INF/Troubleshoot-servlet.xml b/opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/Troubleshoot-servlet.xml similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/WEB-INF/Troubleshoot-servlet.xml rename to opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/Troubleshoot-servlet.xml diff --git a/opendaylight/web/troubleshoot/src/main/resources/WEB-INF/jsp/autherror.jsp b/opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/jsp/autherror.jsp similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/WEB-INF/jsp/autherror.jsp rename to opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/jsp/autherror.jsp diff --git a/opendaylight/web/troubleshoot/src/main/resources/WEB-INF/jsp/error.jsp b/opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/jsp/error.jsp similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/WEB-INF/jsp/error.jsp rename to opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/jsp/error.jsp diff --git a/opendaylight/web/troubleshoot/src/main/resources/WEB-INF/jsp/login.jsp b/opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/jsp/login.jsp similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/WEB-INF/jsp/login.jsp rename to opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/jsp/login.jsp diff --git a/opendaylight/web/troubleshoot/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/WEB-INF/web.xml rename to opendaylight/adsal/web/troubleshoot/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/web/troubleshoot/src/main/resources/js/page.js b/opendaylight/adsal/web/troubleshoot/src/main/resources/js/page.js similarity index 100% rename from opendaylight/web/troubleshoot/src/main/resources/js/page.js rename to opendaylight/adsal/web/troubleshoot/src/main/resources/js/page.js diff --git a/opendaylight/archetypes/opendaylight-karaf-features/src/main/resources/archetype-resources/src/main/resources/features.xml b/opendaylight/archetypes/opendaylight-karaf-features/src/main/resources/archetype-resources/src/main/resources/features.xml index 54bbfe45fc..2acf5d15e0 100644 --- a/opendaylight/archetypes/opendaylight-karaf-features/src/main/resources/archetype-resources/src/main/resources/features.xml +++ b/opendaylight/archetypes/opendaylight-karaf-features/src/main/resources/archetype-resources/src/main/resources/features.xml @@ -28,7 +28,9 @@ - ${project.groupId} - ietf-netconf-monitoring - ${netconf.version} - - - ${project.groupId} - ietf-netconf-monitoring-extension - ${netconf.version} + org.opendaylight.controller + config-artifacts + ${config.version} + pom + import - ${project.groupId} - netconf-netty-util + org.opendaylight.controller + netconf-artifacts ${netconf.version} + pom + import + org.apache.sshd sshd-core @@ -847,70 +847,6 @@ - - org.opendaylight.controller - config-api - ${config.version} - - - org.opendaylight.controller - config-manager - ${config.version} - test-jar - - - org.opendaylight.controller - config-manager - ${config.version} - - - org.opendaylight.controller - config-netconf-connector - ${netconf.version} - - - org.opendaylight.controller - config-persister-api - ${config.version} - test-jar - - - org.opendaylight.controller - config-persister-api - ${config.version} - - - org.opendaylight.controller - config-persister-directory-xml-adapter - ${config.version} - - - org.opendaylight.controller - config-persister-file-xml-adapter - ${config.version} - - - org.opendaylight.controller - config-persister-feature-adapter - ${config.version} - - - org.opendaylight.controller - config-persister-impl - ${netconf.version} - - - - org.opendaylight.controller - config-util - ${config.version} - - - org.opendaylight.controller - config-util - ${config.version} - test-jar - org.opendaylight.controller configuration @@ -1053,11 +989,6 @@ liblldp ${sal.version} - - org.opendaylight.controller - logback-config - ${config.version} - org.opendaylight.controller @@ -1070,114 +1001,6 @@ ${dummy-console.version} - - - org.opendaylight.controller - netconf-api - ${netconf.version} - - - org.opendaylight.controller - netconf-client - ${netconf.version} - - - org.opendaylight.controller - netconf-client - ${netconf.version} - test-jar - - - - - org.opendaylight.controller - netconf-config-dispatcher - ${netconf.version} - - - org.opendaylight.controller - netconf-impl - ${netconf.version} - - - org.opendaylight.controller - netconf-impl - ${netconf.version} - test-jar - - - org.opendaylight.controller - netconf-mapping-api - ${netconf.version} - - - org.opendaylight.controller - netconf-monitoring - ${netconf.version} - - - org.opendaylight.controller - netconf-netty-util - ${netconf.version} - test-jar - - - org.opendaylight.controller - netconf-auth - ${netconf.version} - - - org.opendaylight.controller - netconf-usermanager - ${netconf.version} - - - org.opendaylight.controller - netconf-ssh - ${netconf.version} - - - org.opendaylight.controller - netconf-ssh - ${netconf.version} - test-jar - - - org.opendaylight.controller - netconf-tcp - ${netconf.version} - - - org.opendaylight.controller - netconf-util - ${netconf.version} - - - org.opendaylight.controller - netconf-util - ${netconf.version} - test-jar - - - org.opendaylight.controller - netty-config-api - ${config.version} - - - org.opendaylight.controller - netty-event-executor-config - ${config.version} - - - org.opendaylight.controller - netty-threadgroup-config - ${config.version} - - - org.opendaylight.controller - netty-timer-config - ${config.version} - org.opendaylight.controller networkconfig.bridgedomain.northbound @@ -1340,26 +1163,11 @@ sal-rest-connector-config ${mdsal.version} - - org.opendaylight.controller - config-netty-config - ${config.version} - org.opendaylight.controller md-sal-config ${mdsal.version} - - org.opendaylight.controller - netconf-config - ${netconf.version} - - - org.opendaylight.controller - netconf-connector-config - ${netconf.version} - org.opendaylight.controller sal-rest-docgen @@ -1457,16 +1265,6 @@ ${karaf.security.version} - - org.opendaylight.controller - shutdown-api - ${config.version} - - - org.opendaylight.controller - shutdown-impl - ${config.version} - org.opendaylight.controller statistics.northbound @@ -1503,17 +1301,6 @@ ${switchmanager.northbound.version} - - - org.opendaylight.controller - threadpool-config-api - ${config.version} - - - org.opendaylight.controller - threadpool-config-impl - ${config.version} - org.opendaylight.controller topology.northbound @@ -1561,22 +1348,6 @@ web ${web.version} - - org.opendaylight.controller - yang-jmx-generator - ${config.version} - - - org.opendaylight.controller - yang-jmx-generator - ${config.version} - test-jar - - - org.opendaylight.controller - yang-test - ${config.version} - org.opendaylight.controller.md forwardingrules-manager @@ -1670,14 +1441,6 @@ xml runtime - - org.opendaylight.controller - features-config-netty - ${config.version} - features - xml - runtime - org.opendaylight.controller features-flow @@ -1691,11 +1454,7 @@ com.sun.jersey.jersey-servlet ${jersey-servlet.version} - - org.opendaylight.controller.thirdparty - ganymed - ${ganymed.version} - + org.opendaylight.controller.thirdparty @@ -1712,174 +1471,16 @@ org.openflow.openflowj 1.0.2 - - org.opendaylight.yangtools - binding-generator-impl - ${yangtools.version} - - - org.opendaylight.yangtools - binding-data-codec - ${yangtools.version} - - - org.opendaylight.yangtools - binding-generator-spi - ${yangtools.version} - - - org.opendaylight.yangtools - binding-generator-util - ${yangtools.version} - - - org.opendaylight.yangtools - binding-type-provider - ${yangtools.version} - - - org.opendaylight.yangtools - concepts - ${yangtools.version} - - - org.opendaylight.yangtools - object-cache-api - ${yangtools.version} - - - org.opendaylight.yangtools - object-cache-guava - ${yangtools.version} - - - org.opendaylight.yangtools - restconf-client-api - ${yangtools.version} - - - org.opendaylight.yangtools - restconf-client-impl - ${yangtools.version} - - - org.opendaylight.yangtools - util - ${yangtools.version} - - - org.opendaylight.yangtools - yang-data-composite-node - ${yangtools.version} - - - org.opendaylight.yangtools - yang-data-codec-gson - ${yangtools.version} - - - - org.opendaylight.yangtools - yang-binding - ${yangtools.version} - + org.opendaylight.yangtools - yang-common + yangtools-artifacts ${yangtools.version} + pom + import - - org.opendaylight.yangtools - yang-data-api - ${yangtools.version} - - - org.opendaylight.yangtools - yang-data-impl - ${yangtools.version} - - - org.opendaylight.yangtools - yang-data-util - ${yangtools.version} - - - org.opendaylight.yangtools - yang-maven-plugin-spi - ${yangtools.version} - - - org.opendaylight.yangtools - yang-model-api - ${yangtools.version} - - - org.opendaylight.yangtools - yang-model-util - ${yangtools.version} - - - org.opendaylight.yangtools - yang-parser-api - ${yangtools.version} - - - org.opendaylight.yangtools - yang-parser-impl - ${yangtools.version} - - - - org.opendaylight.yangtools.model - ietf-inet-types - ${ietf-inet-types.version} - - - org.opendaylight.yangtools.model - ietf-restconf - ${ietf-restconf.version} - - - org.opendaylight.yangtools.model - ietf-topology - ${ietf-topology.version} - - - org.opendaylight.yangtools.model - ietf-topology-l3-unicast-igp - ${ietf-topology.version} - - - org.opendaylight.yangtools.model - ietf-yang-types - ${ietf-yang-types.version} - - - org.opendaylight.yangtools.model - ietf-yang-types-20130715 - 2013.07.15.7-SNAPSHOT - - - org.opendaylight.yangtools.model - opendaylight-l2-types - ${opendaylight-l2-types.version} - - - org.opendaylight.yangtools.model - yang-ext - ${yang-ext.version} - - - org.opendaylight.yangtools.thirdparty - antlr4-runtime-osgi-nohead - 4.0 - - - org.opendaylight.yangtools.thirdparty - xtend-lib-osgi - ${xtend.version} - + org.openexi nagasena @@ -1950,20 +1551,6 @@ ${mdsal.version} test - - org.opendaylight.yangtools - mockito-configuration - ${yangtools.version} - test - - - org.opendaylight.controller - features-config - ${config.version} - features - xml - runtime - org.opendaylight.controller features-protocol-framework @@ -1972,30 +1559,6 @@ xml runtime - - org.opendaylight.controller - features-netconf - ${netconf.version} - features - xml - runtime - - - org.opendaylight.controller - features-config-persister - ${config.version} - features - xml - runtime - - - org.opendaylight.controller - config-netty-features - ${config.version} - features - xml - runtime - org.opendaylight.controller features-base @@ -2402,7 +1965,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - ${checkstyle.version} true controller/checkstyle.xml @@ -2488,7 +2050,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${surefire.version} ${testvm.argLine} ${jacoco.agent.ut.arg} diff --git a/opendaylight/commons/protocol-framework/src/test/java/org/opendaylight/protocol/framework/ServerTest.java b/opendaylight/commons/protocol-framework/src/test/java/org/opendaylight/protocol/framework/ServerTest.java index 63026e384c..fc38888de3 100644 --- a/opendaylight/commons/protocol-framework/src/test/java/org/opendaylight/protocol/framework/ServerTest.java +++ b/opendaylight/commons/protocol-framework/src/test/java/org/opendaylight/protocol/framework/ServerTest.java @@ -250,52 +250,6 @@ public class ServerTest { assertFalse(session.isSuccess()); } - @Test - public void testNegotiationFailedNoReconnect() throws Exception { - final Promise p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); - - this.dispatcher = getServerDispatcher(p); - - this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory() { - @Override - public SimpleSessionListener getSessionListener() { - return new SimpleSessionListener(); - } - }); - - this.server.get(); - - this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory() { - @Override - public SessionNegotiator getSessionNegotiator(final SessionListenerFactory factory, - final Channel channel, final Promise promise) { - - return new SimpleSessionNegotiator(promise, channel) { - @Override - protected void startNegotiation() throws Exception { - negotiationFailed(new IllegalStateException("Negotiation failed")); - } - }; - } - }, new DefaultPromise(GlobalEventExecutor.INSTANCE), eventLoopGroup); - - final ReconnectStrategyFactory reconnectStrategyFactory = mock(ReconnectStrategyFactory.class); - final ReconnectStrategy reconnectStrategy = getMockedReconnectStrategy(); - doReturn(reconnectStrategy).when(reconnectStrategyFactory).createReconnectStrategy(); - - this.clientDispatcher.createReconnectingClient(this.serverAddress, - reconnectStrategyFactory, new SessionListenerFactory() { - @Override - public SimpleSessionListener getSessionListener() { - return new SimpleSessionListener(); - } - }); - - - // Only one strategy should be created for initial connect, no more = no reconnects - verify(reconnectStrategyFactory, times(1)).createReconnectStrategy(); - } - private SimpleDispatcher getClientDispatcher() { return new SimpleDispatcher(new SessionNegotiatorFactory() { @Override diff --git a/opendaylight/config/config-api/src/main/yang/config.yang b/opendaylight/config/config-api/src/main/yang/config.yang index 5d6c11fbee..e46d327ece 100644 --- a/opendaylight/config/config-api/src/main/yang/config.yang +++ b/opendaylight/config/config-api/src/main/yang/config.yang @@ -140,7 +140,7 @@ module config { "Top level container encapsulating configuration of all modules."; list module { - key "name"; + key "type name"; leaf name { description "Unique module instance name"; type string; diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/IdentityAttributeRefTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/IdentityAttributeRefTest.java index 6e8ece343f..91e1f14849 100644 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/IdentityAttributeRefTest.java +++ b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/IdentityAttributeRefTest.java @@ -1,17 +1,13 @@ package org.opendaylight.controller.config.api; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import org.junit.Assert; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface; import org.opendaylight.yangtools.yang.binding.BaseIdentity; -import javax.management.*; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - public class IdentityAttributeRefTest { IdentityAttributeRef attr = new IdentityAttributeRef("attr"); diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeValidationExceptionTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeValidationExceptionTest.java index f6e7dfb505..9ff7405257 100644 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeValidationExceptionTest.java +++ b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeValidationExceptionTest.java @@ -1,23 +1,18 @@ package org.opendaylight.controller.config.api; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import com.google.common.collect.Lists; import java.nio.file.AccessDeniedException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - -import com.google.common.collect.Lists; import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import javax.management.Query; - -import static org.junit.Assert.*; - public class JmxAttributeValidationExceptionTest { - private JmxAttribute jmxAttribute = new JmxAttribute("attr1"); + private final JmxAttribute jmxAttribute = new JmxAttribute("attr1"); @Test public void testJmxAttributeValidationExceptionElement() throws Exception { @@ -28,7 +23,7 @@ public class JmxAttributeValidationExceptionTest { @Test public void testJmxAttributeValidationExceptionList() throws Exception { - List attributeNames = new ArrayList(); + List attributeNames = new ArrayList<>(); attributeNames.add(new JmxAttribute("att1")); attributeNames.add(new JmxAttribute("att2")); attributeNames.add(new JmxAttribute("att3")); @@ -38,7 +33,7 @@ public class JmxAttributeValidationExceptionTest { @Test public void testJmxAttributeValidationExceptionList2() throws Exception { - List attributeNames = new ArrayList(); + List attributeNames = new ArrayList<>(); attributeNames.add(new JmxAttribute("att1")); attributeNames.add(new JmxAttribute("att2")); attributeNames.add(new JmxAttribute("att3")); @@ -84,7 +79,7 @@ public class JmxAttributeValidationExceptionTest { JmxAttributeValidationException.checkCondition(false, "message", jmxAttribute); } - private void assertJmxEx(JmxAttributeValidationException e, String message, JmxAttribute... attrNames) { + private void assertJmxEx(final JmxAttributeValidationException e, final String message, final JmxAttribute... attrNames) { assertEquals(message, e.getMessage()); assertEquals(Lists.newArrayList(attrNames), e.getAttributeNames()); } diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ModuleIdentifierTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ModuleIdentifierTest.java index c0e584a098..2771b407f4 100644 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ModuleIdentifierTest.java +++ b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ModuleIdentifierTest.java @@ -1,11 +1,8 @@ package org.opendaylight.controller.config.api; -import junit.framework.Assert; -import org.junit.Test; - import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; +import org.junit.Test; public class ModuleIdentifierTest { String fact = new String("factory"); diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ValidationExceptionTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ValidationExceptionTest.java index 30712c966d..8b4f2fe258 100644 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ValidationExceptionTest.java +++ b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ValidationExceptionTest.java @@ -1,23 +1,20 @@ package org.opendaylight.controller.config.api; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertTrue; -import static junit.framework.Assert.fail; -import static org.junit.Assert.assertNotEquals; +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -import static org.junit.matchers.JUnitMatchers.containsString; - +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.common.collect.Lists; import java.util.Map; - import org.junit.Assert; import org.junit.Test; public class ValidationExceptionTest { - private String instance = "instance"; + private final String instance = "instance"; private final ModuleIdentifier mi = new ModuleIdentifier("module", instance); - private String instance2 = "instance2"; + private final String instance2 = "instance2"; private final ModuleIdentifier mi2 = new ModuleIdentifier("module", instance2); private final String message = "ex message"; private final Exception e = new IllegalStateException(message); diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/CommitStatusTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/CommitStatusTest.java index 36ebc9de93..cb8271a581 100644 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/CommitStatusTest.java +++ b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/CommitStatusTest.java @@ -1,17 +1,16 @@ package org.opendaylight.controller.config.api.jmx; +import java.util.ArrayList; +import java.util.List; +import javax.management.ObjectName; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import javax.management.ObjectName; -import java.util.ArrayList; -import java.util.List; - public class CommitStatusTest { - List newInst = new ArrayList(); - List reusedInst = new ArrayList(); - List recreatedInst = new ArrayList(); + List newInst = new ArrayList<>(); + List reusedInst = new ArrayList<>(); + List recreatedInst = new ArrayList<>(); @Before public void setUp() throws Exception { @@ -43,9 +42,9 @@ public class CommitStatusTest { @Test public void testNotEqual() throws Exception { - List newInst2 = new ArrayList(); - List reusedInst2 = new ArrayList(); - List recreatedInst2 = new ArrayList(); + List newInst2 = new ArrayList<>(); + List reusedInst2 = new ArrayList<>(); + List recreatedInst2 = new ArrayList<>(); newInst2.add(new ObjectName("first: key1 = value1")); reusedInst2.add(new ObjectName("second: key = val")); diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtilTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtilTest.java index 02c1c4b981..e69ff921cc 100644 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtilTest.java +++ b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtilTest.java @@ -7,18 +7,15 @@ */ package org.opendaylight.controller.config.api.jmx; -import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - +import static org.junit.Assert.fail; import com.google.common.base.Throwables; import com.google.common.collect.Maps; - import java.util.HashMap; import java.util.Map; import javax.management.ObjectName; -import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.config.api.ModuleIdentifier; @@ -84,7 +81,7 @@ public class ObjectNameUtilTest { assertPattern(on, pattern); } - private void assertPattern(ObjectName test, ObjectName pattern) { + private void assertPattern(final ObjectName test, final ObjectName pattern) { assertTrue(pattern.isPattern()); assertTrue(pattern.apply(test)); } @@ -150,11 +147,11 @@ public class ObjectNameUtilTest { }, IllegalArgumentException.class); } - private void assertFailure(Runnable test, Class ex) { + private void assertFailure(final Runnable test, final Class ex) { try { test.run(); } catch(Exception e) { - Assert.assertTrue("Failed with wrong exception: " + Throwables.getStackTraceAsString(e), + assertTrue("Failed with wrong exception: " + Throwables.getStackTraceAsString(e), e.getClass().isAssignableFrom(ex)); return; } diff --git a/opendaylight/config/config-artifacts/pom.xml b/opendaylight/config/config-artifacts/pom.xml new file mode 100644 index 0000000000..430d6b41bc --- /dev/null +++ b/opendaylight/config/config-artifacts/pom.xml @@ -0,0 +1,224 @@ + + + + + + 4.0.0 + org.opendaylight.controller + config-artifacts + 0.3.0-SNAPSHOT + pom + + + + + ${project.groupId} + config-api + ${project.version} + + + ${project.groupId} + config-manager + ${project.version} + + + ${project.groupId} + config-manager + ${project.version} + test-jar + test + + + ${project.groupId} + config-module-archetype + ${project.version} + + + ${project.groupId} + config-netty-config + ${project.version} + + + ${project.groupId} + config-persister-api + ${project.version} + + + ${project.groupId} + config-persister-api + ${project.version} + test-jar + test + + + ${project.groupId} + config-persister-directory-adapter + ${project.version} + + + ${project.groupId} + config-persister-directory-autodetect-adapter + ${project.version} + + + ${project.groupId} + config-persister-directory-xml-adapter + ${project.version} + + + ${project.groupId} + config-persister-feature-adapter + ${project.version} + + + ${project.groupId} + config-persister-file-adapter + ${project.version} + + + ${project.groupId} + config-persister-file-xml-adapter + ${project.version} + + + ${project.groupId} + config-plugin-parent + ${project.version} + + + ${project.groupId} + config-util + ${project.version} + + + ${project.groupId} + config-util + ${project.version} + test-jar + test + + + ${project.groupId} + logback-config + ${project.version} + + + ${project.groupId} + logback-config-loader + ${project.version} + + + ${project.groupId} + netty-config-api + ${project.version} + + + ${project.groupId} + netty-event-executor-config + ${project.version} + + + ${project.groupId} + netty-threadgroup-config + ${project.version} + + + ${project.groupId} + netty-timer-config + ${project.version} + + + ${project.groupId} + shutdown-api + ${project.version} + + + ${project.groupId} + shutdown-impl + ${project.version} + + + ${project.groupId} + threadpool-config-api + ${project.version} + + + ${project.groupId} + threadpool-config-impl + ${project.version} + + + ${project.groupId} + yang-jmx-generator + ${project.version} + + + ${project.groupId} + yang-jmx-generator + ${project.version} + test-jar + test + + + ${project.groupId} + yang-jmx-generator-plugin + ${project.version} + + + ${project.groupId} + yang-store-api + ${project.version} + + + ${project.groupId} + yang-store-impl + ${project.version} + + + ${project.groupId} + yang-test + ${project.version} + + + + ${project.groupId} + features-config + ${project.version} + features + xml + runtime + + + ${project.groupId} + features-config-netty + ${project.version} + features + xml + runtime + + + ${project.groupId} + features-config-persister + ${project.version} + features + xml + runtime + + + ${project.groupId} + config-netty-features + ${project.version} + features + xml + runtime + + + + + diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java index 0f881e95ad..0dff41402e 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java @@ -8,7 +8,8 @@ package org.opendaylight.controller.config.manager.impl; import static com.google.common.base.Preconditions.checkNotNull; - +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -71,22 +72,22 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public Set lookupConfigBeans(String moduleName) { + public Set lookupConfigBeans(final String moduleName) { throw new UnsupportedOperationException(); } @Override - public Set lookupConfigBeans(String moduleName, String instanceName) { + public Set lookupConfigBeans(final String moduleName, final String instanceName) { throw new UnsupportedOperationException(); } @Override - public ObjectName lookupConfigBean(String moduleName, String instanceName) throws InstanceNotFoundException { + public ObjectName lookupConfigBean(final String moduleName, final String instanceName) throws InstanceNotFoundException { throw new UnsupportedOperationException(); } @Override - public void checkConfigBeanExists(ObjectName objectName) throws InstanceNotFoundException { + public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException { throw new InstanceNotFoundException("Cannot find " + objectName + " - Tried to use mocking registry"); } @@ -110,7 +111,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public ServiceReferenceJMXRegistration registerMBean(ServiceReferenceMXBeanImpl object, ObjectName on) throws InstanceAlreadyExistsException { + public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object, final ObjectName on) throws InstanceAlreadyExistsException { throw new UnsupportedOperationException(); } @@ -128,9 +129,9 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe /** * Static constructor for transaction controller. Take current state as seen by config registry, allow writing new data. */ - public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry(ServiceReferenceReadableRegistry oldReadableRegistry, - ConfigTransactionLookupRegistry txLookupRegistry, - Map> currentlyRegisteredFactories) { + public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry(final ServiceReferenceReadableRegistry oldReadableRegistry, + final ConfigTransactionLookupRegistry txLookupRegistry, + final Map> currentlyRegisteredFactories) { if (txLookupRegistry == null) { throw new IllegalArgumentException("txLookupRegistry is null"); @@ -148,8 +149,8 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe /** * Copy back state to config registry after commit. */ - public static CloseableServiceReferenceReadableRegistry createSRReadableRegistry(ServiceReferenceWritableRegistry oldWritableRegistry, - LookupRegistry lookupRegistry, BaseJMXRegistrator baseJMXRegistrator) { + public static CloseableServiceReferenceReadableRegistry createSRReadableRegistry(final ServiceReferenceWritableRegistry oldWritableRegistry, + final LookupRegistry lookupRegistry, final BaseJMXRegistrator baseJMXRegistrator) { ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldWritableRegistry; // even if factories do change, nothing in the mapping can change between transactions @@ -163,7 +164,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe /** * Fill refNames and mBeans maps from old instance */ - private static void copy(ServiceReferenceRegistryImpl old, ServiceReferenceRegistryImpl newRegistry, String nullableDstTransactionName) { + private static void copy(final ServiceReferenceRegistryImpl old, final ServiceReferenceRegistryImpl newRegistry, final String nullableDstTransactionName) { for (Entry> refNameEntry : old.mBeans.entrySet()) { ObjectName currentImplementation; ObjectName currentImplementationSrc = refNameEntry.getValue().getKey().getCurrentImplementation(); @@ -182,7 +183,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } } - private static Map extractFactoriesMap(Map> currentlyRegisteredFactories) { + private static Map extractFactoriesMap(final Map> currentlyRegisteredFactories) { Map result = new HashMap<>(); for (Entry> entry : currentlyRegisteredFactories.entrySet()) { result.put(entry.getKey(), entry.getValue().getKey()); @@ -190,9 +191,9 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe return result; } - private ServiceReferenceRegistryImpl(Map factories, LookupRegistry lookupRegistry, - ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory, - boolean writable) { + private ServiceReferenceRegistryImpl(final Map factories, final LookupRegistry lookupRegistry, + final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory, + final boolean writable) { this.factories = factories; this.writable = writable; this.lookupRegistry = lookupRegistry; @@ -213,10 +214,10 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe Set qNames = InterfacesHelper.getQNames(siAnnotations); allAnnotations.addAll(siAnnotations); allQNameSet.addAll(qNames); - modifiableFactoryNamesToQNames.put(entry.getKey(), Collections.unmodifiableSet(qNames)); + modifiableFactoryNamesToQNames.put(entry.getKey(), qNames); } - this.factoryNamesToQNames = Collections.unmodifiableMap(modifiableFactoryNamesToQNames); - this.allQNames = Collections.unmodifiableSet(allQNameSet); + this.factoryNamesToQNames = ImmutableMap.copyOf(modifiableFactoryNamesToQNames); + this.allQNames = ImmutableSet.copyOf(allQNameSet); // fill namespacesToAnnotations Map> modifiableNamespacesToAnnotations = new HashMap<>(); @@ -235,13 +236,13 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe ofNamespace.put(sia.localName(), sia); modifiableServiceQNamesToAnnotations.put(sia.value(), sia); } - this.namespacesToAnnotations = Collections.unmodifiableMap(modifiableNamespacesToAnnotations); - this.serviceQNamesToAnnotations = Collections.unmodifiableMap(modifiableServiceQNamesToAnnotations); + this.namespacesToAnnotations = ImmutableMap.copyOf(modifiableNamespacesToAnnotations); + this.serviceQNamesToAnnotations = ImmutableMap.copyOf(modifiableServiceQNamesToAnnotations); LOGGER.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames); } @Override - public Map findServiceInterfaces(ModuleIdentifier moduleIdentifier) { + public Map findServiceInterfaces(final ModuleIdentifier moduleIdentifier) { Map result = modulesToServiceRef.get(moduleIdentifier); if (result == null) { return Collections.emptyMap(); @@ -250,7 +251,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized Set lookupServiceInterfaceNames(ObjectName objectName) throws InstanceNotFoundException { + public synchronized Set lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException { lookupRegistry.checkConfigBeanExists(objectName); String factoryName = ObjectNameUtil.getFactoryName(objectName); @@ -264,7 +265,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized String getServiceInterfaceName(String namespace, String localName) { + public synchronized String getServiceInterfaceName(final String namespace, final String localName) { Map ofNamespace = namespacesToAnnotations.get(namespace); if (ofNamespace == null) { LOGGER.error("Cannot find namespace {} in {}", namespace, namespacesToAnnotations); @@ -295,7 +296,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe return result; } - private ObjectName getObjectName(ModuleIdentifier moduleIdentifier) { + private ObjectName getObjectName(final ModuleIdentifier moduleIdentifier) { ObjectName on; try { on = lookupRegistry.lookupConfigBean(moduleIdentifier.getFactoryName(), moduleIdentifier.getInstanceName()); @@ -307,7 +308,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(String serviceInterfaceQName, String refName) { + public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) { ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName); ModuleIdentifier moduleIdentifier = refNames.get(serviceReference); if (moduleIdentifier == null) { @@ -318,7 +319,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized Map lookupServiceReferencesByServiceInterfaceName(String serviceInterfaceQName) { + public synchronized Map lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { Map> serviceMapping = getServiceMapping(); Map innerMap = serviceMapping.get(serviceInterfaceQName); if (innerMap == null) { @@ -329,7 +330,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized ObjectName getServiceReference(String serviceInterfaceQName, String refName) throws InstanceNotFoundException { + public synchronized ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException { ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName); if (mBeans.containsKey(serviceReference) == false) { throw new InstanceNotFoundException("Cannot find " + serviceReference); @@ -338,7 +339,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized void checkServiceReferenceExists(ObjectName objectName) throws InstanceNotFoundException { + public synchronized void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException { String actualTransactionName = ObjectNameUtil.getTransactionName(objectName); String expectedTransactionName = serviceReferenceRegistrator.getNullableTransactionName(); if (writable & actualTransactionName == null || (writable && actualTransactionName.equals(expectedTransactionName) == false)) { @@ -362,19 +363,19 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized ObjectName saveServiceReference(String serviceInterfaceName, String refName, ObjectName moduleON) throws InstanceNotFoundException { + public synchronized ObjectName saveServiceReference(final String serviceInterfaceName, final String refName, final ObjectName moduleON) throws InstanceNotFoundException { assertWritable(); ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName); return saveServiceReference(serviceReference, moduleON); } - private synchronized ObjectName saveServiceReference(ServiceReference serviceReference, ObjectName moduleON) + private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference, final ObjectName moduleON) throws InstanceNotFoundException{ return saveServiceReference(serviceReference, moduleON, false); } - private synchronized ObjectName saveServiceReference(ServiceReference serviceReference, ObjectName moduleON, - boolean skipChecks) throws InstanceNotFoundException { + private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference, final ObjectName moduleON, + final boolean skipChecks) throws InstanceNotFoundException { // make sure it is found if (skipChecks == false) { @@ -443,13 +444,13 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public ServiceReferenceJMXRegistration setValue(ServiceReferenceJMXRegistration value) { + public ServiceReferenceJMXRegistration setValue(final ServiceReferenceJMXRegistration value) { throw new UnsupportedOperationException(); } }; } - private ObjectName getServiceON(ServiceReference serviceReference) { + private ObjectName getServiceON(final ServiceReference serviceReference) { if (writable) { return ObjectNameUtil.createTransactionServiceON(serviceReferenceRegistrator.getNullableTransactionName(), serviceReference.getServiceInterfaceQName(), serviceReference.getRefName()); @@ -459,12 +460,12 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized void removeServiceReference(String serviceInterfaceName, String refName) throws InstanceNotFoundException{ + public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName) throws InstanceNotFoundException{ ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName); removeServiceReference(serviceReference); } - private synchronized void removeServiceReference(ServiceReference serviceReference) throws InstanceNotFoundException { + private synchronized void removeServiceReference(final ServiceReference serviceReference) throws InstanceNotFoundException { LOGGER.debug("Removing service reference {} from {}", serviceReference, this); assertWritable(); // is the qName known? @@ -496,7 +497,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } @Override - public synchronized boolean removeServiceReferences(ObjectName moduleObjectName) throws InstanceNotFoundException { + public synchronized boolean removeServiceReferences(final ObjectName moduleObjectName) throws InstanceNotFoundException { lookupRegistry.checkConfigBeanExists(moduleObjectName); String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName); // check that service interface name exist @@ -505,7 +506,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe } - private boolean removeServiceReferences(ObjectName moduleObjectName, Set qNames) throws InstanceNotFoundException { + private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set qNames) throws InstanceNotFoundException { ObjectNameUtil.checkType(moduleObjectName, ObjectNameUtil.TYPE_MODULE); assertWritable(); Set serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, qNames); @@ -515,7 +516,7 @@ public class ServiceReferenceRegistryImpl implements CloseableServiceReferenceRe return serviceReferencesLinkingTo.isEmpty() == false; } - private Set findServiceReferencesLinkingTo(ObjectName moduleObjectName, Set serviceInterfaceQNames) { + private Set findServiceReferencesLinkingTo(final ObjectName moduleObjectName, final Set serviceInterfaceQNames) { String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName); if (serviceInterfaceQNames == null) { LOGGER.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName, factoryNamesToQNames, moduleObjectName); diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java index 4d94c6d265..f4d732c65c 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java @@ -7,19 +7,19 @@ */ package org.opendaylight.controller.config.manager.impl.util; -import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface; -import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation; -import org.opendaylight.controller.config.spi.Module; -import org.opendaylight.controller.config.spi.ModuleFactory; - -import javax.management.JMX; +import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; +import javax.management.JMX; +import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface; +import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation; +import org.opendaylight.controller.config.spi.Module; +import org.opendaylight.controller.config.spi.ModuleFactory; -public class InterfacesHelper { +public final class InterfacesHelper { private InterfacesHelper() { } @@ -40,7 +40,7 @@ public class InterfacesHelper { } - private static Set> getAllSuperInterfaces(Set> ifcs) { + private static Set> getAllSuperInterfaces(final Set> ifcs) { Set> interfaces = new HashSet<>(ifcs); // create copy to modify // each interface can extend other interfaces Set> result = new HashSet<>(); @@ -61,7 +61,7 @@ public class InterfacesHelper { * Get interfaces that this class is derived from that are JMX interfaces. */ public static Set> getMXInterfaces( - Class configBeanClass) { + final Class configBeanClass) { Set> allInterfaces = getAllInterfaces(configBeanClass); Set> result = new HashSet<>(); for (Class clazz : allInterfaces) { @@ -78,7 +78,7 @@ public class InterfacesHelper { * annotation. */ public static Set> getServiceInterfaces( - Class configBeanClass) { + final Class configBeanClass) { Set> allInterfaces = getAllInterfaces(configBeanClass); Set> result = new HashSet<>(); for (Class clazz : allInterfaces) { @@ -93,7 +93,7 @@ public class InterfacesHelper { return result; } - public static Set> getAllAbstractServiceClasses(Class configBeanClass) { + public static Set> getAllAbstractServiceClasses(final Class configBeanClass) { Set> foundGeneratedSIClasses = new HashSet<>(); for (Class clazz : getAllInterfaces(configBeanClass)) { @@ -111,7 +111,7 @@ public class InterfacesHelper { * {@link org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation#osgiRegistrationType()} */ public static Set> getOsgiRegistrationTypes( - Class configBeanClass) { + final Class configBeanClass) { Set> serviceInterfaces = getServiceInterfaces(configBeanClass); Set> result = new HashSet<>(); for (Class clazz : serviceInterfaces) { @@ -122,20 +122,20 @@ public class InterfacesHelper { return result; } - public static Set getQNames(Set siAnnotations) { + public static Set getQNames(final Set siAnnotations) { Set qNames = new HashSet<>(); for (ServiceInterfaceAnnotation sia: siAnnotations) { qNames.add(sia.value()); } - return Collections.unmodifiableSet(qNames); + return ImmutableSet.copyOf(qNames); } - public static Set getServiceInterfaceAnnotations(ModuleFactory factory) { + public static Set getServiceInterfaceAnnotations(final ModuleFactory factory) { Set> implementedServiceIntefaces = Collections.unmodifiableSet(factory.getImplementedServiceIntefaces()); return getServiceInterfaceAnnotations(implementedServiceIntefaces); } - private static Set getServiceInterfaceAnnotations(Set> implementedServiceIntefaces) { + private static Set getServiceInterfaceAnnotations(final Set> implementedServiceIntefaces) { Set> inspected = getAllAbstractServiceInterfaceClasses(implementedServiceIntefaces); Set result = new HashSet<>(); // SIs can form hierarchies, inspect superclass until it does not extend AbstractSI @@ -149,9 +149,9 @@ public class InterfacesHelper { } static Set> getAllAbstractServiceInterfaceClasses( - Set> directlyImplementedAbstractSIs) { + final Set> directlyImplementedAbstractSIs) { - Set> allInterfaces = getAllSuperInterfaces((Set) directlyImplementedAbstractSIs); + Set> allInterfaces = getAllSuperInterfaces(directlyImplementedAbstractSIs); Set> result = new HashSet<>(); for(Class ifc: allInterfaces){ if (AbstractServiceInterface.class.isAssignableFrom(ifc) && diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java index f839452dca..4f792e72b1 100644 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java +++ b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java @@ -9,7 +9,6 @@ package org.opendaylight.controller.config.manager.impl.util; import static com.google.common.base.Preconditions.checkNotNull; - import java.util.ArrayList; import java.util.List; import java.util.ListIterator; @@ -27,7 +26,7 @@ public class OsgiRegistrationUtil { } @SafeVarargs - public static AutoCloseable registerService(BundleContext bundleContext, T service, Class ... interfaces) { + public static AutoCloseable registerService(final BundleContext bundleContext, final T service, final Class ... interfaces) { checkNotNull(service); checkNotNull(interfaces); List autoCloseableList = new ArrayList<>(); @@ -48,7 +47,7 @@ public class OsgiRegistrationUtil { }; } - public static AutoCloseable wrap(final BundleTracker bundleTracker) { + public static AutoCloseable wrap(final BundleTracker bundleTracker) { checkNotNull(bundleTracker); return new AutoCloseable() { @Override diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java index 63a37de0c3..c4a4192cba 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java @@ -213,7 +213,7 @@ public abstract class AbstractConfigTest extends Object serviceTypeRaw = args[0]; Object serviceInstance = args[1]; - Dictionary props = (Dictionary) args[2]; + Dictionary props = (Dictionary) args[2]; if (serviceTypeRaw instanceof Class) { Class serviceType = (Class) serviceTypeRaw; diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java index 48d7de0e82..83ee87ce0e 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java @@ -100,10 +100,10 @@ public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanSe tested.put(moduleIdentifier, mockedModule(), - moduleFactory, - maybeOldInternalInfo, - transactionModuleJMXRegistration, - isDefaultBean, mock(BundleContext.class)); + moduleFactory, + maybeOldInternalInfo, + transactionModuleJMXRegistration, + isDefaultBean, mock(BundleContext.class)); } private static Module mockedModule() { diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java index 471c98a676..8ceee0caf5 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java @@ -1,14 +1,13 @@ package org.opendaylight.controller.config.manager.impl.osgi; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.assertSame; -import static junit.framework.Assert.fail; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - import java.util.Collections; import javax.management.ObjectName; import org.junit.Before; diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java index dc3deddddc..44e6e9ab77 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java @@ -1,13 +1,12 @@ package org.opendaylight.controller.config.manager.impl.osgi; -import static junit.framework.Assert.fail; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.junit.matchers.JUnitMatchers.containsString; +import static org.junit.Assert.fail; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; - import com.google.common.collect.Lists; import java.util.Map; import org.junit.Before; @@ -24,8 +23,8 @@ public class BundleContextBackedModuleFactoriesResolverTest { @Mock private BundleContext bundleContext; private BundleContextBackedModuleFactoriesResolver resolver; - private ServiceReference s1; - private ServiceReference s2; + private ServiceReference s1; + private ServiceReference s2; private ModuleFactory f1; private ModuleFactory f2; @@ -42,15 +41,15 @@ public class BundleContextBackedModuleFactoriesResolverTest { resolver = new BundleContextBackedModuleFactoriesResolver(bundleContext); } - private ModuleFactory getMockFactory(String name) { + private ModuleFactory getMockFactory(final String name) { ModuleFactory mock = mock(ModuleFactory.class); doReturn(name).when(mock).toString(); doReturn(name).when(mock).getImplementationName(); return mock; } - private ServiceReference getServiceRef() { - ServiceReference mock = mock(ServiceReference.class); + private ServiceReference getServiceRef() { + ServiceReference mock = mock(ServiceReference.class); doReturn("serviceRef").when(mock).toString(); final Bundle bundle = mock(Bundle.class); doReturn(bundleContext).when(bundle).getBundleContext(); diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java index 5b83412083..25d770e6c9 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java @@ -1,8 +1,8 @@ package org.opendaylight.controller.config.manager.impl.osgi; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.fail; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; @@ -11,10 +11,8 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; - import java.util.Dictionary; import java.util.Set; - import org.junit.Before; import org.junit.Test; import org.mockito.Mock; @@ -44,7 +42,7 @@ public class ModuleFactoryBundleTrackerTest { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { return getClass().getClassLoader().loadClass((String) invocation.getArguments()[0]); @@ -141,7 +139,7 @@ public class ModuleFactoryBundleTrackerTest { } static class WrongConstructorTestingFactory extends TestingFactory { - WrongConstructorTestingFactory(String randomParam) { + WrongConstructorTestingFactory(final String randomParam) { } } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java index 79391d4343..9edb64ac6b 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/RefreshingSCPModuleInfoRegistryTest.java @@ -1,5 +1,9 @@ package org.opendaylight.controller.config.manager.impl.osgi; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import java.util.Dictionary; import org.junit.Test; import org.mockito.Mockito; import org.opendaylight.controller.config.manager.impl.osgi.mapping.RefreshingSCPModuleInfoRegistry; @@ -10,12 +14,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; -import java.util.*; - -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - public class RefreshingSCPModuleInfoRegistryTest { @Test public void testConstructor() throws Exception { @@ -24,8 +22,7 @@ public class RefreshingSCPModuleInfoRegistryTest { doReturn("string").when(prov).toString(); BundleContext ctxt = mock(BundleContext.class); - Dictionary dict = new Hashtable(); - ServiceRegistration servReg = mock(ServiceRegistration.class); + ServiceRegistration servReg = mock(ServiceRegistration.class); doReturn(servReg).when(ctxt).registerService(Mockito.any(Class.class), Mockito.any(SchemaContextProvider.class), Mockito.any(Dictionary.class)); doReturn(servReg).when(ctxt).registerService(Mockito.anyString(), Mockito.any(Object.class), Mockito.any(Dictionary.class)); RefreshingSCPModuleInfoRegistry scpreg = new RefreshingSCPModuleInfoRegistry(reg, prov, ctxt); diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java index 220bef03bc..4be40a64f5 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java @@ -8,7 +8,7 @@ package org.opendaylight.controller.config.manager.impl.util; import static org.junit.Assert.assertEquals; - +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Collections; import java.util.HashSet; @@ -92,7 +92,7 @@ public class InterfacesHelperTest { input.add(clazz); Set> result = InterfacesHelper.getAllAbstractServiceInterfaceClasses(input); - Set> expected = Sets.newHashSet((Class) TestingScheduledThreadPoolServiceInterface.class, + Set> expected = ImmutableSet.of((Class) TestingScheduledThreadPoolServiceInterface.class, TestingThreadPoolServiceInterface.class ); assertEquals(expected, result); diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java index fb59e3d515..f1efc4787d 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java @@ -4,7 +4,6 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; - import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; @@ -37,7 +36,7 @@ public class OsgiRegistrationUtilTest { OsgiRegistrationUtil.wrap(serviceReg).close(); verify(serviceReg).unregister(); - final BundleTracker tracker = mock(BundleTracker.class); + final BundleTracker tracker = mock(BundleTracker.class); doNothing().when(tracker).close(); OsgiRegistrationUtil.wrap(tracker).close(); verify(tracker).close(); @@ -49,7 +48,7 @@ public class OsgiRegistrationUtilTest { } private ServiceRegistration mockServiceRegistration() { - ServiceRegistration mock = mock(ServiceRegistration.class); + ServiceRegistration mock = mock(ServiceRegistration.class); doNothing().when(mock).unregister(); return mock; } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java index e5306a4fa6..d34e73ec47 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java @@ -7,7 +7,9 @@ */ package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool; -import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableSet; +import java.util.HashSet; +import java.util.Set; import org.opendaylight.controller.config.api.DependencyResolver; import org.opendaylight.controller.config.api.DependencyResolverFactory; import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; @@ -19,20 +21,16 @@ import org.opendaylight.controller.config.spi.Module; import org.opendaylight.controller.config.spi.ModuleFactory; import org.osgi.framework.BundleContext; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory { public static final String NAME = "scheduled"; - private static Set> ifc = Collections.unmodifiableSet(Sets.newHashSet( + private static Set> ifc = ImmutableSet.of( (Class) TestingScheduledThreadPoolServiceInterface.class, - TestingThreadPoolServiceInterface.class)); + TestingThreadPoolServiceInterface.class); @Override public boolean isModuleImplementingServiceInterface( - Class serviceInterface) { + final Class serviceInterface) { return ifc.contains(serviceInterface); } @@ -42,15 +40,15 @@ public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory { } @Override - public Module createModule(String instanceName, - DependencyResolver dependencyResolver, BundleContext bundleContext) { + public Module createModule(final String instanceName, + final DependencyResolver dependencyResolver, final BundleContext bundleContext) { return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null); } @Override - public Module createModule(String instanceName, - DependencyResolver dependencyResolver, DynamicMBeanWithInstance old, BundleContext bundleContext) + public Module createModule(final String instanceName, + final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { TestingScheduledThreadPoolImpl oldInstance; try { @@ -68,7 +66,7 @@ public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory { } @Override - public Set getDefaultModules(DependencyResolverFactory dependencyResolverFactory, BundleContext bundleContext) { + public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) { return new HashSet(); } diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java index ca038f1f1c..9c8b575fe5 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java @@ -7,38 +7,35 @@ */ package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.test; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; - import javax.annotation.Nullable; import javax.management.DynamicMBean; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.ObjectName; - import org.junit.Test; import org.opendaylight.controller.config.api.ValidationException; import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPConfigMXBean; import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory; import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl; -import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool - .TestingScheduledThreadPoolModuleFactory; +import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory; import org.opendaylight.controller.config.util.ConfigTransactionJMXClient; public class TwoInterfacesExportTest extends AbstractScheduledTest { - private void assertExists(String moduleName, String instanceName) + private void assertExists(final String moduleName, final String instanceName) throws Exception { assertExists(null, moduleName, instanceName); } - private void assertExists(@Nullable ConfigTransactionJMXClient transaction, - String moduleName, String instanceName) + private void assertExists(@Nullable final ConfigTransactionJMXClient transaction, + final String moduleName, final String instanceName) throws InstanceNotFoundException { if (transaction != null) { transaction.lookupConfigBean(moduleName, instanceName); @@ -56,13 +53,13 @@ public class TwoInterfacesExportTest extends AbstractScheduledTest { } } - private void assertNotExists(String moduleName, String instanceName) { + private void assertNotExists(final String moduleName, final String instanceName) { assertNotExists(null, moduleName, instanceName); } private void assertNotExists( - @Nullable ConfigTransactionJMXClient transaction, - String moduleName, String instanceName) { + @Nullable final ConfigTransactionJMXClient transaction, + final String moduleName, final String instanceName) { if (transaction != null) { try { diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java index bec2868557..d385a7db5a 100644 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java +++ b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java @@ -7,7 +7,9 @@ */ package org.opendaylight.controller.config.manager.testingservices.threadpool; -import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableSet; +import java.util.HashSet; +import java.util.Set; import org.opendaylight.controller.config.api.DependencyResolver; import org.opendaylight.controller.config.api.DependencyResolverFactory; import org.opendaylight.controller.config.api.DynamicMBeanWithInstance; @@ -19,16 +21,12 @@ import org.opendaylight.controller.config.spi.Module; import org.opendaylight.controller.config.spi.ModuleFactory; import org.osgi.framework.BundleContext; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory implements ModuleFactory { public static final String NAME = "fixed"; - private static Set> ifc = Collections.unmodifiableSet(Sets.newHashSet( + private static final Set> ifc = ImmutableSet.of( (Class) ModifiableThreadPoolServiceInterface.class, - TestingThreadPoolServiceInterface.class)); + TestingThreadPoolServiceInterface.class); @Override public String getImplementationName() { @@ -36,15 +34,15 @@ public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThr } @Override - public TestingFixedThreadPoolModule createModule(String instanceName, - DependencyResolver dependencyResolver, BundleContext bundleContext) { + public TestingFixedThreadPoolModule createModule(final String instanceName, + final DependencyResolver dependencyResolver, final BundleContext bundleContext) { return new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null); } @Override - public Module createModule(String instanceName, - DependencyResolver dependencyResolver, DynamicMBeanWithInstance old, BundleContext bundleContext) + public Module createModule(final String instanceName, + final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { int threadCount = (Integer) old.getAttribute("ThreadCount"); // is the instance compatible? @@ -65,12 +63,12 @@ public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThr @Override public boolean isModuleImplementingServiceInterface( - Class serviceInterface) { + final Class serviceInterface) { return ifc.contains(serviceInterface); } @Override - public Set getDefaultModules(DependencyResolverFactory dependencyResolverFactory, BundleContext bundleContext) { + public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) { return new HashSet(); } diff --git a/opendaylight/config/config-netty-config/pom.xml b/opendaylight/config/config-netty-config/pom.xml index 257c36779c..1e7a027b5b 100644 --- a/opendaylight/config/config-netty-config/pom.xml +++ b/opendaylight/config/config-netty-config/pom.xml @@ -1,4 +1,5 @@ + - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.3.0-SNAPSHOT - - config-netty-config - Configuration files for sal-rest-connector - jar - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/initial/00-netty.xml - xml - config - - - - - - - - + 4.0.0 + + org.opendaylight.controller + config-subsystem + 0.3.0-SNAPSHOT + + config-netty-config + Configuration files for sal-rest-connector + jar + + + + org.codehaus.mojo + build-helper-maven-plugin + + + attach-artifacts + + attach-artifact + + package + + + + ${project.build.directory}/classes/initial/00-netty.xml + xml + config + + + + + + + + diff --git a/opendaylight/config/config-persister-api/src/test/java/org/opendaylight/controller/config/persist/test/PropertiesProviderTest.java b/opendaylight/config/config-persister-api/src/test/java/org/opendaylight/controller/config/persist/test/PropertiesProviderTest.java index 3d4757b926..2c60310e8a 100644 --- a/opendaylight/config/config-persister-api/src/test/java/org/opendaylight/controller/config/persist/test/PropertiesProviderTest.java +++ b/opendaylight/config/config-persister-api/src/test/java/org/opendaylight/controller/config/persist/test/PropertiesProviderTest.java @@ -12,7 +12,7 @@ import java.util.Map; import org.opendaylight.controller.config.persist.api.PropertiesProvider; public class PropertiesProviderTest implements PropertiesProvider { - private final Map properties = new HashMap(); + private final Map properties = new HashMap<>(); public void addProperty(String key,String value){ properties.put(key,value); diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryPersister.java b/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryPersister.java index 7f8ebd7fdd..92bf080662 100644 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryPersister.java +++ b/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryPersister.java @@ -7,17 +7,9 @@ */ package org.opendaylight.controller.config.persist.storage.directory.xml; +import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Optional; import com.google.common.io.Files; -import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; -import org.opendaylight.controller.config.persist.api.Persister; -import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; @@ -27,11 +19,17 @@ import java.util.Collections; import java.util.List; import java.util.Set; import java.util.SortedSet; - -import static com.google.common.base.Preconditions.checkArgument; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; +import org.opendaylight.controller.config.persist.api.Persister; +import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class XmlDirectoryPersister implements Persister { - private static final Logger logger = LoggerFactory.getLogger(XmlDirectoryPersister.class); + private static final Logger LOG = LoggerFactory.getLogger(XmlDirectoryPersister.class); private final File storage; private final Optional extensionsFilter; @@ -39,25 +37,25 @@ public class XmlDirectoryPersister implements Persister { /** * Creates XmlDirectoryPersister that picks up all files in specified folder */ - public XmlDirectoryPersister(File storage) { + public XmlDirectoryPersister(final File storage) { this(storage, Optional.absent()); } /** * Creates XmlDirectoryPersister that picks up files only with specified file extension */ - public XmlDirectoryPersister(File storage, Set fileExtensions) { + public XmlDirectoryPersister(final File storage, final Set fileExtensions) { this(storage, Optional.of(getFilter(fileExtensions))); } - private XmlDirectoryPersister(File storage, Optional extensionsFilter) { + private XmlDirectoryPersister(final File storage, final Optional extensionsFilter) { checkArgument(storage.exists() && storage.isDirectory(), "Storage directory does not exist: " + storage); this.storage = storage; this.extensionsFilter = extensionsFilter; } @Override - public void persistConfig(ConfigSnapshotHolder holder) throws IOException { + public void persistConfig(final ConfigSnapshotHolder holder) throws IOException { throw new UnsupportedOperationException("This adapter is read only. Please set readonly=true on " + getClass()); } @@ -70,11 +68,11 @@ public class XmlDirectoryPersister implements Persister { List sortedFiles = new ArrayList<>(Arrays.asList(filesArray)); Collections.sort(sortedFiles); // combine all found files - logger.debug("Reading files in following order: {}", sortedFiles); + LOG.debug("Reading files in following order: {}", sortedFiles); List result = new ArrayList<>(); for (File file : sortedFiles) { - logger.trace("Adding file '{}' to combined result", file); + LOG.trace("Adding file '{}' to combined result", file); Optional h = fromXmlSnapshot(file); // Ignore non valid snapshot if(h.isPresent() == false) { @@ -86,12 +84,12 @@ public class XmlDirectoryPersister implements Persister { return result; } - private Optional fromXmlSnapshot(File file) { + private Optional fromXmlSnapshot(final File file) { try { return Optional.of(loadLastConfig(file)); } catch (JAXBException e) { // In case of parse error, issue a warning, ignore and continue - logger.warn( + LOG.warn( "Unable to parse configuration snapshot from {}. Initial config from {} will be IGNORED in this run. " + "Note that subsequent config files may fail due to this problem. " + "Xml markup in this file needs to be fixed, for detailed information see enclosed exception.", @@ -101,7 +99,7 @@ public class XmlDirectoryPersister implements Persister { return Optional.absent(); } - public static ConfigSnapshotHolder loadLastConfig(File file) throws JAXBException { + public static ConfigSnapshotHolder loadLastConfig(final File file) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(ConfigSnapshot.class); Unmarshaller um = jaxbContext.createUnmarshaller(); @@ -132,7 +130,7 @@ public class XmlDirectoryPersister implements Persister { return new FilenameFilter() { @Override - public boolean accept(File dir, String name) { + public boolean accept(final File dir, final String name) { String ext = Files.getFileExtension(name); return fileExtensions.contains(ext); } diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryStorageAdapter.java b/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryStorageAdapter.java index 40f8c283dd..42ab93b585 100644 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryStorageAdapter.java +++ b/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryStorageAdapter.java @@ -11,21 +11,20 @@ package org.opendaylight.controller.config.persist.storage.directory.xml; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Sets; +import java.io.File; +import java.util.Set; import org.opendaylight.controller.config.persist.api.Persister; import org.opendaylight.controller.config.persist.api.PropertiesProvider; import org.opendaylight.controller.config.persist.api.StorageAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.util.Set; - /** * StorageAdapter that retrieves initial configuration from a directory. If multiple files are present, snapshot and * required capabilities will be merged together. Writing to this persister is not supported. */ public class XmlDirectoryStorageAdapter implements StorageAdapter { - private static final Logger logger = LoggerFactory.getLogger(XmlDirectoryStorageAdapter.class); + private static final Logger LOG = LoggerFactory.getLogger(XmlDirectoryStorageAdapter.class); public static final String DIRECTORY_STORAGE_PROP = "directoryStorage"; public static final String INCLUDE_EXT_PROP = "includeExtensions"; @@ -33,23 +32,23 @@ public class XmlDirectoryStorageAdapter implements StorageAdapter { @Override - public Persister instantiate(PropertiesProvider propertiesProvider) { + public Persister instantiate(final PropertiesProvider propertiesProvider) { String fileStorageProperty = propertiesProvider.getProperty(DIRECTORY_STORAGE_PROP); Preconditions.checkNotNull(fileStorageProperty, "Unable to find " + propertiesProvider.getFullKeyForReporting(DIRECTORY_STORAGE_PROP)); File storage = new File(fileStorageProperty); String fileExtensions = propertiesProvider.getProperty(INCLUDE_EXT_PROP); - logger.debug("Using storage: {}", storage); + LOG.debug("Using storage: {}", storage); if(fileExtensions != null) { - logger.debug("Using extensions: {}", fileExtensions); + LOG.debug("Using extensions: {}", fileExtensions); return new XmlDirectoryPersister(storage, splitExtensions(fileExtensions)); } else { return new XmlDirectoryPersister(storage); } } - private Set splitExtensions(String fileExtensions) { + private Set splitExtensions(final String fileExtensions) { return Sets.newHashSet(Splitter.on(EXTENSIONS_SEPARATOR).trimResults().omitEmptyStrings() .split(fileExtensions)); } diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/directory/xml/DirectoryStorageAdapterTest.java b/opendaylight/config/config-persister-directory-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/directory/xml/DirectoryStorageAdapterTest.java index 7af06bd3e3..11c7e1253a 100644 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/directory/xml/DirectoryStorageAdapterTest.java +++ b/opendaylight/config/config-persister-directory-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/directory/xml/DirectoryStorageAdapterTest.java @@ -12,13 +12,12 @@ import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; - +import com.google.common.base.Optional; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.SortedSet; - import org.junit.Test; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.config.persist.api.Persister; @@ -27,13 +26,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; -import com.google.common.base.Optional; - public class DirectoryStorageAdapterTest { + private static final Logger LOG = LoggerFactory.getLogger(DirectoryStorageAdapterTest.class); Persister tested; - Logger logger = LoggerFactory.getLogger(DirectoryStorageAdapterTest.class.toString()); - private Persister instantiatePersisterFromAdapter(File file, Optional extensions){ + private Persister instantiatePersisterFromAdapter(final File file, final Optional extensions){ PropertiesProviderTest pp = new PropertiesProviderTest(); pp.addProperty(XmlDirectoryStorageAdapter.DIRECTORY_STORAGE_PROP,file.getPath()); if(extensions.isPresent()) { @@ -44,7 +41,7 @@ public class DirectoryStorageAdapterTest { return dsa.instantiate(pp); } - private Persister instantiatePersisterFromAdapter(File file){ + private Persister instantiatePersisterFromAdapter(final File file){ return instantiatePersisterFromAdapter(file, Optional.absent()); } @@ -74,7 +71,7 @@ public class DirectoryStorageAdapterTest { } } - private File getFolder(String folderName) { + private File getFolder(final String folderName) { File result = new File(("src/test/resources/" + folderName).replace("/", File.separator)); assertTrue(result + " is not a directory", result.isDirectory()); @@ -86,7 +83,7 @@ public class DirectoryStorageAdapterTest { File folder = getFolder("oneFile"); tested = instantiatePersisterFromAdapter(folder, Optional.of("xml")); - logger.info("Testing : " + tested.toString()); + LOG.info("Testing : {}", tested); List results = tested.loadLastConfigs(); assertEquals(1, results.size()); ConfigSnapshotHolder result = results.get(0); @@ -97,10 +94,10 @@ public class DirectoryStorageAdapterTest { public void testOneFileWrongExtension() throws Exception { File folder = getFolder("oneFile"); tested = instantiatePersisterFromAdapter(folder, Optional.of("aa, bb")); - logger.info("Testing : " + tested.toString()); + LOG.info("Testing : {}", tested); } - private void assertResult(ConfigSnapshotHolder result, String s, String... caps) throws SAXException, IOException { + private void assertResult(final ConfigSnapshotHolder result, final String s, final String... caps) throws SAXException, IOException { assertXMLEqual(s, result.getConfigSnapshot()); int i = 0; for (String capFromSnapshot : result.getCapabilities()) { @@ -112,7 +109,7 @@ public class DirectoryStorageAdapterTest { public void testTwoFilesAllExtensions() throws Exception { File folder = getFolder("twoFiles"); tested = instantiatePersisterFromAdapter(folder); - logger.info("Testing : " + tested.toString()); + LOG.info("Testing : {}", tested); List results = tested.loadLastConfigs(); assertEquals(2, results.size()); @@ -124,7 +121,7 @@ public class DirectoryStorageAdapterTest { public void testTwoFilesTwoExtensions() throws Exception { File folder = getFolder("twoFiles"); tested = instantiatePersisterFromAdapter(folder, Optional.of("xml, xml2")); - logger.info("Testing : " + tested.toString()); + LOG.info("Testing : {}", tested); assertEquals(2, tested.loadLastConfigs().size()); } @@ -132,7 +129,7 @@ public class DirectoryStorageAdapterTest { public void testTwoFilesOnlyOneExtension() throws Exception { File folder = getFolder("twoFiles"); tested = instantiatePersisterFromAdapter(folder, Optional.of("xml")); - logger.info("Testing : " + tested.toString()); + LOG.info("Testing : ", tested); List results = tested.loadLastConfigs(); assertEquals(1, results.size()); @@ -143,7 +140,7 @@ public class DirectoryStorageAdapterTest { public void testTwoFilesOneInvalid() throws Exception { File folder = getFolder("twoFiles_corrupt"); tested = instantiatePersisterFromAdapter(folder, Optional.of("xml")); - logger.info("Testing : " + tested.toString()); + LOG.info("Testing : {}", tested); List results = tested.loadLastConfigs(); assertEquals(1, results.size()); diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPusherCustomizer.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPusherCustomizer.java index abb1dbe9aa..52bca76555 100644 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPusherCustomizer.java +++ b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPusherCustomizer.java @@ -17,14 +17,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConfigPusherCustomizer implements ServiceTrackerCustomizer, AutoCloseable { - private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPusherCustomizer.class); + private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherCustomizer.class); private ConfigFeaturesListener configFeaturesListener = null; private FeatureServiceCustomizer featureServiceCustomizer = null; private ServiceTracker fsst = null; @Override public ConfigPusher addingService(ServiceReference configPusherServiceReference) { - LOGGER.trace("Got ConfigPusherCustomizer.addingService {}", configPusherServiceReference); + LOG.trace("Got ConfigPusherCustomizer.addingService {}", configPusherServiceReference); BundleContext bc = configPusherServiceReference.getBundle().getBundleContext(); ConfigPusher cpService = bc.getService(configPusherServiceReference); featureServiceCustomizer = new FeatureServiceCustomizer(cpService); diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPushingRunnable.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPushingRunnable.java index b0e64b84d2..1a40bb34d7 100644 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPushingRunnable.java +++ b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPushingRunnable.java @@ -40,14 +40,14 @@ public class ConfigPushingRunnable implements Runnable { while(true) { try { if(!interuppted) { - if(toInstall.isEmpty()) { - event = queue.take(); - } else { - event = queue.poll(POLL_TIME, TimeUnit.MILLISECONDS); - } - if(event != null && event.getFeature() !=null) { - processFeatureEvent(event,toInstall); - } + if(toInstall.isEmpty()) { + event = queue.take(); + } else { + event = queue.poll(POLL_TIME, TimeUnit.MILLISECONDS); + } + if(event != null && event.getFeature() !=null) { + processFeatureEvent(event,toInstall); + } } else if(toInstall.isEmpty()) { LOGGER.error("ConfigPushingRunnable - exiting"); return; diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigPusher.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigPusher.java index 5c5061277b..7b90580a66 100644 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigPusher.java +++ b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigPusher.java @@ -7,11 +7,11 @@ */ package org.opendaylight.controller.configpusherfeature.internal; +import com.google.common.collect.LinkedHashMultimap; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; - import org.apache.karaf.features.Feature; import org.apache.karaf.features.FeaturesService; import org.opendaylight.controller.config.persist.api.ConfigPusher; @@ -19,13 +19,11 @@ import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.LinkedHashMultimap; - /* * Simple class to push configs to the config subsystem from Feature's configfiles */ public class FeatureConfigPusher { - private static final Logger LOGGER = LoggerFactory.getLogger(FeatureConfigPusher.class); + private static final Logger LOG = LoggerFactory.getLogger(FeatureConfigPusher.class); private static final int MAX_RETRIES=100; private static final int RETRY_PAUSE_MILLIS=1; private FeaturesService featuresService = null; @@ -46,7 +44,7 @@ public class FeatureConfigPusher { /* * @param p - ConfigPusher to push ConfigSnapshotHolders */ - public FeatureConfigPusher(ConfigPusher p, FeaturesService f) { + public FeatureConfigPusher(final ConfigPusher p, final FeaturesService f) { pusher = p; featuresService = f; } @@ -59,7 +57,7 @@ public class FeatureConfigPusher { * If a Feature is not in the returned LinkedHashMultimap then we couldn't push its configs * (Ususally because it was not yet installed) */ - public LinkedHashMultimap pushConfigs(List features) throws Exception, InterruptedException { + public LinkedHashMultimap pushConfigs(final List features) throws Exception, InterruptedException { LinkedHashMultimap pushedFeatures = LinkedHashMultimap.create(); for(Feature feature: features) { LinkedHashSet configSnapShots = pushConfig(feature); @@ -70,7 +68,7 @@ public class FeatureConfigPusher { return pushedFeatures; } - private LinkedHashSet pushConfig(Feature feature) throws Exception, InterruptedException { + private LinkedHashSet pushConfig(final Feature feature) throws Exception, InterruptedException { LinkedHashSet configs = new LinkedHashSet(); if(isInstalled(feature)) { ChildAwareFeatureWrapper wrappedFeature = new ChildAwareFeatureWrapper(feature,featuresService); @@ -83,20 +81,20 @@ public class FeatureConfigPusher { return configs; } - private boolean isInstalled(Feature feature) { + private boolean isInstalled(final Feature feature) { for(int retries=0;retries installedFeatures = Arrays.asList(featuresService.listInstalledFeatures()); if(installedFeatures.contains(feature)) { return true; } else { - LOGGER.warn("Karaf featuresService.listInstalledFeatures() has not yet finished installing feature (retry {}) {} {}",retries,feature.getName(),feature.getVersion()); + LOG.warn("Karaf featuresService.listInstalledFeatures() has not yet finished installing feature (retry {}) {} {}",retries,feature.getName(),feature.getVersion()); } } catch (Exception e) { if(retries < MAX_RETRIES) { - LOGGER.warn("Karaf featuresService.listInstalledFeatures() has thrown an exception, retry {}, Exception {}", retries,e); + LOG.warn("Karaf featuresService.listInstalledFeatures() has thrown an exception, retry {}", retries, e); } else { - LOGGER.error("Giving up on Karaf featuresService.listInstalledFeatures() which has thrown an exception, retry {}, Exception {}", retries,e); + LOG.error("Giving up on Karaf featuresService.listInstalledFeatures() which has thrown an exception, retry {}", retries, e); throw e; } } @@ -106,11 +104,11 @@ public class FeatureConfigPusher { throw new IllegalStateException(e1); } } - LOGGER.error("Giving up (after {} retries) on Karaf featuresService.listInstalledFeatures() which has not yet finished installing feature {} {}",MAX_RETRIES,feature.getName(),feature.getVersion()); + LOG.error("Giving up (after {} retries) on Karaf featuresService.listInstalledFeatures() which has not yet finished installing feature {} {}",MAX_RETRIES,feature.getName(),feature.getVersion()); return false; } - private LinkedHashSet pushConfig(LinkedHashSet configs) throws InterruptedException { + private LinkedHashSet pushConfig(final LinkedHashSet configs) throws InterruptedException { LinkedHashSet configsToPush = new LinkedHashSet(configs); configsToPush.removeAll(pushedConfigs); if(!configsToPush.isEmpty()) { diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigSnapshotHolder.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigSnapshotHolder.java index d1a92ebe7f..5ab5c959f7 100644 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigSnapshotHolder.java +++ b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigSnapshotHolder.java @@ -106,16 +106,15 @@ public class FeatureConfigSnapshotHolder implements ConfigSnapshotHolder { @Override public String toString() { - StringBuilder b = new StringBuilder(); - Path p = Paths.get(fileInfo.getFinalname()); - b.append(p.getFileName()) - .append("(") - .append(getCauseFeature()) - .append(",") - .append(getFeature()) - .append(")"); - return b.toString(); - + StringBuilder b = new StringBuilder(); + Path p = Paths.get(fileInfo.getFinalname()); + b.append(p.getFileName()) + .append("(") + .append(getCauseFeature()) + .append(",") + .append(getFeature()) + .append(")"); + return b.toString(); } @Override diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/FileStorageAdapterTest.java b/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/FileStorageAdapterTest.java index 2bfe70adb8..942ba4c4b3 100644 --- a/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/FileStorageAdapterTest.java +++ b/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/FileStorageAdapterTest.java @@ -8,12 +8,12 @@ package org.opendaylight.controller.config.persist.storage.file.xml; -import static junit.framework.Assert.assertFalse; +import static org.junit.Assert.assertFalse; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; - +import com.google.common.base.Charsets; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -21,17 +21,12 @@ import java.nio.file.Files; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; - -import junit.framework.Assert; - import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.config.persist.test.PropertiesProviderTest; -import com.google.common.base.Charsets; - public class FileStorageAdapterTest { private static int i; @@ -42,8 +37,9 @@ public class FileStorageAdapterTest { @Before public void setUp() throws Exception { file = Files.createTempFile("testFilePersist", ".txt").toFile(); - if (!file.exists()) + if (!file.exists()) { return; + } com.google.common.io.Files.write("", file, Charsets.UTF_8); i = 1; } @@ -71,7 +67,7 @@ public class FileStorageAdapterTest { storage.persistConfig(holder); - Assert.assertEquals(storage.toString().replace("\\","/"),"XmlFileStorageAdapter [storage="+NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE+"]"); + assertEquals(storage.toString().replace("\\","/"),"XmlFileStorageAdapter [storage="+NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE+"]"); delete(new File(NON_EXISTENT_DIRECTORY)); } @Test @@ -109,7 +105,7 @@ public class FileStorageAdapterTest { storage.setNumberOfBackups(Integer.MAX_VALUE); List last = storage.loadLastConfigs(); - Assert.assertEquals(createCaps(), last.get(0).getCapabilities()); + assertEquals(createCaps(), last.get(0).getCapabilities()); } private SortedSet createCaps() { @@ -188,8 +184,9 @@ public class FileStorageAdapterTest { @Test public void testNoLastConfig() throws Exception { File file = Files.createTempFile("testFilePersist", ".txt").toFile(); - if (!file.exists()) + if (!file.exists()) { return; + } XmlFileStorageAdapter storage = new XmlFileStorageAdapter(); storage.setFileStorage(file); @@ -223,12 +220,14 @@ public class FileStorageAdapterTest { return "" + i++ + ""; } - private void delete(File f) throws IOException { + private void delete(final File f) throws IOException { if (f.isDirectory()) { - for (File c : f.listFiles()) + for (File c : f.listFiles()) { delete(c); + } } - if (!f.delete()) + if (!f.delete()) { throw new FileNotFoundException("Failed to delete file: " + f); + } } } diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/AttributeEntryTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/AttributeEntryTest.java index b2afd3542e..200fa8854d 100644 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/AttributeEntryTest.java +++ b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/AttributeEntryTest.java @@ -2,8 +2,6 @@ package org.opendaylight.controller.config.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; - -import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigRegistryClientsTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigRegistryClientsTest.java index 0524f0019a..fc1c3f8afe 100644 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigRegistryClientsTest.java +++ b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigRegistryClientsTest.java @@ -7,29 +7,25 @@ */ package org.opendaylight.controller.config.util; +import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; -import static org.junit.matchers.JUnitMatchers.hasItem; - +import com.google.common.collect.Sets; import java.lang.management.ManagementFactory; import java.util.HashMap; import java.util.Map; import java.util.Set; - import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.ObjectName; - import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.config.api.ConfigRegistry; -import com.google.common.collect.Sets; - public class ConfigRegistryClientsTest { private TestingConfigRegistry testingRegistry; @@ -145,7 +141,7 @@ public class ConfigRegistryClientsTest { assertEquals(Sets.newHashSet(TestingConfigRegistry.run2, TestingConfigRegistry.run1, TestingConfigRegistry.run3), jmxLookup); } - private Set lookupRuntimeBeans(ConfigRegistryClient client) + private Set lookupRuntimeBeans(final ConfigRegistryClient client) throws Exception { Set beans = client.lookupRuntimeBeans(); for (ObjectName on : beans) { @@ -178,7 +174,7 @@ public class ConfigRegistryClientsTest { } private Set clientLookupRuntimeBeansWithModuleAndInstance( - ConfigRegistryClient client, String moduleName, String instanceName) { + final ConfigRegistryClient client, final String moduleName, final String instanceName) { Set beans = client.lookupRuntimeBeans(moduleName, instanceName); if (beans.size() > 0) { assertEquals("RuntimeBean", @@ -220,7 +216,7 @@ public class ConfigRegistryClientsTest { assertThat(clientLookupServiceInterfaceNames(testingRegistryON), hasItem(TestingConfigRegistry.serviceQName2)); } - private Set clientLookupServiceInterfaceNames(ObjectName client) throws InstanceNotFoundException{ + private Set clientLookupServiceInterfaceNames(final ObjectName client) throws InstanceNotFoundException{ return jmxRegistryClient.lookupServiceInterfaceNames(client); } diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/LookupTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/LookupTest.java index 4489762a47..3bc362b38c 100644 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/LookupTest.java +++ b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/LookupTest.java @@ -93,8 +93,7 @@ public class LookupTest { public void testLookupConfigBeans2() throws Exception { Method method = LookupRegistry.class.getMethod("lookupConfigBeans", String.class, String.class); - Object[] args = new Object[] { TestingConfigRegistry.moduleName1, - TestingConfigRegistry.instName1 }; + Object[] args = new Object[] { TestingConfigRegistry.moduleName1, TestingConfigRegistry.instName1 }; test(method, args); } @@ -102,8 +101,7 @@ public class LookupTest { public void testLookupConfigBean() throws Exception { Method method = LookupRegistry.class.getMethod("lookupConfigBean", String.class, String.class); - Object[] args = new Object[] { TestingConfigRegistry.moduleName1, - TestingConfigRegistry.instName1 }; + Object[] args = new Object[] { TestingConfigRegistry.moduleName1, TestingConfigRegistry.instName1 }; test(method, args); } diff --git a/opendaylight/config/logback-config-loader/src/test/java/org/opendaylight/controller/logback/config/loader/test/LogbackConfigurationLoaderTest.java b/opendaylight/config/logback-config-loader/src/test/java/org/opendaylight/controller/logback/config/loader/test/LogbackConfigurationLoaderTest.java index 2e9bf1df00..adbb9f4cd6 100644 --- a/opendaylight/config/logback-config-loader/src/test/java/org/opendaylight/controller/logback/config/loader/test/LogbackConfigurationLoaderTest.java +++ b/opendaylight/config/logback-config-loader/src/test/java/org/opendaylight/controller/logback/config/loader/test/LogbackConfigurationLoaderTest.java @@ -58,23 +58,22 @@ public class LogbackConfigurationLoaderTest { // check logs String[] expectedLogs = new String[] { - "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.LogbackConfigurationLoaderTest: LOGBACK ready -> about to use it", - "LoggingEvent -> [TRACE] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: tracing", - "LoggingEvent -> [DEBUG] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: debugging", - "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: infoing", - "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: warning", - "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: erroring", - "LoggingEvent -> [DEBUG] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: debugging", - "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: infoing", - "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: warning", - "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: erroring", - "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: infoing", - "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: warning", - "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: erroring", - "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Warner: warning", - "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Warner: erroring", - "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Errorer: erroring" - + "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.LogbackConfigurationLoaderTest: LOGBACK ready -> about to use it", + "LoggingEvent -> [TRACE] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: tracing", + "LoggingEvent -> [DEBUG] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: debugging", + "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: infoing", + "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: warning", + "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Tracer: erroring", + "LoggingEvent -> [DEBUG] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: debugging", + "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: infoing", + "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: warning", + "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Debugger: erroring", + "LoggingEvent -> [INFO] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: infoing", + "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: warning", + "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Informer: erroring", + "LoggingEvent -> [WARN] org.opendaylight.controller.logback.config.loader.test.logwork.Warner: warning", + "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Warner: erroring", + "LoggingEvent -> [ERROR] org.opendaylight.controller.logback.config.loader.test.logwork.Errorer: erroring" }; List logSnapshot = new ArrayList<>(TestAppender.getLogRecord()); diff --git a/opendaylight/config/logback-config-loader/src/test/resources/logback-test.xml b/opendaylight/config/logback-config-loader/src/test/resources/logback-test.xml index 7fb760aca7..52f2521969 100755 --- a/opendaylight/config/logback-config-loader/src/test/resources/logback-test.xml +++ b/opendaylight/config/logback-config-loader/src/test/resources/logback-test.xml @@ -1,17 +1,17 @@ - - - - - - %date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - + + + + + + %date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + diff --git a/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt.xml b/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt.xml index ca489d5c78..e4f8dfc26b 100755 --- a/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt.xml +++ b/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt.xml @@ -1,19 +1,19 @@ - - - - - - - %date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - + + + + + + + %date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + diff --git a/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt2.xml b/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt2.xml index 89f82c5046..83557f6072 100755 --- a/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt2.xml +++ b/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt2.xml @@ -1,12 +1,12 @@ - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt3.xml b/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt3.xml index a37b6f7f21..a944cc28b5 100755 --- a/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt3.xml +++ b/opendaylight/config/logback-config-loader/src/test/resources/logback.d/logback-alt3.xml @@ -1,11 +1,11 @@ - - - - - - - - - - - + + + + + + + + + + + diff --git a/opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/ContextSetterImpl.java b/opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/ContextSetterImpl.java index ff7da5df48..087648cae7 100644 --- a/opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/ContextSetterImpl.java +++ b/opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/ContextSetterImpl.java @@ -7,16 +7,6 @@ */ package org.opendaylight.controller.config.yang.logback.config; -import java.io.Closeable; -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.slf4j.LoggerFactory; - import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; @@ -26,10 +16,17 @@ import ch.qos.logback.core.Appender; import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; - import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; +import java.io.Closeable; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.slf4j.LoggerFactory; /** * Implementation of {@link ContextSetter}. Resets running logback @@ -40,12 +37,13 @@ public class ContextSetterImpl implements ContextSetter, Closeable { private final LogbackStatusListener statusListener; private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ContextSetterImpl.class); - public ContextSetterImpl(LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) { + public ContextSetterImpl(final LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) { statusListener = new LogbackStatusListener(rootRuntimeBeanRegistratorWrapper); statusListener.register(); } - public void updateContext(LogbackModule module) { + @Override + public void updateContext(final LogbackModule module) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); List loggersBefore = context.getLoggerList(); @@ -53,12 +51,12 @@ public class ContextSetterImpl implements ContextSetter, Closeable { createLoggers(context, module, Sets.newHashSet(loggersBefore)); } - private Map> createConsoleAppenders(LoggerContext context, LogbackModule module) { + private Map> createConsoleAppenders(final LoggerContext context, final LogbackModule module) { Map> appendersMap = new HashMap<>(); for (ConsoleAppenderTO appender : module.getConsoleAppenderTO()) { Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false, "Duplicate appender name %s", appender.getName()); - ch.qos.logback.core.ConsoleAppender app = new ch.qos.logback.core.ConsoleAppender(); + ch.qos.logback.core.ConsoleAppender app = new ch.qos.logback.core.ConsoleAppender<>(); app.setContext(context); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(context); @@ -77,8 +75,8 @@ public class ContextSetterImpl implements ContextSetter, Closeable { return appendersMap; } - private void createLoggers(LoggerContext context, LogbackModule module, - Set loggersBefore) { + private void createLoggers(final LoggerContext context, final LogbackModule module, + final Set loggersBefore) { Map> appendersMap = getAppenders(module, context); @@ -97,8 +95,8 @@ public class ContextSetterImpl implements ContextSetter, Closeable { } } - private void addNewAppenders(Map> appendersMap, LoggerTO logger, - ch.qos.logback.classic.Logger logbackLogger, Optional>> appendersBefore) { + private void addNewAppenders(final Map> appendersMap, final LoggerTO logger, + final ch.qos.logback.classic.Logger logbackLogger, final Optional>> appendersBefore) { if (logger.getAppenders() != null) { for (String appenderName : logger.getAppenders()) { if (appendersMap.containsKey(appenderName)) { @@ -112,8 +110,8 @@ public class ContextSetterImpl implements ContextSetter, Closeable { } } - private void removeBeforeAppenders(Set loggersBefore, LoggerTO logger, - ch.qos.logback.classic.Logger logbackLogger, Optional>> appendersBefore) { + private void removeBeforeAppenders(final Set loggersBefore, final LoggerTO logger, + final ch.qos.logback.classic.Logger logbackLogger, final Optional>> appendersBefore) { if (appendersBefore.isPresent()) { for (Appender appenderBefore : appendersBefore.get()) { logbackLogger.detachAppender(appenderBefore); @@ -125,8 +123,8 @@ public class ContextSetterImpl implements ContextSetter, Closeable { } } - private Optional>> getAppendersBefore(Set loggersBefore, - ch.qos.logback.classic.Logger logbackLogger) { + private Optional>> getAppendersBefore(final Set loggersBefore, + final ch.qos.logback.classic.Logger logbackLogger) { if (loggersBefore.contains(logbackLogger)) { Iterator> appenderIt = logbackLogger.iteratorForAppenders(); Set> appendersBefore = Sets.newHashSet(); @@ -140,7 +138,7 @@ public class ContextSetterImpl implements ContextSetter, Closeable { } - private Map> getAppenders(LogbackModule module, LoggerContext context) { + private Map> getAppenders(final LogbackModule module, final LoggerContext context) { Map> appendersMap = new HashMap<>(); addAllAppenders(appendersMap, createRollingAppenders(context, module)); addAllAppenders(appendersMap, createFileAppenders(context, module)); @@ -149,8 +147,8 @@ public class ContextSetterImpl implements ContextSetter, Closeable { return appendersMap; } - private void addAllAppenders(Map> allAppenders, - Map> appendersToAdd) { + private void addAllAppenders(final Map> allAppenders, + final Map> appendersToAdd) { for (String appenderName : appendersToAdd.keySet()) { Preconditions.checkState(allAppenders.containsKey(appenderName) == false, "Duplicate appender name %s", appenderName); @@ -158,12 +156,12 @@ public class ContextSetterImpl implements ContextSetter, Closeable { } } - private Map> createFileAppenders(LoggerContext context, LogbackModule module) { + private Map> createFileAppenders(final LoggerContext context, final LogbackModule module) { Map> appendersMap = new HashMap<>(); for (FileAppenderTO appender : module.getFileAppenderTO()) { Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false, "Duplicate appender name %s", appender.getName()); - ch.qos.logback.core.FileAppender app = new ch.qos.logback.core.FileAppender<>(); + ch.qos.logback.core.FileAppender app = new ch.qos.logback.core.FileAppender<>(); app.setAppend(appender.getAppend()); app.setContext(context); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); @@ -180,12 +178,12 @@ public class ContextSetterImpl implements ContextSetter, Closeable { return appendersMap; } - private Map> createRollingAppenders(LoggerContext context, LogbackModule module) { + private Map> createRollingAppenders(final LoggerContext context, final LogbackModule module) { Map> appendersMap = new HashMap<>(); for (RollingFileAppenderTO appender : module.getRollingFileAppenderTO()) { Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false, "Duplicate appender name %s", appender.getName()); - ch.qos.logback.core.rolling.RollingFileAppender app = new ch.qos.logback.core.rolling.RollingFileAppender<>(); + ch.qos.logback.core.rolling.RollingFileAppender app = new ch.qos.logback.core.rolling.RollingFileAppender<>(); app.setAppend(appender.getAppend()); app.setContext(context); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); @@ -204,7 +202,7 @@ public class ContextSetterImpl implements ContextSetter, Closeable { policy.start(); app.setRollingPolicy(policy); } else if (appender.getRollingPolicyType().equals("TimeBasedRollingPolicy")) { - TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy(); + TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy<>(); policy.setContext(context); policy.setMaxHistory(appender.getMaxHistory()); if (appender.getCleanHistoryOnStart() != null) { @@ -215,7 +213,7 @@ public class ContextSetterImpl implements ContextSetter, Closeable { policy.start(); app.setRollingPolicy(policy); } - SizeBasedTriggeringPolicy triggeringPolicy = new SizeBasedTriggeringPolicy(); + SizeBasedTriggeringPolicy triggeringPolicy = new SizeBasedTriggeringPolicy<>(); triggeringPolicy.setContext(context); triggeringPolicy.setMaxFileSize(appender.getMaxFileSize()); triggeringPolicy.start(); diff --git a/opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleFactory.java b/opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleFactory.java index b5d0d1b4de..bd19d5eecd 100644 --- a/opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleFactory.java +++ b/opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleFactory.java @@ -16,6 +16,18 @@ */ package org.opendaylight.controller.config.yang.logback.config; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.encoder.PatternLayoutEncoder; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.LoggerComparator; +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; +import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; +import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -24,7 +36,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import org.apache.commons.lang3.StringUtils; import org.opendaylight.controller.config.api.DependencyResolver; import org.opendaylight.controller.config.api.DependencyResolverFactory; @@ -32,20 +43,6 @@ import org.opendaylight.controller.config.api.ModuleIdentifier; import org.osgi.framework.BundleContext; import org.slf4j.LoggerFactory; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.encoder.PatternLayoutEncoder; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.classic.spi.LoggerComparator; -import ch.qos.logback.core.Appender; -import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; -import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; -import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - /** * */ @@ -59,8 +56,8 @@ public class LogbackModuleFactory extends private Map fileDTOs; @Override - public LogbackModule instantiateModule(String instanceName, DependencyResolver dependencyResolver, - BundleContext bundleContext) { + public LogbackModule instantiateModule(final String instanceName, final DependencyResolver dependencyResolver, + final BundleContext bundleContext) { Preconditions.checkArgument(instanceName.equals(INSTANCE_NAME), "There should be just one instance of logback, named " + INSTANCE_NAME); prepareDTOs(); @@ -74,8 +71,8 @@ public class LogbackModuleFactory extends } @Override - public LogbackModule instantiateModule(String instanceName, DependencyResolver dependencyResolver, - LogbackModule oldModule, AutoCloseable oldInstance, BundleContext bundleContext) { + public LogbackModule instantiateModule(final String instanceName, final DependencyResolver dependencyResolver, + final LogbackModule oldModule, final AutoCloseable oldInstance, final BundleContext bundleContext) { Preconditions.checkArgument(instanceName.equals(INSTANCE_NAME), "There should be just one instance of logback, named " + INSTANCE_NAME); prepareDTOs(); @@ -97,7 +94,7 @@ public class LogbackModuleFactory extends prepareAppendersDTOs(context); } - private void prepareAppendersDTOs(LoggerContext context) { + private void prepareAppendersDTOs(final LoggerContext context) { this.rollingDTOs = new HashMap<>(); this.consoleDTOs = new HashMap<>(); this.fileDTOs = new HashMap<>(); @@ -131,7 +128,7 @@ public class LogbackModuleFactory extends app.setFileNamePattern(rollingPolicy.getFileNamePattern()); app.setRollingPolicyType("FixedWindowRollingPolicy"); } else if (rollingApp.getRollingPolicy() instanceof TimeBasedRollingPolicy) { - TimeBasedRollingPolicy rollingPolicy = (TimeBasedRollingPolicy) rollingApp.getRollingPolicy(); + TimeBasedRollingPolicy rollingPolicy = (TimeBasedRollingPolicy) rollingApp.getRollingPolicy(); app.setRollingPolicyType("TimeBasedRollingPolicy"); app.setFileNamePattern(rollingPolicy.getFileNamePattern()); app.setMaxHistory(rollingPolicy.getMaxHistory()); @@ -166,7 +163,7 @@ public class LogbackModuleFactory extends } } - private Map prepareLoggersDTOs(LoggerContext context) { + private Map prepareLoggersDTOs(final LoggerContext context) { Map DTOs = new HashMap<>(); List appenders = new ArrayList<>(); List loggersToBeAdd = removeUnusableLoggers(context.getLoggerList(), @@ -192,7 +189,7 @@ public class LogbackModuleFactory extends return DTOs; } - private List removeUnusableLoggers(List loggerList, Logger rootLogger) { + private List removeUnusableLoggers(final List loggerList, final Logger rootLogger) { Collections.sort(loggerList, new LoggerComparator()); Map loggersToReturn = new HashMap<>(); @@ -234,8 +231,8 @@ public class LogbackModuleFactory extends } @Override - public Set getDefaultModules(DependencyResolverFactory dependencyResolverFactory, - BundleContext bundleContext) { + public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, + final BundleContext bundleContext) { DependencyResolver resolver = dependencyResolverFactory.createDependencyResolver(new ModuleIdentifier( getImplementationName(), INSTANCE_NAME)); LogbackModule defaultLogback = instantiateModule(INSTANCE_NAME, resolver, bundleContext); diff --git a/opendaylight/config/logback-config/src/test/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleTest.java b/opendaylight/config/logback-config/src/test/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleTest.java index 75323d256e..9e07cc68cb 100644 --- a/opendaylight/config/logback-config/src/test/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleTest.java +++ b/opendaylight/config/logback-config/src/test/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleTest.java @@ -7,9 +7,9 @@ */ package org.opendaylight.controller.config.yang.logback.config; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; import java.util.ArrayList; import java.util.Arrays; diff --git a/opendaylight/config/netconf-config-dispatcher/src/main/java/org/opendaylight/controller/config/yang/config/netconf/client/dispatcher/NetconfClientDispatcherModule.java b/opendaylight/config/netconf-config-dispatcher/src/main/java/org/opendaylight/controller/config/yang/config/netconf/client/dispatcher/NetconfClientDispatcherModule.java index 344ef3dec3..0a10c2d3a8 100644 --- a/opendaylight/config/netconf-config-dispatcher/src/main/java/org/opendaylight/controller/config/yang/config/netconf/client/dispatcher/NetconfClientDispatcherModule.java +++ b/opendaylight/config/netconf-config-dispatcher/src/main/java/org/opendaylight/controller/config/yang/config/netconf/client/dispatcher/NetconfClientDispatcherModule.java @@ -12,8 +12,7 @@ import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl; /** * */ -public final class NetconfClientDispatcherModule extends org.opendaylight.controller.config.yang.config.netconf.client.dispatcher.AbstractNetconfClientDispatcherModule - { +public final class NetconfClientDispatcherModule extends org.opendaylight.controller.config.yang.config.netconf.client.dispatcher.AbstractNetconfClientDispatcherModule { public NetconfClientDispatcherModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { super(identifier, dependencyResolver); diff --git a/opendaylight/config/netty-timer-config/src/test/java/org/opendaylight/controller/config/yang/netty/timer/HashedWheelTimerModuleTest.java b/opendaylight/config/netty-timer-config/src/test/java/org/opendaylight/controller/config/yang/netty/timer/HashedWheelTimerModuleTest.java index 5fe5f9496e..578476f0f7 100644 --- a/opendaylight/config/netty-timer-config/src/test/java/org/opendaylight/controller/config/yang/netty/timer/HashedWheelTimerModuleTest.java +++ b/opendaylight/config/netty-timer-config/src/test/java/org/opendaylight/controller/config/yang/netty/timer/HashedWheelTimerModuleTest.java @@ -7,12 +7,11 @@ */ package org.opendaylight.controller.config.yang.netty.timer; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.ObjectName; - -import junit.framework.Assert; - import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.config.api.ConflictingVersionException; @@ -42,9 +41,9 @@ public class HashedWheelTimerModuleTest extends AbstractConfigTest { try { createInstance(transaction, instanceName, 0L, 10, true); transaction.validateConfig(); - Assert.fail(); + fail(); } catch (ValidationException e) { - Assert.assertTrue(e.getMessage().contains("TickDuration value must be greater than 0")); + assertTrue(e.getMessage().contains("TickDuration value must be greater than 0")); } } @@ -53,9 +52,9 @@ public class HashedWheelTimerModuleTest extends AbstractConfigTest { try { createInstance(transaction, instanceName, 500L, 0, true); transaction.validateConfig(); - Assert.fail(); + fail(); } catch (ValidationException e) { - Assert.assertTrue(e.getMessage().contains("TicksPerWheel value must be greater than 0")); + assertTrue(e.getMessage().contains("TicksPerWheel value must be greater than 0")); } } @@ -112,7 +111,7 @@ public class HashedWheelTimerModuleTest extends AbstractConfigTest { assertStatus(status, 0, 1, 1); } - private ObjectName createInstance(ConfigTransactionJMXClient transaction, String instanceName, + private ObjectName createInstance(final ConfigTransactionJMXClient transaction, final String instanceName, final Long tickDuration, final Integer ticksPerWheel, final boolean hasThreadfactory) throws InstanceAlreadyExistsException { ObjectName nameCreated = transaction.createModule(factory.getImplementationName(), instanceName); @@ -126,7 +125,7 @@ public class HashedWheelTimerModuleTest extends AbstractConfigTest { return nameCreated; } - private ObjectName createThreadfactoryInstance(ConfigTransactionJMXClient transaction, String instanceName, + private ObjectName createThreadfactoryInstance(final ConfigTransactionJMXClient transaction, final String instanceName, final String namePrefix) throws InstanceAlreadyExistsException { ObjectName nameCreated = transaction.createModule(threadFactory.getImplementationName(), instanceName); NamingThreadFactoryModuleMXBean mxBean = transaction.newMBeanProxy(nameCreated, diff --git a/opendaylight/config/pom.xml b/opendaylight/config/pom.xml index ea7b243179..ad2607a8db 100644 --- a/opendaylight/config/pom.xml +++ b/opendaylight/config/pom.xml @@ -41,6 +41,8 @@ netconf-config-dispatcher config-module-archetype config-netty-config + + config-artifacts diff --git a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModuleFactory.java b/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModuleFactory.java index 4df9b036f1..1994e21a6d 100644 --- a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModuleFactory.java +++ b/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModuleFactory.java @@ -5,26 +5,16 @@ * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ -/** - * Generated file - - * Generated from: yang module name: shutdown-impl yang module local name: shutdown - * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator - * Generated at: Wed Dec 18 14:02:06 CET 2013 - * - * Do not modify this file unless it is present under src/main directory - */ package org.opendaylight.controller.config.yang.shutdown.impl; +import java.util.Arrays; +import java.util.Set; import org.opendaylight.controller.config.api.DependencyResolver; import org.opendaylight.controller.config.api.DependencyResolverFactory; import org.opendaylight.controller.config.api.ModuleIdentifier; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; -import java.util.Arrays; -import java.util.Set; - public class ShutdownModuleFactory extends AbstractShutdownModuleFactory { public ShutdownModule instantiateModule(String instanceName, DependencyResolver dependencyResolver, diff --git a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownServiceImpl.java b/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownServiceImpl.java index 4abbd3b36f..7d97fcd964 100644 --- a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownServiceImpl.java +++ b/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownServiceImpl.java @@ -8,15 +8,14 @@ package org.opendaylight.controller.config.yang.shutdown.impl; import com.google.common.base.Optional; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; import org.opendaylight.controller.config.shutdown.ShutdownService; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; - public class ShutdownServiceImpl implements ShutdownService, AutoCloseable { private final ShutdownService impl; private final ShutdownRuntimeRegistration registration; @@ -42,7 +41,7 @@ public class ShutdownServiceImpl implements ShutdownService, AutoCloseable { } class Impl implements ShutdownService { - private static final Logger logger = LoggerFactory.getLogger(Impl.class); + private static final Logger LOG = LoggerFactory.getLogger(Impl.class); private final String secret; private final Bundle systemBundle; @@ -53,27 +52,27 @@ class Impl implements ShutdownService { @Override public void shutdown(String inputSecret, Long maxWaitTime, Optional reason) { - logger.warn("Shutdown issued with secret {} and reason {}", inputSecret, reason); + LOG.warn("Shutdown issued with secret {} and reason {}", inputSecret, reason); try { Thread.sleep(1000); // prevent brute force attack } catch (InterruptedException e) { Thread.currentThread().interrupt(); - logger.warn("Shutdown process interrupted", e); + LOG.warn("Shutdown process interrupted", e); } if (this.secret.equals(inputSecret)) { - logger.info("Server is shutting down"); + LOG.info("Server is shutting down"); // actual work: Thread stopSystemBundleThread = new StopSystemBundleThread(systemBundle); stopSystemBundleThread.start(); if (maxWaitTime != null && maxWaitTime > 0) { Thread systemExitThread = new CallSystemExitThread(maxWaitTime); - logger.debug("Scheduling {}", systemExitThread); + LOG.debug("Scheduling {}", systemExitThread); systemExitThread.start(); } // end } else { - logger.warn("Unauthorized attempt to shut down server"); + LOG.warn("Unauthorized attempt to shut down server"); throw new IllegalArgumentException("Invalid secret"); } } @@ -81,7 +80,7 @@ class Impl implements ShutdownService { } class StopSystemBundleThread extends Thread { - private static final Logger logger = LoggerFactory.getLogger(StopSystemBundleThread.class); + private static final Logger LOG = LoggerFactory.getLogger(StopSystemBundleThread.class); private final Bundle systemBundle; StopSystemBundleThread(Bundle systemBundle) { @@ -94,18 +93,18 @@ class StopSystemBundleThread extends Thread { try { // wait so that JMX response is received Thread.sleep(1000); - logger.debug("Stopping system bundle"); + LOG.debug("Stopping system bundle"); systemBundle.stop(); } catch (BundleException e) { - logger.warn("Can not stop OSGi server", e); + LOG.warn("Can not stop OSGi server", e); } catch (InterruptedException e) { - logger.warn("Shutdown process interrupted", e); + LOG.warn("Shutdown process interrupted", e); } } } class CallSystemExitThread extends Thread { - private static final Logger logger = LoggerFactory.getLogger(CallSystemExitThread.class); + private static final Logger LOG = LoggerFactory.getLogger(CallSystemExitThread.class); private final long maxWaitTime; CallSystemExitThread(long maxWaitTime) { super("call-system-exit-daemon"); @@ -128,7 +127,7 @@ class CallSystemExitThread extends Thread { try { // wait specified time Thread.sleep(maxWaitTime); - logger.error("Since some threads are still running, server is going to shut down via System.exit(1) !"); + LOG.error("Since some threads are still running, server is going to shut down via System.exit(1) !"); // do a thread dump ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true); StringBuffer sb = new StringBuffer(); @@ -136,10 +135,10 @@ class CallSystemExitThread extends Thread { sb.append(info); sb.append("\n"); } - logger.warn("Thread dump:{}", sb); + LOG.warn("Thread dump:{}", sb); System.exit(1); } catch (InterruptedException e) { - logger.warn("Interrupted, not going to call System.exit(1)"); + LOG.warn("Interrupted, not going to call System.exit(1)"); } } } diff --git a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/async/AsyncEventBusConfigBeanTest.java b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/async/AsyncEventBusConfigBeanTest.java index 0b339fc600..92b81220ff 100644 --- a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/async/AsyncEventBusConfigBeanTest.java +++ b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/async/AsyncEventBusConfigBeanTest.java @@ -7,9 +7,9 @@ */ package org.opendaylight.controller.config.threadpool.async; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; import javax.management.InstanceAlreadyExistsException; import javax.management.ObjectName; diff --git a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/eventbus/SyncEventBusConfigBeanTest.java b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/eventbus/SyncEventBusConfigBeanTest.java index aeb6d6b959..6d0449cf5a 100644 --- a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/eventbus/SyncEventBusConfigBeanTest.java +++ b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/eventbus/SyncEventBusConfigBeanTest.java @@ -20,10 +20,10 @@ import org.opendaylight.controller.config.yang.threadpool.impl.EventBusModuleFac import javax.management.InstanceAlreadyExistsException; import javax.management.ObjectName; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; public class SyncEventBusConfigBeanTest extends AbstractConfigTest { diff --git a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/fixed/FixedThreadPoolConfigBeanTest.java b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/fixed/FixedThreadPoolConfigBeanTest.java index 62b295be8d..f968e287c2 100644 --- a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/fixed/FixedThreadPoolConfigBeanTest.java +++ b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/fixed/FixedThreadPoolConfigBeanTest.java @@ -7,10 +7,10 @@ */ package org.opendaylight.controller.config.threadpool.fixed; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; diff --git a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/flexible/FlexibleThreadPoolConfigBeanTest.java b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/flexible/FlexibleThreadPoolConfigBeanTest.java index a1d1c40655..9ae721ee87 100644 --- a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/flexible/FlexibleThreadPoolConfigBeanTest.java +++ b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/flexible/FlexibleThreadPoolConfigBeanTest.java @@ -24,9 +24,9 @@ import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.ObjectName; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; public class FlexibleThreadPoolConfigBeanTest extends AbstractConfigTest { diff --git a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/naming/NamingThreadPoolFactoryConfigBeanTest.java b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/naming/NamingThreadPoolFactoryConfigBeanTest.java index 499beced5f..be3d59bf39 100644 --- a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/naming/NamingThreadPoolFactoryConfigBeanTest.java +++ b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/naming/NamingThreadPoolFactoryConfigBeanTest.java @@ -7,11 +7,11 @@ */ package org.opendaylight.controller.config.threadpool.naming; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; diff --git a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/scheduled/ScheduledThreadPoolConfigBeanTest.java b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/scheduled/ScheduledThreadPoolConfigBeanTest.java index 0fc2fd6eb3..6482fe9c1b 100644 --- a/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/scheduled/ScheduledThreadPoolConfigBeanTest.java +++ b/opendaylight/config/threadpool-config-impl/src/test/java/org/opendaylight/controller/config/threadpool/scheduled/ScheduledThreadPoolConfigBeanTest.java @@ -7,11 +7,11 @@ */ package org.opendaylight.controller.config.threadpool.scheduled; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TemplateFactory.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TemplateFactory.java index f8f5cd6742..ca1e823ec7 100644 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TemplateFactory.java +++ b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TemplateFactory.java @@ -607,9 +607,8 @@ public class TemplateFactory { String varName = BindingGeneratorUtil .parseToValidParamName(attrEntry.getKey()); - { - ModuleField field; + ModuleField field; if (isIdentity) { String identityBaseClass = getInnerTypeFromIdentity(((TypedAttribute) attributeIfc).getType()); IdentityRefModuleField identityField = new IdentityRefModuleField(type, varName, @@ -641,7 +640,8 @@ public class TemplateFactory { nullableDefaultWrapped, isDependency, dependency, isListOfDependencies, needsDepResolver); } moduleFields.add(field); - } + + String getterName = "get" + attributeIfc.getUpperCaseCammelCase(); MethodDefinition getter = new MethodDefinition(type, diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java index 33546b1e2a..2378fac6e7 100644 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java +++ b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java @@ -318,11 +318,11 @@ public class AbsModuleGeneratedObjectFactory { .append("}\n"); } else { result.append(format( - "private %s %sDependency;\n"+ - "protected final %s get%sDependency(){\n"+ - "return %sDependency;\n"+ - "}", - osgi, moduleField.getName(), osgi, moduleField.getAttributeName(), moduleField.getName())); + "private %s %sDependency;\n"+ + "protected final %s get%sDependency(){\n"+ + "return %sDependency;\n"+ + "}", + osgi, moduleField.getName(), osgi, moduleField.getAttributeName(), moduleField.getName())); } } } diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorFileNamesValidationTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorFileNamesValidationTest.java index e33f1cddc4..cdff5090bb 100644 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorFileNamesValidationTest.java +++ b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorFileNamesValidationTest.java @@ -7,11 +7,11 @@ */ package org.opendaylight.controller.config.yangjmxgenerator.plugin; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; import org.junit.Test; import org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants; diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorGeneratedFilesTrackerTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorGeneratedFilesTrackerTest.java index 4112ff017a..589fe41f46 100644 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorGeneratedFilesTrackerTest.java +++ b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorGeneratedFilesTrackerTest.java @@ -7,10 +7,8 @@ */ package org.opendaylight.controller.config.yangjmxgenerator.plugin; +import static org.junit.Assert.assertEquals; import java.io.File; - -import junit.framework.Assert; - import org.junit.Test; public class JMXGeneratorGeneratedFilesTrackerTest { @@ -20,7 +18,7 @@ public class JMXGeneratorGeneratedFilesTrackerTest { JMXGenerator.GeneratedFilesTracker tracker = new JMXGenerator.GeneratedFilesTracker(); tracker.addFile(new File("./a/b/c")); - Assert.assertEquals(1, tracker.getFiles().size()); + assertEquals(1, tracker.getFiles().size()); tracker.addFile(new File("./a/b/c")); } } diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorTest.java index 864ebdf954..42112013e9 100644 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorTest.java +++ b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorTest.java @@ -7,6 +7,7 @@ */ package org.opendaylight.controller.config.yangjmxgenerator.plugin; +import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; @@ -15,7 +16,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Dependency.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Dependency.java index b3e7b90c96..6ea2ea1724 100644 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Dependency.java +++ b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Dependency.java @@ -10,43 +10,43 @@ package org.opendaylight.controller.config.yangjmxgenerator.attribute; import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry; public class Dependency { - private final ServiceInterfaceEntry sie; - private final boolean mandatory; + private final ServiceInterfaceEntry sie; + private final boolean mandatory; - public Dependency(ServiceInterfaceEntry sie, boolean mandatory) { - this.sie = sie; - this.mandatory = mandatory; - } + public Dependency(ServiceInterfaceEntry sie, boolean mandatory) { + this.sie = sie; + this.mandatory = mandatory; + } - public ServiceInterfaceEntry getSie() { - return sie; - } + public ServiceInterfaceEntry getSie() { + return sie; + } - public boolean isMandatory() { - return mandatory; - } + public boolean isMandatory() { + return mandatory; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; - Dependency that = (Dependency) o; + Dependency that = (Dependency) o; - if (mandatory != that.mandatory) - return false; - if (!sie.equals(that.sie)) - return false; + if (mandatory != that.mandatory) + return false; + if (!sie.equals(that.sie)) + return false; - return true; - } - - @Override - public int hashCode() { - int result = sie.hashCode(); - result = 31 * result + (mandatory ? 1 : 0); - return result; - } + return true; + } + + @Override + public int hashCode() { + int result = sie.hashCode(); + result = 31 * result + (mandatory ? 1 : 0); + return result; } +} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractYangTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractYangTest.java index b9f2ba9cd1..e3c3a3024c 100644 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractYangTest.java +++ b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractYangTest.java @@ -7,8 +7,7 @@ */ package org.opendaylight.controller.config.yangjmxgenerator; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.format; +import static org.junit.Assert.assertNotNull; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @@ -92,8 +91,8 @@ public abstract class AbstractYangTest { QName qName = identitySchemaNode.getQName(); Preconditions.checkArgument( result.containsKey(qName) == false, - format("Two identities of %s contain same " + "qname %s", - module, qName)); + "Two identities of %s contain same qname %s", + module, qName); result.put(qName, identitySchemaNode); } return result; diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntryTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntryTest.java index e80ebc67a5..38b0a3afec 100644 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntryTest.java +++ b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntryTest.java @@ -7,10 +7,10 @@ */ package org.opendaylight.controller.config.yangjmxgenerator; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.assertNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/SchemaContextTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/SchemaContextTest.java index 1837bac266..b72d85c118 100644 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/SchemaContextTest.java +++ b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/SchemaContextTest.java @@ -95,7 +95,7 @@ public class SchemaContextTest extends AbstractYangTest { } } assertEquals("Expected identities not found " + copyOfExpectedNames, - Collections.EMPTY_MAP, copyOfExpectedNames); + Collections.emptyMap(), copyOfExpectedNames); } @Test diff --git a/opendaylight/config/yang-test/src/test/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleTest.java b/opendaylight/config/yang-test/src/test/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleTest.java index 13a31f5976..fb9264749b 100644 --- a/opendaylight/config/yang-test/src/test/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleTest.java +++ b/opendaylight/config/yang-test/src/test/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleTest.java @@ -9,8 +9,6 @@ package org.opendaylight.controller.config.yang.test.impl; import com.google.common.collect.Lists; -import junit.framework.Assert; - import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.config.api.IdentityAttributeRef; @@ -96,7 +94,7 @@ public class NetconfTestImplModuleTest extends AbstractConfigTest { List testingDeps = proxy.getTestingDeps(); ObjectName testingDep = proxy.getTestingDep(); - Assert.assertEquals(TESTING_DEP_PREFIX, ObjectNameUtil.getInstanceName(testingDep)); + assertEquals(TESTING_DEP_PREFIX, ObjectNameUtil.getInstanceName(testingDep)); assertTestingDeps(testingDeps, 4); transaction.abortConfig(); @@ -135,11 +133,11 @@ public class NetconfTestImplModuleTest extends AbstractConfigTest { } private void assertTestingDeps(List testingDeps, int i) { - Assert.assertEquals(i, testingDeps.size()); + assertEquals(i, testingDeps.size()); int c = 1; for (ObjectName testingDep : testingDeps) { - Assert.assertEquals(TESTING_DEP_PREFIX + Integer.toString(c++), ObjectNameUtil.getInstanceName(testingDep)); + assertEquals(TESTING_DEP_PREFIX + Integer.toString(c++), ObjectNameUtil.getInstanceName(testingDep)); } } diff --git a/opendaylight/distribution/opendaylight-karaf-empty/pom.xml b/opendaylight/distribution/opendaylight-karaf-empty/pom.xml index 72eaf005ad..a66a502a70 100644 --- a/opendaylight/distribution/opendaylight-karaf-empty/pom.xml +++ b/opendaylight/distribution/opendaylight-karaf-empty/pom.xml @@ -156,7 +156,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - ${checkstyle.version} **\/target\/,**\/bin\/,**\/target-ide\/,**\/configuration\/initial\/ diff --git a/opendaylight/distribution/opendaylight-karaf/pom.xml b/opendaylight/distribution/opendaylight-karaf/pom.xml index 3a2f4b0580..e44b569759 100644 --- a/opendaylight/distribution/opendaylight-karaf/pom.xml +++ b/opendaylight/distribution/opendaylight-karaf/pom.xml @@ -221,7 +221,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - ${checkstyle.version} **\/target\/,**\/bin\/,**\/target-ide\/,**\/configuration\/initial\/ diff --git a/opendaylight/distribution/opendaylight/opendaylight-application.launch b/opendaylight/distribution/opendaylight/opendaylight-application.launch deleted file mode 100644 index cd9fc94343..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-application.launch +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-assembleit-fast.launch b/opendaylight/distribution/opendaylight/opendaylight-assembleit-fast.launch deleted file mode 100644 index bc5c53ca95..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-assembleit-fast.launch +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-assembleit-full.launch b/opendaylight/distribution/opendaylight/opendaylight-assembleit-full.launch deleted file mode 100644 index 82b9fe22d0..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-assembleit-full.launch +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-assembleit-noclean.launch b/opendaylight/distribution/opendaylight/opendaylight-assembleit-noclean.launch deleted file mode 100644 index f42f6577f0..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-assembleit-noclean.launch +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-assembleit-skiput.launch b/opendaylight/distribution/opendaylight/opendaylight-assembleit-skiput.launch deleted file mode 100644 index 753839c0bb..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-assembleit-skiput.launch +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-assembleit-sonar.launch b/opendaylight/distribution/opendaylight/opendaylight-assembleit-sonar.launch deleted file mode 100644 index b498f908f2..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-assembleit-sonar.launch +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-assembleit.launch b/opendaylight/distribution/opendaylight/opendaylight-assembleit.launch deleted file mode 100644 index 0edd2a734a..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-assembleit.launch +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-local.target b/opendaylight/distribution/opendaylight/opendaylight-local.target deleted file mode 100644 index a7780fe610..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-local.target +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-osgi-launcher-local.launch b/opendaylight/distribution/opendaylight/opendaylight-osgi-launcher-local.launch deleted file mode 100644 index 98de065c5b..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-osgi-launcher-local.launch +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-osgi-launcher.launch b/opendaylight/distribution/opendaylight/opendaylight-osgi-launcher.launch deleted file mode 100644 index b14197f3d6..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-osgi-launcher.launch +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-sonar-fast.launch b/opendaylight/distribution/opendaylight/opendaylight-sonar-fast.launch deleted file mode 100644 index 6d5a588441..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-sonar-fast.launch +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight-sonar.launch b/opendaylight/distribution/opendaylight/opendaylight-sonar.launch deleted file mode 100644 index bb66bd8a92..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight-sonar.launch +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/opendaylight.target b/opendaylight/distribution/opendaylight/opendaylight.target deleted file mode 100644 index 7ae309cce4..0000000000 --- a/opendaylight/distribution/opendaylight/opendaylight.target +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/pom.xml b/opendaylight/distribution/opendaylight/pom.xml deleted file mode 100644 index e30ff05bf0..0000000000 --- a/opendaylight/distribution/opendaylight/pom.xml +++ /dev/null @@ -1,1455 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.5.0-SNAPSHOT - ../../commons/opendaylight - - distribution.opendaylight - 0.2.0-SNAPSHOT - pom - - 3.0 - - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - - com.fasterxml.jackson.core - jackson-annotations - - - - com.fasterxml.jackson.core - jackson-core - - - - com.fasterxml.jackson.core - jackson-databind - - - - com.fasterxml.jackson.datatype - jackson-datatype-json-org - - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-base - - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - - - - com.google.code.gson - gson - - - com.google.guava - guava - - - com.sun.jersey - jersey-client - - - - com.sun.jersey - jersey-core - - - com.sun.jersey - jersey-server - - - commons-codec - commons-codec - - - commons-fileupload - commons-fileupload - - - commons-io - commons-io - - - commons-net - commons-net - - - eclipselink - javax.persistence - - - eclipselink - javax.resource - - - equinoxSDK381 - javax.servlet - - - equinoxSDK381 - javax.servlet.jsp - - - equinoxSDK381 - org.apache.felix.gogo.command - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - equinoxSDK381 - org.apache.felix.gogo.shell - - - equinoxSDK381 - org.eclipse.equinox.cm - - - equinoxSDK381 - org.eclipse.equinox.console - - - equinoxSDK381 - org.eclipse.equinox.ds - - - equinoxSDK381 - org.eclipse.equinox.launcher - - - equinoxSDK381 - org.eclipse.equinox.util - - - equinoxSDK381 - org.eclipse.osgi - - - equinoxSDK381 - org.eclipse.osgi.services - - - - geminiweb - org.eclipse.gemini.web.core - - - geminiweb - org.eclipse.gemini.web.extender - - - geminiweb - org.eclipse.gemini.web.tomcat - - - geminiweb - org.eclipse.virgo.kernel.equinox.extensions - - - geminiweb - org.eclipse.virgo.util.common - - - geminiweb - org.eclipse.virgo.util.io - - - geminiweb - org.eclipse.virgo.util.math - - - geminiweb - org.eclipse.virgo.util.osgi - - - geminiweb - org.eclipse.virgo.util.osgi.manifest - - - geminiweb - org.eclipse.virgo.util.parser.manifest - - - io.netty - netty-buffer - - - io.netty - netty-codec - - - io.netty - netty-codec-http - - - io.netty - netty-common - - - - - io.netty - netty-handler - - - io.netty - netty-transport - - - orbit - javax.activation - - - orbit - javax.annotation - - - orbit - javax.ejb - - - orbit - javax.el - - - orbit - javax.mail.glassfish - - - orbit - javax.servlet.jsp.jstl - - - orbit - javax.servlet.jsp.jstl.impl - - - orbit - javax.xml.rpc - - - orbit - org.apache.catalina - - - orbit - org.apache.catalina.ha - - - orbit - org.apache.catalina.tribes - - - orbit - org.apache.coyote - - - orbit - org.apache.el - - - orbit - org.apache.jasper - - - orbit - org.apache.juli.extras - - - orbit - org.apache.tomcat.api - - - orbit - org.apache.tomcat.util - - - org.aopalliance - com.springsource.org.aopalliance - - - org.apache.commons - commons-lang3 - - - org.apache.felix - org.apache.felix.dependencymanager - - - org.apache.felix - org.apache.felix.dependencymanager.shell - - - org.apache.felix - org.apache.felix.fileinstall - - - - org.apache.felix - org.apache.felix.webconsole - all - - - - org.codehaus.jettison - jettison - - - - org.eclipse.equinox.http - servlet - - - org.eclipse.persistence - org.eclipse.persistence.antlr - - - org.eclipse.persistence - org.eclipse.persistence.core - - - org.eclipse.persistence - org.eclipse.persistence.moxy - - - org.javassist - javassist - - - org.jboss.spec.javax.transaction - jboss-transaction-api_1.1_spec - - - org.jolokia - jolokia-osgi - - - - org.json - json - - - org.opendaylight.controller - appauth - - - org.opendaylight.controller - arphandler - - - org.opendaylight.controller - bundlescanner - - - org.opendaylight.controller - bundlescanner.implementation - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.services-implementation - - - - - org.opendaylight.controller - clustering.test - - - org.opendaylight.controller - commons.httpclient - - - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - connectionmanager.implementation - - - org.opendaylight.controller - connectionmanager.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.implementation - - - org.opendaylight.controller - containermanager.northbound - - - org.opendaylight.controller - controllermanager.northbound - - - org.opendaylight.controller - devices.web - - - org.opendaylight.controller - flowprogrammer.northbound - - - org.opendaylight.controller - flows.web - - - org.opendaylight.controller - forwarding.staticrouting - - - org.opendaylight.controller - forwarding.staticrouting.northbound - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - forwardingrulesmanager.implementation - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - hosttracker.implementation - - - org.opendaylight.controller - hosttracker.northbound - - - org.opendaylight.controller - httpservice-bridge - - - org.opendaylight.controller - jolokia-bridge - - - - - org.opendaylight.controller - logging.bridge - - - org.opendaylight.controller - networkconfig.bridgedomain.northbound - - - - - org.opendaylight.controller - networkconfig.neutron - - - org.opendaylight.controller - networkconfig.neutron.implementation - - - org.opendaylight.controller - networkconfig.neutron.northbound - - - org.opendaylight.controller - osgi-brandfragment.web - - - - - org.opendaylight.controller - protocol_plugins.openflow - - - org.opendaylight.controller - routing.dijkstra_implementation - - - - - org.opendaylight.controller - sal - - - - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - sal.connection.implementation - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - sal.networkconfiguration - - - org.opendaylight.controller - sal.networkconfiguration.implementation - - - - - org.opendaylight.controller - samples.loadbalancer - - - org.opendaylight.controller - samples.loadbalancer.northbound - - - org.opendaylight.controller - samples.simpleforwarding - - - org.opendaylight.controller - security - - - org.opendaylight.controller - statistics.northbound - - - org.opendaylight.controller - statisticsmanager - - - org.opendaylight.controller - statisticsmanager.implementation - - - org.opendaylight.controller - subnets.northbound - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - switchmanager.northbound - - - org.opendaylight.controller - topology.northbound - - - org.opendaylight.controller - topology.web - - - org.opendaylight.controller - topologymanager - - - org.opendaylight.controller - troubleshoot.web - - - org.opendaylight.controller - usermanager - - - org.opendaylight.controller - usermanager.implementation - - - org.opendaylight.controller - usermanager.northbound - - - - - - org.opendaylight.controller - web - - - org.opendaylight.controller.thirdparty - com.sun.jersey.jersey-servlet - - - - - org.opendaylight.controller.thirdparty - net.sf.jung2 - - - org.opendaylight.controller.thirdparty - org.openflow.openflowj - - - - org.ow2.asm - asm-all - - - - org.ow2.chameleon.management - chameleon-mbeans - - - - - org.slf4j - jcl-over-slf4j - - - org.slf4j - log4j-over-slf4j - - - org.slf4j - slf4j-api - - - org.springframework - org.springframework.aop - - - - org.springframework - org.springframework.asm - - - org.springframework - org.springframework.beans - - - org.springframework - org.springframework.context - - - org.springframework - org.springframework.context.support - - - org.springframework - org.springframework.core - - - org.springframework - org.springframework.expression - - - org.springframework - org.springframework.transaction - - - org.springframework - org.springframework.web - - - org.springframework - org.springframework.web.servlet - - - - org.springframework.security - spring-security-config - - - org.springframework.security - spring-security-core - - - org.springframework.security - spring-security-taglibs - - - org.springframework.security - spring-security-web - - - virgomirror - org.eclipse.jdt.core.compiler.batch - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.8 - - - unpack-provided-configs - - unpack-dependencies - - generate-resources - - ${project.build.directory}/configuration - sal-rest-connector-config,config-netty-config,md-sal-config,netconf-config,toaster-config,netconf-connector-config,sal-clustering-config - **\/*.xml,**/*.conf - true - false - - - - - - maven-assembly-plugin - 2.3 - - - distro-assembly - - single - - package - - - src/assemble/bin.xml - - ${project.artifactId} - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle.version} - - **\/target\/,**\/bin\/,**\/target-ide\/,**\/configuration\/initial\/ - - - - org.codehaus.mojo - buildnumber-maven-plugin - 1.2 - - false - false - VersionUnknown - - - - - create - - validate - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - - - - notduringrelease - - - !DOINGRELEASE - - - - - ${project.groupId} - ietf-netconf-monitoring - - - ${project.groupId} - ietf-netconf-monitoring-extension - - - commons-lang - commons-lang - 2.4 - - - org.apache.servicemix.bundles - org.apache.servicemix.bundles.xerces - 2.11.0_1 - - - org.bouncycastle - bcpkix-jdk15on - - - org.bouncycastle - bcprov-jdk15on - - - org.eclipse.birt.runtime.3_7_1 - org.apache.xml.resolver - 1.2.0 - - - org.opendaylight.controller - concepts - - - - - org.opendaylight.controller - config-api - - - org.opendaylight.controller - config-manager - - - org.opendaylight.controller - config-util - - - org.opendaylight.controller - config-netconf-connector - - - org.opendaylight.controller - config-persister-api - - - org.opendaylight.controller - config-persister-directory-xml-adapter - - - org.opendaylight.controller - config-persister-file-xml-adapter - - - org.opendaylight.controller - config-persister-impl - - - org.opendaylight.controller - filter-valve - - - org.opendaylight.controller - logback-config - - - - - org.opendaylight.controller - netconf-api - - - org.opendaylight.controller - netconf-client - - - - - org.opendaylight.controller - netconf-config-dispatcher - - - org.opendaylight.controller - netconf-impl - - - org.opendaylight.controller - netconf-mapping-api - - - org.opendaylight.controller - netconf-monitoring - - - org.opendaylight.controller - netconf-netty-util - - - org.opendaylight.controller - netconf-ssh - - - org.opendaylight.controller - netconf-auth - - - org.opendaylight.controller - netconf-usermanager - - - org.opendaylight.controller - netconf-tcp - - - org.opendaylight.controller - netconf-util - - - org.opendaylight.controller - netty-config-api - - - org.opendaylight.controller - netty-event-executor-config - - - org.opendaylight.controller - netty-threadgroup-config - - - org.opendaylight.controller - netty-timer-config - - - org.opendaylight.controller - protocol-framework - - - - org.opendaylight.controller - sal-binding-api - - - org.opendaylight.controller - sal-binding-broker-impl - - - org.opendaylight.controller - sal-binding-config - - - org.opendaylight.controller - sal-binding-util - - - org.opendaylight.controller - sal-broker-impl - - - - org.opendaylight.controller - sal-common - - - org.opendaylight.controller - sal-common-api - - - org.opendaylight.controller - sal-common-impl - - - org.opendaylight.controller - sal-common-util - - - org.opendaylight.controller - sal-compatibility - - - org.opendaylight.controller - sal-connector-api - - - org.opendaylight.controller - sal-core-api - - - org.opendaylight.controller - sal-core-spi - - - org.opendaylight.controller - sal-inmemory-datastore - 1.2.0-SNAPSHOT - - - org.opendaylight.controller - sal-netconf-connector - - - org.opendaylight.controller - sal-remote - - - org.opendaylight.controller - sal-rest-connector - - - org.opendaylight.controller - sal-rest-connector-config - - - org.opendaylight.controller - config-netty-config - - - org.opendaylight.controller - md-sal-config - - - org.opendaylight.controller - netconf-config - - - org.opendaylight.controller - netconf-connector-config - - - org.opendaylight.controller.samples - toaster-config - - - org.opendaylight.controller - sal-rest-docgen - - - org.opendaylight.controller - sal-restconf-broker - - - - - org.opendaylight.controller - shutdown-api - - - org.opendaylight.controller - shutdown-impl - - - - - org.opendaylight.controller - threadpool-config-api - - - org.opendaylight.controller - threadpool-config-impl - - - org.opendaylight.controller - yang-jmx-generator - - - org.opendaylight.controller.md - forwardingrules-manager - - - org.opendaylight.controller.md - inventory-manager - - - org.opendaylight.controller.md - statistics-manager - - - org.opendaylight.controller.md - topology-lldp-discovery - - - org.opendaylight.controller - liblldp - - - org.opendaylight.controller.md - topology-manager - - - org.opendaylight.controller.model - model-flow-base - - - org.opendaylight.controller.model - model-flow-service - - - org.opendaylight.controller.model - model-flow-statistics - - - org.opendaylight.controller.model - model-inventory - - - org.opendaylight.controller.model - model-topology - 1.2.0-SNAPSHOT - - - - - org.opendaylight.controller.samples - sample-toaster - ${mdsal.version} - - - org.opendaylight.controller.samples - sample-toaster-consumer - ${mdsal.version} - - - org.opendaylight.controller.samples - sample-toaster-provider - ${mdsal.version} - - - org.opendaylight.controller.thirdparty - ganymed - - - org.apache.sshd - sshd-core - - - org.opendaylight.yangtools - binding-generator-api - ${yangtools.version} - - - org.opendaylight.yangtools - binding-generator-impl - - - org.opendaylight.yangtools - binding-data-codec - - - org.opendaylight.yangtools - binding-generator-spi - - - org.opendaylight.yangtools - binding-generator-util - - - org.opendaylight.yangtools - binding-model-api - ${yangtools.version} - - - org.opendaylight.yangtools - binding-type-provider - - - org.opendaylight.yangtools - concepts - - - org.opendaylight.yangtools - object-cache-api - - - org.opendaylight.yangtools - object-cache-guava - - - org.opendaylight.yangtools - restconf-client-api - - - org.opendaylight.yangtools - restconf-client-impl - - - org.opendaylight.yangtools - util - - - - org.opendaylight.yangtools - yang-binding - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.yangtools - yang-data-api - - - org.opendaylight.yangtools - yang-data-impl - - - org.opendaylight.yangtools - yang-data-util - - - org.opendaylight.yangtools - yang-model-api - - - org.opendaylight.yangtools - yang-model-util - - - org.opendaylight.yangtools - yang-parser-api - - - org.opendaylight.yangtools - yang-parser-impl - - - org.opendaylight.yangtools - yang-data-codec-gson - - - org.opendaylight.yangtools - yang-data-composite-node - - - - org.opendaylight.yangtools.model - ietf-inet-types - - - org.opendaylight.yangtools.model - ietf-restconf - - - org.opendaylight.yangtools.model - ietf-topology - - - org.opendaylight.yangtools.model - ietf-yang-types - - - org.opendaylight.yangtools.model - ietf-yang-types-20130715 - - - org.opendaylight.yangtools.model - opendaylight-l2-types - - - org.opendaylight.yangtools.model - yang-ext - - - - org.opendaylight.yangtools.thirdparty - antlr4-runtime-osgi-nohead - 4.0 - - - org.opendaylight.yangtools.thirdparty - xtend-lib-osgi - 2.4.3 - - - org.openexi - nagasena - - - org.openexi - nagasena-rta - - - org.zeromq - jeromq - 0.3.1 - - - org.opendaylight.controller - sal-clustering-config - - - org.eclipse.jetty - jetty-servlets - 8.1.14.v20131031 - - - org.eclipse.jetty - jetty-client - 8.1.14.v20131031 - - - org.eclipse.jetty - jetty-continuation - 8.1.14.v20131031 - - - org.eclipse.jetty - jetty-util - 8.1.14.v20131031 - - - org.eclipse.jetty - jetty-server - 8.1.14.v20131031 - - - org.eclipse.jetty - jetty-io - 8.1.14.v20131031 - - - org.eclipse.jetty - jetty-http - 8.1.14.v20131031 - - - - - integrationtests - - false - - - - org.opendaylight.controller - sanitytest - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.8 - - - - org.opendaylight.controller - sanitytest - jar - - - - - - org.opendaylight.controller - sanitytest - ${sanitytest.version} - - - - - copy - - copy - - package - - - unpack-provided-configs - - unpack-dependencies - - generate-resources - - ${project.build.directory}/configuration - sal-rest-connector-config,config-netty-config,md-sal-config,netconf-config,toaster-config,netconf-connector-config,sal-clustering-config - **\/*.xml,**/*.conf - true - false - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - ${java.home}/bin/java - - -cp - ./target/dependency/* - org.opendaylight.controller.distribution.Sanity - - - ${java.home} - - - - - sanity-test - - exec - - package - - - - - - - - docs - - false - - - - org.opendaylight.controller - swagger-ui - 0.1.0-SNAPSHOT - - - - - diff --git a/opendaylight/distribution/opendaylight/runsanity.bat b/opendaylight/distribution/opendaylight/runsanity.bat deleted file mode 100644 index f219828bad..0000000000 --- a/opendaylight/distribution/opendaylight/runsanity.bat +++ /dev/null @@ -1,23 +0,0 @@ -rem Inject the sanitytest jar as a controller plugin -copy .\target\dependency\sanitytest*.jar .\target\distribution.opendaylight-osgipackage\opendaylight\plugins - -rem Store the current working directory in a variable so that we can get back to it later -set cwd=%cd% - -rem Switch to the distribution folder -cd .\target\distribution.opendaylight-osgipackage\opendaylight - -rem Run the controller -cmd.exe /c run.bat - -rem Store the exit value of the controller in a variable -set success=%ERRORLEVEL% - -rem Switch back to the directory from which this script was invoked -cd %cwd% - -rem Remove the sanitytest jar from the plugins directory -del .\target\distribution.opendaylight-osgipackage\opendaylight\plugins\sanitytest*.jar - -rem Exit using the exit code that we had captured earlier after running the controller -exit /b %SUCCESS% \ No newline at end of file diff --git a/opendaylight/distribution/opendaylight/runsanity.sh b/opendaylight/distribution/opendaylight/runsanity.sh deleted file mode 100755 index 4ee9555b97..0000000000 --- a/opendaylight/distribution/opendaylight/runsanity.sh +++ /dev/null @@ -1,24 +0,0 @@ -# Inject the sanitytest jar as a controller plugin -cp ./target/dependency/sanitytest*.jar ./target/distribution.opendaylight-osgipackage/opendaylight/plugins - -# Store the current working directory in a variable so that we can get back to it later -cwd=`pwd` - -# Switch to the distribution folder -cd ./target/distribution.opendaylight-osgipackage/opendaylight/ - -# Run the controller -./run.sh - -# Store the exit value of the controller in a variable -success=`echo $?` - -# Switch back to the directory from which this script was invoked -cd $cwd - -# Remove the sanitytest jar from the plugins directory -rm ./target/distribution.opendaylight-osgipackage/opendaylight/plugins/sanitytest*.jar - -# Exit using the exit code that we had captured earlier after running the controller -exit $success - diff --git a/opendaylight/distribution/opendaylight/src/assemble/bin.xml b/opendaylight/distribution/opendaylight/src/assemble/bin.xml deleted file mode 100644 index e5fc98a863..0000000000 --- a/opendaylight/distribution/opendaylight/src/assemble/bin.xml +++ /dev/null @@ -1,98 +0,0 @@ - - osgipackage - - dir - zip - - false - - - opendaylight/plugins - - equinoxSDK381:org.eclipse.osgi - equinoxSDK381:org.eclipse.equinox.console - equinoxSDK381:org.eclipse.equinox.launcher - equinoxSDK381:org.eclipse.equinox.ds - equinoxSDK381:org.eclipse.equinox.util - equinoxSDK381:org.eclipse.osgi.services - virgomirror:org.eclipse.jdt.core.compiler.batch - org.apache.felix:org.apache.felix.fileinstall - geminiweb:org.eclipse.virgo.kernel.equinox.extensions - org.slf4j:slf4j-api - ch.qos.logback:logback-core - ch.qos.logback:logback-classic - com.sun.jersey:jersey-core - com.sun.jersey:jersey-server - org.opendaylight.controller:logging.bridge - org.opendaylight.controller:sanitytest - - - ${artifact.groupId}.${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension} - - false - runtime - false - - - opendaylight/lib - - equinoxSDK381:org.eclipse.osgi - equinoxSDK381:org.eclipse.equinox.console - equinoxSDK381:org.eclipse.equinox.launcher - equinoxSDK381:org.eclipse.equinox.ds - equinoxSDK381:org.eclipse.equinox.util - equinoxSDK381:org.eclipse.osgi.services - virgomirror:org.eclipse.jdt.core.compiler.batch - org.apache.felix:org.apache.felix.fileinstall - geminiweb:org.eclipse.virgo.kernel.equinox.extensions - org.slf4j:slf4j-api - ch.qos.logback:logback-core - ch.qos.logback:logback-classic - com.sun.jersey:jersey-core - com.sun.jersey:jersey-server - org.opendaylight.controller:logging.bridge - - false - - ${artifact.artifactId}-${artifact.version}${dashClassifier?}.${artifact.extension} - - false - runtime - - - - - - src/main/resources/ - - - version.properties - configuration/config.ini - - - opendaylight/ - - - - ${project.build.directory}/configuration/initial - /opendaylight/configuration/initial - - **/META-INF/** - - - - - - src/main/resources/version.properties - opendaylight - true - - - src/main/resources/configuration/config.ini - opendaylight/configuration - true - - - diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/config.ini b/opendaylight/distribution/opendaylight/src/main/resources/configuration/config.ini deleted file mode 100644 index 691d83d45e..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/config.ini +++ /dev/null @@ -1,163 +0,0 @@ -osgi.bundles=\ - reference\:file\:../lib/org.apache.felix.fileinstall-3.1.6.jar@1:start,\ - reference\:file\:../lib/org.eclipse.jdt.core.compiler.batch-3.8.0.I20120518-2145.jar@1:start,\ - reference\:file\:../lib/org.eclipse.equinox.ds-1.4.0.v20120522-1841.jar@2:start,\ - reference\:file\:../lib/org.eclipse.equinox.util-1.0.400.v20120522-2049.jar@2:start,\ - reference\:file\:../lib/org.eclipse.osgi.services-3.3.100.v20120522-1822@2:start,\ - reference\:file\:../lib/org.eclipse.equinox.console-1.0.0.v20120522-1841.jar@start,\ - reference\:file\:../lib/slf4j-api-1.7.2.jar@1:start,\ - reference\:file\:../lib/logback-classic-1.0.9.jar@1:start,\ - reference\:file\:../lib/logback-core-1.0.9.jar@1:start,\ - reference\:file\:../lib/logging.bridge-${logging.bridge.version}@1:start,\ - reference\:file\:../lib/jersey-core-1.17.jar@2:start,\ - reference\:file\:../lib/jersey-server-1.17.jar@2:start - -# Netconf startup configuration - -# Netconf tcp address:port is optional -#netconf.tcp.address=127.0.0.1 -#netconf.tcp.port=8383 - -# Netconf tcp address:port is optional -netconf.ssh.address=0.0.0.0 -netconf.ssh.port=1830 -netconf.ssh.pk.path = ./configuration/RSA.pk -netconf.ssh.default.user = netconf -netconf.ssh.default.password = netconf - - -netconf.config.persister.active=1,2 -# read startup configuration -netconf.config.persister.1.storageAdapterClass=org.opendaylight.controller.config.persist.storage.directory.xml.XmlDirectoryStorageAdapter -netconf.config.persister.1.properties.directoryStorage=configuration/initial/ -# include only xml files, files with other extensions will be skipped, multiple extensions are permitted e.g. netconf.config.persister.1.properties.includeExtensions=xml,cfg,config -netconf.config.persister.1.properties.includeExtensions=xml -netconf.config.persister.1.readonly=true - -netconf.config.persister.2.storageAdapterClass=org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter -netconf.config.persister.2.properties.fileStorage=configuration/current/controller.currentconfig.xml -netconf.config.persister.2.properties.numberOfBackups=1 - -# Set Default start level for framework -osgi.bundles.defaultStartLevel=4 -# Extra packages to import from the boot class loader -org.osgi.framework.system.packages.extra=sun.reflect,sun.reflect.misc,sun.misc,sun.nio.ch -# This is not Eclipse App -eclipse.ignoreApp=true -# Don't shutdown equinox if the eclipse App has ended, -# which is our case because we are not running any eclipse application -osgi.noShutdown=true -# Clean any cached data on restart of the framework -osgi.clean=true - -# https://bugs.eclipse.org/bugs/show_bug.cgi?id=325578 -# Extend the framework to avoid the resources to be presented with -# a URL of type bundleresource: but to be presented as file: -osgi.hook.configurators.include=org.eclipse.virgo.kernel.equinox.extensions.hooks.ExtensionsHookConfigurator - -# Directory from where the fileinstall will monitor for new bundles -felix.fileinstall.dir=./plugins -# Immediately learn new bundles at startup -felix.fileinstall.noInitialDelay=true -# Auto start the bundles at level 4 -felix.fileinstall.start.level=4 -# Avoid to auto-install following bundles, that means those need -# to be started manually or in other way like osgi.bundles -felix.fileinstall.filter=^(?!org.apache.felix.fileinstall).* - -# logback configuration -logback.configurationFile=configuration/logback.xml - -# Container configuration -container.profile = Container - -# Connection manager configuration -connection.scheme = ANY_CONTROLLER_ONE_MASTER - -# Embedded Tomcat configuration File -org.eclipse.gemini.web.tomcat.config.path=configuration/tomcat-server.xml -org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true - -# Open Flow related system parameters -# TCP port on which the controller is listening (default 6633) -# of.listenPort=6633 -# IP address of the controller (default: wild card) -# of.address = 127.0.0.1 -# The time (in milliseconds) the controller will wait for a response after sending a Barrier Request or a Statistic Request message (default 2000 msec) -# of.messageResponseTimer=2000 -# The switch liveness timeout value (default 60500 msec) -# of.switchLivenessTimeout=60500 -# The size of the queue holding pending statistics requests (default 64). For large networks of n switches, it is recommended to set the queue size to n -# of.statsQueueSize = 64 -# The flow statistics polling interval in second (default 10 sec) -# of.flowStatsPollInterval=10 -# The port statistics polling interval in second (default 5 sec) -# of.portStatsPollInterval=5 -# The description statistics polling interval in second (default 60 sec) -# of.descStatsPollInterval=60 -# The table statistics polling interval in second (default 10 sec) -# of.tableStatsPollInterval=10 -# The maximum number of asynchronous messages can be sent before sending a Barrier Request (default 100) -# of.barrierMessagePriorCount=100 -# The interval which determines how often the discovery packets should be sent (default 300 sec) -# of.discoveryInterval=300 -# The timeout multiple of discovery interval -# of.discoveryTimeoutMultiple=2 -# For newly added ports, allow one more retry if the elapsed time exceeds this threshold (default 30 sec) -# of.discoveryThreshold=30 -# The maximum number of ports handled in one discovery batch (default 512) -# of.discoveryBatchMaxPorts=512 - -# OVSDB configuration -# ovsdb plugin supports both active and passive connections. It listens on port 6640 by default for Active connections. -ovsdb.listenPort=6640 - -# ovsdb creates Openflow nodes/bridges. This configuration configures the bridge's Openflow version. -# default Openflow version = 1.3, we also support 1.0. -ovsdb.of.version=1.3 - -# ovsdb can be configured with ml2 to perform l3 forwarding. The config below enables that functionality, which is -# disabled by default. -# ovsdb.l3.fwd.enabled=yes - -# ovsdb can be configured with ml2 to perform l3 forwarding. When used in that scenario, the mac address of the default -# gateway --on the external subnet-- is expected to be resolved from its inet address. The config below overrides that -# specific arp/neighDiscovery lookup. -# ovsdb.l3gateway.mac=00:00:5E:00:02:01 - -# TLS configuration -# To enable TLS, set secureChannelEnabled=true and specify the location of controller Java KeyStore and TrustStore files. -# The Java KeyStore contains controller's private key and certificate. The Java TrustStore contains the trusted certificate -# entries, including switches' Certification Authority (CA) certificates. For example, -# secureChannelEnabled=true -# controllerKeyStore=./configuration/ctlKeyStore -# controllerKeyStorePassword=xxxxxxxx (this password should match the password used for KeyStore generation and at least 6 characters) -# controllerTrustStore=./configuration/ctlTrustStore -# controllerTrustStorePassword=xxxxxxxx (this password should match the password used for TrustStore generation and at least 6 characters) - -secureChannelEnabled=false -controllerKeyStore= -controllerKeyStorePassword= -controllerTrustStore= -controllerTrustStorePassword= - -# User Manager configurations -enableStrongPasswordCheck = false - -#Jolokia configurations -org.jolokia.listenForHttpService=false - -# Logging configuration for Tomcat-JUL logging -java.util.logging.config.file=configuration/tomcat-logging.properties - -#Hosttracker hostsdb key scheme setting -hosttracker.keyscheme=IP - -# LISP Flow Mapping configuration -# Map-Register messages overwrite existing RLOC sets in EID-to-RLOC mappings -lisp.mappingOverwrite = true -# Enable the Solicit-Map-Request (SMR) mechanism -lisp.smr = false - -#RESTConf websocket listen port (default is 8181) -restconf.websocket.port=8181 diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/context.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/context.xml deleted file mode 100644 index 90b9ddf1c8..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/context.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/cors-config.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/cors-config.xml deleted file mode 100644 index c148b83a7a..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/cors-config.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, - origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - - - CorsFilter - - - - - CorsFilter - /* - - - - - - CorsFilter - - - - - CorsFilter - /* - - - - - diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/logback.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/logback.xml deleted file mode 100644 index b73244bc0a..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/logback.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - - - %date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{36} %X{akkaSource} - %msg%n - - - - logs/opendaylight.log - - - logs/opendaylight.%d.log.zip - 1 - - - - 10MB - - - - %date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level %logger{35} - %msg%n - - - - logs/audit.log - true - - %date{"yyyy-MM-dd HH:mm:ss.SSS z"} %msg %n - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/startup/README b/opendaylight/distribution/opendaylight/src/main/resources/configuration/startup/README deleted file mode 100644 index 2da70fff1e..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/startup/README +++ /dev/null @@ -1 +0,0 @@ -Directory where the opendaylight controller modules store their configuration files diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/tomcat-logging.properties b/opendaylight/distribution/opendaylight/src/main/resources/configuration/tomcat-logging.properties deleted file mode 100644 index 3dbd9921b3..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/tomcat-logging.properties +++ /dev/null @@ -1,42 +0,0 @@ -############################################################ -# Configuration file for tomcat logging -############################################################ -# Handlers: -# "handlers" specifies a comma separated list of log Handler -# classes. These handlers will be installed during VM startup. -# Note that these classes must be on the system classpath. -# Following line configures a ConsoleHandler and a FileHandler - -handlers= java.util.logging.FileHandler,java.util.logging.ConsoleHandler - -############################################################ -# Handler specific properties -# Describes specific configuration info for Handlers -# JUL does not support rolling file handler based on date -# For now we will keep count of files to 5 with rolling size of 10MB -############################################################ - -java.util.logging.FileHandler.pattern = logs/tomcat%g.log -java.util.logging.FileHandler.limit = 104857600 -java.util.logging.FileHandler.count = 5 -java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter -java.util.logging.FileHandler.append = true -java.util.logging.FileHandler.level = INFO - -# Limit the message that are printed on the console to SEVERE and above. -java.util.logging.ConsoleHandler.level = WARNING -java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter - -# SimpleFormatter output format to print one-line log message like this: -# --
:: [] > -# -java.util.logging.SimpleFormatter.format=%1$tF %1$tT %1$tZ [%3$s] %4$s %2$s %5$s%6$s%n - -############################################################ -# Facility specific properties. -# Provides extra control for each logger. -############################################################ - -# For example, set the com.xyz.foo logger to only log SEVERE -# messages -#org.apache.catalina = SEVERE diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/tomcat-server.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/tomcat-server.xml deleted file mode 100644 index da2500be62..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/configuration/tomcat-server.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/opendaylight/src/main/resources/functions.sh b/opendaylight/distribution/opendaylight/src/main/resources/functions.sh deleted file mode 100644 index 21dd4c16ba..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/functions.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -# Function harvestHelp searches in run.sh part for line starting with "##". -# Next lines starting with "#" will be printed without first char # (=help content). -# Help content has to end with "##" on new line. -# Example: -##foo -# Foo is world wide used synnonym for bar. -## -function harvestHelp() { - key="$1" - if [ -z "${key}" ]; then - key='HELP' - fi - echo - sed -rn "/^##${key}$/,/^##/ p" $0 | sed -r '1 d; $ d; s/^#/ /' - grep "##${key}" $0 > /dev/null -} diff --git a/opendaylight/distribution/opendaylight/src/main/resources/run.bat b/opendaylight/distribution/opendaylight/src/main/resources/run.bat deleted file mode 100644 index ce13e33968..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/run.bat +++ /dev/null @@ -1,280 +0,0 @@ -@ECHO OFF -SETLOCAL ENABLEDELAYEDEXPANSION - -IF NOT EXIST "%JAVA_HOME%" ( - ECHO JAVA_HOME environment variable is not set - EXIT /B 2 -) - -SET basedir=%~dp0 -SET debugport=8000 -SET consoleport=2400 -SET jmxport=1088 -SET jvmMaxMemory= -SET extraJVMOpts= -SET consoleOpts=-console -consoleLog -SET PID= -SET JAVA_H=%JAVA_HOME%\bin\jps.exe - -:LOOP -IF "%~1" NEQ "" ( - SET CARG=%~1 - IF "!CARG!"=="-debug" ( - SET debugEnabled=true - SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-debugsuspend" ( - SET debugEnabled=true - SET debugSuspended=true - SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-debugport" ( - SET debugEnabled=true - SET debugport=%~2 - SHIFT & SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-jmx" ( - SET jmxEnabled=true - SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-jmxport" ( - SET jmxEnabled=true - SET jmxport=%~2 - SHIFT & SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-start" ( - SET startEnabled=true - SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-consoleport" ( - SET consoleport=%~2 - SHIFT & SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-console" ( - SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-status" ( - for /F "TOKENS=1" %%G in ('""!JAVA_H!" -lvV ^| find /I "opendaylight""') do ( - set PID=%%G - ) - if "!PID!" NEQ "" ( - ECHO Controller is running with PID !PID! - ) else ( - ECHO Controller is not running. - ) - GOTO :EOF - ) - IF "!CARG!"=="-stop" ( - for /F "TOKENS=1" %%G in ('""!JAVA_H!" -lvV ^| find /I "opendaylight""') do ( - set PID=%%G - ) - if "!PID!" NEQ "" ( - ECHO Stopping controller PID !PID! - TASKKILL /F /PID !PID! - ) else ( - ECHO Controller is not running. - ) - GOTO :EOF - ) - IF "!CARG:~0,4!"=="-Xmx" ( - SET jvmMaxMemory=!CARG! - SHIFT - GOTO :LOOP - ) - IF "!CARG:~0,2!"=="-D" ( - SET extraJVMOpts=!extraJVMOpts! !CARG! - SHIFT - GOTO :LOOP - ) - IF "!CARG:~0,2!"=="-X" ( - SET extraJVMOpts=!extraJVMOpts! !CARG! - SHIFT - GOTO :LOOP - ) - IF "!CARG!"=="-help" ( - SHIFT - SET CARG=%2 - IF "!CARG!" NEQ "" ( - CALL:!CARG! - ) ELSE ( - CALL:helper - ) - GOTO :EOF - ) - - ECHO "Unknown option: !CARG!" - EXIT /B 1 -) - -IF "%debugEnabled%" NEQ "" ( - REM ECHO "DEBUG enabled" - SET extraJVMOpts=!extraJVMOpts! -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=%debugport% -) - -IF "%debugSuspended%" NEQ "" ( - REM ECHO "DEBUG enabled suspended" - SET extraJVMOpts=!extraJVMOpts! -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=%debugport% -) - -IF "%jvmMaxMemory%"=="" ( - SET jvmMaxMemory=-Xmx1G - ECHO Setting maximum memory to 1G. -) - -SET extraJVMOpts=!extraJVMOpts! %jvmMaxMemory% - -IF "%jmxEnabled%" NEQ "" ( - REM ECHO "JMX enabled " - SET extraJVMOpts=!extraJVMOpts! -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=%jmxport% -Dcom.sun.management.jmxremote -) -IF "%startEnabled%" NEQ "" ( - REM ECHO "START enabled " - SET consoleOpts=-console %consoleport% -consoleLog -) - -REM Check if controller is already running -for /F "TOKENS=1" %%G in ('""!JAVA_H!" -lvV ^| find /I "opendaylight""') do ( - SET PID=%%G -) -if "!PID!" NEQ "" ( - ECHO Controller is already running with PID !PID! - EXIT /B 1 -) - - -REM Now set the classpath: -SET cp="%basedir%lib\org.eclipse.osgi-3.8.1.v20120830-144521.jar;%basedir%lib\org.eclipse.virgo.kernel.equinox.extensions-3.6.0.RELEASE.jar;%basedir%lib\org.eclipse.equinox.launcher-1.3.0.v20120522-1813.jar" - -REM Now set framework classpath -SET fwcp="file:\%basedir%lib\org.eclipse.osgi-3.8.1.v20120830-144521.jar,file:\%basedir%lib\org.eclipse.virgo.kernel.equinox.extensions-3.6.0.RELEASE.jar,file:\%basedir%lib\org.eclipse.equinox.launcher-1.3.0.v20120522-1813.jar" - -SET RUN_CMD="%JAVA_HOME%\bin\java.exe" -Dopendaylight.controller !extraJVMOpts! -Djava.io.tmpdir="%basedir%work\tmp" -Djava.awt.headless=true -Dosgi.install.area=%basedir% -Dosgi.configuration.area="%basedir%configuration" -Dosgi.frameworkClassPath=%fwcp% -Dosgi.framework="file:\%basedir%lib\org.eclipse.osgi-3.8.1.v20120830-144521.jar" -classpath %cp% org.eclipse.equinox.launcher.Main %consoleOpts% - -ECHO !RUN_CMD! - -if "%startEnabled%" NEQ "" ( - START /B cmd /C CALL !RUN_CMD! > %basedir%\logs\controller.out 2>&1 - ECHO Running controller in the background. - EXIT /B 1 -) else ( - !RUN_CMD! - EXIT /B %ERRORLEVEL% -) - -:helper -echo. For more information on a specific command, type -help command-name. -echo. -echo jmx ^[-jmx^] -echo jmxport ^[-jmxport ^^] - DEFAULT is 1088 -echo debug ^[-debug^] -echo debugsuspend ^[-debugsuspend^] -echo debugport ^[-debugport ^^] - DEFAULT is 8000 -echo start ^[-start ^[^^]^] - DEFAULT port is 2400 -echo stop ^[-stop^] -echo status ^[-status^] -echo console ^[-console^] -echo agentpath ^[-agentpath:^^] -exit/B 1 - -:debugsuspend -ECHO. -ECHO. debugsuspend ^[-debugsuspend^] -ECHO. -ECHO. This command sets suspend on true in runjdwp in extra JVM options. If its true, VMStartEvent has a suspendPolicy of SUSPEND_ALL. If its false, VMStartEvent has a suspendPolicy of SUSPEND_NONE. -ECHO. -EXIT /B 1 - -:debugport -ECHO. -ECHO. debugport ^[-debugport ^^] - DEFAULT is 8000 -ECHO. -ECHO. Set address for settings in runjdwp in extra JVM options. -ECHO. The address is transport address for the connection. -ECHO. The address has to be in the range ^[1024,65535^]. If the option was not call, port will be set to default value. -ECHO. -EXIT /B 1 - -:jmxport -ECHO. -ECHO. jmxport ^[-jmxport ^^] - DEFAULT is 1088 -ECHO. -ECHO. Set jmx port for com.sun.management.jmxremote.port in JMX support. Port has to be in the range ^[1024,65535^]. If this option was not call, port will be set to default value. -ECHO. -EXIT /B 1 - -:debug -ECHO. -ECHO. debug [-debug] -ECHO. -ECHO. Run ODL controller with -Xdebug and -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=^$^{debugport^} -ECHO. -ECHO. -Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. -ECHO. -ECHO. -Xrunjdwp option loads the JPDA reference implementation of JDWP. This library resides in the target VM and uses JVMDI and JNI to interact with it. It uses a transport and the JDWP protocol to communicate with a separate debugger application. -ECHO. -ECHO. settings for -Xrunjdwp: -ECHO. transport - name of the transport to use in connecting to debugger application -ECHO. server - if 'y', listen for a debugger application to attach; otherwise, attach to the debugger application at the specified address -ECHO. - if 'y' and no address is specified, choose a transport address at which to listen for a debugger application, and print the address to the standard output stream -ECHO. suspend - if 'y', VMStartEvent has a suspend Policy of SUSPEND_ALL -ECHO. - if 'n', VMStartEvent has a suspend policy of SUSPEND_NONE -ECHO. address - transport address for the connection -ECHO. - if server=n, attempt to attach to debugger application at this address -ECHO. - if server=y, listen for a connection at this address -ECHO. -EXIT /B 1 - -:jmx -ECHO. -ECHO. jmx [-jmx] -ECHO. -ECHO. Add JMX support. With settings for extra JVM options: -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=^$^{jmxport^} -Dcom.sun.management.jmxremote -ECHO. jmxport can by set with option -jmxport ^. Default num for the option is 1088. -ECHO. -EXIT /B 1 - -:stop -ECHO. -ECHO. stop ^[-stop^] -ECHO. -ECHO. If a controller is running, the command stop controller. Pid will be clean. -ECHO. -EXIT /B 1 - -:status -ECHO. -ECHO. status ^[-status^] -ECHO. -ECHO. Find out whether a controller is running and print it. -ECHO. -EXIT /B 1 - -:start -ECHO. -ECHO. start ^[-start ^[^^]^] -ECHO. -ECHO. If controller is not running, the command with argument^(for set port, where controller has start^) will start new controller on a port. The port has to be in the range ^[1024,65535^]. If this option was not call, port will be set to default value. Pid will be create. -EXIT /B 1 - -:console -ECHO. -ECHO. console [-console] -ECHO. Default option. -EXIT /B 1 - -:agentpath -ECHO. -ECHO. agentpath ^[-agentpath:^^] -ECHO. -ECHO. Agentpath option passes path to agent to jvm in order to load native agent library, e.g. yourkit profiler agent. -EXIT /B 1 - - diff --git a/opendaylight/distribution/opendaylight/src/main/resources/run.sh b/opendaylight/distribution/opendaylight/src/main/resources/run.sh deleted file mode 100755 index b032469b7f..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/run.sh +++ /dev/null @@ -1,331 +0,0 @@ -#!/bin/bash - -##HELP -# For more information on a specific command, type -help command-name. -# -# jmx [-jmx] -# jmxport [-jmxport ] - DEFAULT is 1088 -# debug [-debug] -# debugsuspend [-debugsuspend] -# debugport [-debugport ] - DEFAULT is 8000 -# start [-start []] - DEFAULT port is 2400 -# stop [-stop] -# status [-status] -# console [-console] -# agentpath [-agentpath:] -## - -platform='unknown' -unamestr=`uname` -if [[ "$unamestr" == 'Linux' ]]; then - platform='linux' -elif [[ "$unamestr" == 'Darwin' ]]; then - platform='osx' -fi - -if [[ $platform == 'linux' ]]; then - fullpath=`readlink -f $0` - - if [[ -z ${JAVA_HOME} ]]; then - # Find the actual location of the Java launcher: - java_launcher=`command -v java` - java_launcher=`readlink -f "${java_launcher}"` - - # Compute the Java home from the location of the Java launcher: - export JAVA_HOME="${java_launcher%/bin/java}" - fi -elif [[ $platform == 'osx' ]]; then - TARGET_FILE=$0 - cd `dirname "$TARGET_FILE"` - TARGET_FILE=`basename $TARGET_FILE` - - # Iterate down a (possible) chain of symlinks - while [ -L "$TARGET_FILE" ] - do - TARGET_FILE=`readlink "$TARGET_FILE"` - cd `dirname "$TARGET_FILE"` - TARGET_FILE=`basename "$TARGET_FILE"` - done - - # Compute the canonicalized name by finding the physical path - # for the directory we're in and appending the target file. - PHYS_DIR=`pwd -P` - RESULT=$PHYS_DIR/$TARGET_FILE - fullpath=$RESULT - - [[ -z ${JAVA_HOME} ]] && [[ -x "/usr/libexec/java_home" ]] && export JAVA_HOME=`/usr/libexec/java_home -v 1.7`; - -fi - -[[ -z ${JAVA_HOME} ]] && echo "Need to set JAVA_HOME environment variable" && exit -1; -[[ ! -x ${JAVA_HOME}/bin/java ]] && echo "Cannot find an executable \ -JVM at path ${JAVA_HOME}/bin/java check your JAVA_HOME" && exit -1; - -if [ -z ${ODL_BASEDIR} ]; then - basedir=`dirname "${fullpath}"` -else - basedir=${ODL_BASEDIR} -fi - -if [ -z ${ODL_DATADIR} ]; then - datadir=`dirname "${fullpath}"` -else - datadir=${ODL_DATADIR} -fi - -if [ -z ${TMP} ]; then - pidfile="/tmp/opendaylight.PID" -else - pidfile="${TMP}/opendaylight.PID" -fi -debug=0 -debugsuspend=0 -debugport=8000 -debugportread="" -startdaemon=0 -daemonport=2400 -daemonportread="" -jmxport=1088 -jmxportread="" -startjmx=0 -stopdaemon=0 -statusdaemon=0 -consolestart=1 -dohelp=0 -jvmMaxMemory="-Xmx1G" -extraJVMOpts="" -agentPath="" -unknown_option=0 -helper="" -while true ; do - case "$1" in - -debug) debug=1; shift ;; - -help) dohelp=1; shift; helper=$1; break ;; - -jmx) startjmx=1; shift ;; - -debugsuspend) debugsuspend=1; shift ;; - -debugport) shift; debugportread="$1"; if [[ "${debugportread}" =~ ^[0-9]+$ ]] ; then debugport=${debugportread}; shift; else echo "-debugport expects a number but was not found"; exit -1; fi;; - -jmxport) shift; jmxportread="$1"; if [[ "${jmxportread}" =~ ^[0-9]+$ ]] ; then jmxport=${jmxportread}; shift; else echo "-jmxport expects a number but was not found"; exit -1; fi;; - -start) startdaemon=1; shift; daemonportread="$1"; if [[ "${daemonportread}" =~ ^[0-9]+$ ]] ; then daemonport=${daemonportread}; shift; fi;; - -stop) stopdaemon=1; shift ;; - -status) statusdaemon=1; shift ;; - -console) shift ;; - -Xmx*) jvmMaxMemory="$1"; shift;; - -D*) extraJVMOpts="${extraJVMOpts} $1"; shift;; - -X*) extraJVMOpts="${extraJVMOpts} $1"; shift;; - -J*) extraJVMOpts="${extraJVMOpts} -$(echo "$1" | cut -d'J' -f2)"; shift;; - -agentpath:*) agentPath="$1"; shift;; - "") break ;; - *) echo "Unknown option $1"; unknown_option=1; break ;; - esac -done - - - -if [ "${unknown_option}" -eq 1 ]; then - echo "Use -help for more information." - exit 1 -fi - - -if [ "${dohelp}" -eq 1 ]; then - . ${basedir}/functions.sh - harvestHelp ${helper} - echo -e '\nFor other information type -help.\n' - exit 1 -fi - -extraJVMOpts="${extraJVMOpts} ${jvmMaxMemory}" - -##debugport -#debugport [-debugport ] - DEFAULT is 8000 -# -# Set address for settings in runjdwp in extra JVM options. -# The address is transport address for the connection. -# The address has to be in the range [1024,65535]. If this option was not call, port will be set to default value. -## -# Validate debug port -if [[ "${debugport}" -lt 1024 ]] || [[ "${debugport}" -gt 65535 ]]; then - echo "Debug Port not in the range [1024,65535] ${debugport}" - exit -1 -fi - -# Validate daemon console port -if [[ "${daemonport}" -lt 1024 ]] || [[ "${daemonport}" -gt 65535 ]]; then - echo "Daemon console Port not in the range [1024,65535] value is ${daemonport}" - exit -1 -fi - -##jmxport -#jmxport [-jmxport ] - DEFAULT is 1088 -# -# Set jmx port for com.sun.management.jmxremote.port in JMX support. Port has to be in the range [1024,65535]. If this option was not call, port will be set to default value. -## -# Validate jmx port -if [[ "${jmxport}" -lt 1024 ]] || [[ "${jmxport}" -gt 65535 ]]; then - echo "JMX Port not in the range [1024,65535] value is ${jmxport}" - exit -1 -fi -##debug -#debug [-debug] -# -#Run ODL controller with -Xdebug and -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=\${debugport} -#-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. -#-Xrunjdwp option loads the JPDA reference implementation of JDWP. This library resides in the target VM and uses JVMDI and JNI to interact with it. It uses a transport and the JDWP protocol to -#communicate with a separate debugger application. -#settings for -Xrunjdwp: -# transport - name of the transport to use in connecting to debugger application -# server - if “y”, listen for a debugger application to attach; otherwise, attach to the debugger application at the specified address -# - if “y” and no address is specified, choose a transport address at which to listen for a debugger application, and print the address to the standard output stream -# suspend - if “y”, VMStartEvent has a suspend Policy of SUSPEND_ALL -# - if “n”, VMStartEvent has a suspend policy of SUSPEND_NONE -# address - transport address for the connection -# - if server=n, attempt to attach to debugger application at this address -# - if server=y, listen for a connection at this address -## - -##debugsuspend -#debugsuspend [-debugsuspend] -# -#This command sets suspend on true in runjdwp in extra JVM options. If its true, VMStartEvent has a suspendPolicy of SUSPEND_ALL. If its false, VMStartEvent has a suspendPolicy of SUSPEND_NONE. -## -# Debug options -if [ "${debugsuspend}" -eq 1 ]; then - extraJVMOpts="${extraJVMOpts} -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${debugport}" -elif [ "${debug}" -eq 1 ]; then - extraJVMOpts="${extraJVMOpts} -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${debugport}" -fi -##jmx -#jmx [-jmx] -# -#Add JMX support. With settings for extra JVM options: -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=\${jmxport} -Dcom.sun.management.jmxremote -#jmxport can by set with command -jmxport . Default num for the option is 1088. -## -# Add JMX support -if [ "${startjmx}" -eq 1 ]; then - extraJVMOpts="${extraJVMOpts} -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=${jmxport} -Dcom.sun.management.jmxremote" -fi - -######################################## -# Now add to classpath the OSGi JAR -######################################## -CLASSPATH=${CLASSPATH}:${basedir}/lib/org.eclipse.osgi-3.8.1.v20120830-144521.jar -FWCLASSPATH=file:"${basedir}"/lib/org.eclipse.osgi-3.8.1.v20120830-144521.jar - -######################################## -# Now add the extensions -######################################## - -# Extension 1: this is used to be able to convert all the -# bundleresouce: URL in file: so packages that are not OSGi ready can -# still work. Notably this is the case for spring classes -CLASSPATH=${CLASSPATH}:${basedir}/lib/org.eclipse.virgo.kernel.equinox.extensions-3.6.0.RELEASE.jar -FWCLASSPATH=${FWCLASSPATH},file:${basedir}/lib/org.eclipse.virgo.kernel.equinox.extensions-3.6.0.RELEASE.jar - -######################################## -# Now add the launcher -######################################## -CLASSPATH=${CLASSPATH}:${basedir}/lib/org.eclipse.equinox.launcher-1.3.0.v20120522-1813.jar -FWCLASSPATH=${FWCLASSPATH},file:${basedir}/lib/org.eclipse.equinox.launcher-1.3.0.v20120522-1813.jar - -cd $basedir - -##stop -#stop [-stop] -# -#If a controller is running, the command stop controller. Pid will be clean. -## -if [ "${stopdaemon}" -eq 1 ]; then - if [ -e "${pidfile}" ]; then - daemonpid=`cat "${pidfile}"` - kill "${daemonpid}" - rm -f "${pidfile}" - echo "Controller with PID: ${daemonpid} -- Stopped!" - exit 0 - else - echo "Doesn't seem any Controller daemon is currently running" - exit -1 - fi -fi - -##status -#status [-status] -# -#Find out whether a controller is running and print it. -## -if [ "${statusdaemon}" -eq 1 ]; then - if [ -e "${pidfile}" ]; then - daemonpid=`cat "${pidfile}"` - ps -p ${daemonpid} > /dev/null - daemonexists=$? - if [ "${daemonexists}" -eq 0 ]; then - echo "Controller with PID: ${daemonpid} -- Running!" - exit 0 - else - echo "Controller with PID: ${daemonpid} -- Doesn't seem to exist" - rm -f "${pidfile}" - exit 1 - fi - else - echo "Doesn't seem any Controller daemon is currently running, at least no PID file has been found" - exit -1 - fi -fi - -iotmpdir=`echo "${datadir}" | sed 's/ /\\ /g'` -bdir=`echo "${basedir}" | sed 's/ /\\ /g'` -confarea=`echo "${datadir}" | sed 's/ /\\ /g'` -fwclasspath=`echo "${FWCLASSPATH}" | sed 's/ /\\ /g'` - -##start -#start [-start []] -# -# If controller is not running, the command with argument(for set port, where controller has start) will start new controller on a port. The port has to be in the range [1024,65535]. If this option was not call, port will be set to default value. Pid will be create. -## -##console -#console [-console] -# -# Default option. -## -##agentpath -#agentpath [-agentpath:] -# -# Agentpath option passes path to agent to jvm in order to load native agent library, e.g. yourkit profiler agent. -## -echo "JVM maximum memory was set to ${jvmMaxMemory}." -if [ "${startdaemon}" -eq 1 ]; then - if [ -e "${pidfile}" ]; then - echo "Another instance of controller running, check with $0 -status" - exit -1 - fi - $JAVA_HOME/bin/java ${extraJVMOpts} \ - ${agentPath} \ - -Djava.io.tmpdir="${iotmpdir}/work/tmp" \ - -Dosgi.install.area="${bdir}" \ - -Dosgi.configuration.area="${confarea}/configuration" \ - -Dosgi.frameworkClassPath="${fwclasspath}" \ - -Dosgi.framework=file:"${bdir}/lib/org.eclipse.osgi-3.8.1.v20120830-144521.jar" \ - -Djava.awt.headless=true \ - -classpath "${CLASSPATH}" \ - org.eclipse.equinox.launcher.Main \ - -console ${daemonport} \ - -consoleLog & - daemonpid=$! - echo ${daemonpid} > ${pidfile} -elif [ "${consolestart}" -eq 1 ]; then - if [ -e "${pidfile}" ]; then - echo "Another instance of controller running, check with $0 -status" - exit -1 - fi - $JAVA_HOME/bin/java ${extraJVMOpts} \ - ${agentPath} \ - -Djava.io.tmpdir="${iotmpdir}/work/tmp" \ - -Dosgi.install.area="${bdir}" \ - -Dosgi.configuration.area="${confarea}/configuration" \ - -Dosgi.frameworkClassPath="${fwclasspath}" \ - -Dosgi.framework=file:"${bdir}/lib/org.eclipse.osgi-3.8.1.v20120830-144521.jar" \ - -Djava.awt.headless=true \ - -classpath "${CLASSPATH}" \ - org.eclipse.equinox.launcher.Main \ - -console \ - -consoleLog -fi diff --git a/opendaylight/distribution/opendaylight/src/main/resources/version.properties b/opendaylight/distribution/opendaylight/src/main/resources/version.properties deleted file mode 100644 index 90af49dfc2..0000000000 --- a/opendaylight/distribution/opendaylight/src/main/resources/version.properties +++ /dev/null @@ -1,6 +0,0 @@ -org.opendaylight.controller.version = 0.1 -org.opendaylight.controller.build.scm.version = ${buildNumber} -org.opendaylight.controller.build.user = ${env.USER} -org.opendaylight.controller.build.workspace = ********** -org.opendaylight.controller.build.timestamp = ${timestamp} -org.opendaylight.controller.build.machine = ********** diff --git a/opendaylight/distribution/p2site/opendayligh-target-platform-p2site.launch b/opendaylight/distribution/p2site/opendayligh-target-platform-p2site.launch deleted file mode 100644 index d6e307f76c..0000000000 --- a/opendaylight/distribution/p2site/opendayligh-target-platform-p2site.launch +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/distribution/p2site/pom.xml b/opendaylight/distribution/p2site/pom.xml deleted file mode 100644 index 5a66a6191b..0000000000 --- a/opendaylight/distribution/p2site/pom.xml +++ /dev/null @@ -1,454 +0,0 @@ - - - 4.0.0 - - 3.0 - - - - - - - - - org.opendaylight.controller - commons.opendaylight - 1.5.0-SNAPSHOT - ../../commons/opendaylight - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - - - - reficio - ${nexusproxy}/repositories/reficioplugin/ - - - - org.opendaylight.controller - distribution.p2site - 0.2.0-SNAPSHOT - pom - - - - - org.reficio - p2-maven-plugin - 1.0.0 - - - default-cli - - true - - - org.slf4j:jcl-over-slf4j:${slf4j.version} - false - false - - - org.slf4j:slf4j-api:${slf4j.version} - false - false - - - org.slf4j:log4j-over-slf4j:${slf4j.version} - false - false - - - ch.qos.logback:logback-core:${logback.version} - false - false - - - ch.qos.logback:logback-classic:${logback.version} - false - false - - - org.codehaus.jackson:jackson-mapper-asl:${jackson.version} - false - false - - - org.codehaus.jackson:jackson-core-asl:${jackson.version} - false - false - - - org.codehaus.jackson:jackson-jaxrs:${jackson.version} - false - false - - - org.codehaus.jettison:jettison:1.3.3 - false - false - - - commons-io:commons-io:2.4 - false - false - - - commons-fileupload:commons-fileupload:1.2.2 - false - false - - - equinoxSDK381:javax.servlet:3.0.0.v201112011016 - false - false - - - equinoxSDK381:javax.servlet.jsp:2.2.0.v201112011158 - false - false - - - equinoxSDK381:org.eclipse.equinox.ds:1.4.0.v20120522-1841 - false - false - - - equinoxSDK381:org.eclipse.equinox.util:1.0.400.v20120522-2049 - false - false - - - equinoxSDK381:org.eclipse.osgi.services:3.3.100.v20120522-1822 - false - false - - - equinoxSDK381:org.eclipse.osgi:3.8.1.v20120830-144521 - false - false - - - equinoxSDK381:org.apache.felix.gogo.command:0.8.0.v201108120515 - false - false - - - equinoxSDK381:org.apache.felix.gogo.runtime:0.8.0.v201108120515 - false - false - - - equinoxSDK381:org.apache.felix.gogo.shell:0.8.0.v201110170705 - false - false - - - equinoxSDK381:org.eclipse.equinox.cm:1.0.400.v20120522-1841 - false - false - - - equinoxSDK381:org.eclipse.equinox.console:1.0.0.v20120522-1841 - false - false - - - equinoxSDK381:org.eclipse.equinox.launcher:1.3.0.v20120522-1813 - false - false - - - geminiweb:org.eclipse.gemini.web.core:${geminiweb.version} - false - false - - - geminiweb:org.eclipse.gemini.web.extender:${geminiweb.version} - false - false - - - geminiweb:org.eclipse.gemini.web.tomcat:${geminiweb.version} - false - false - - - geminiweb:org.eclipse.virgo.kernel.equinox.extensions:${virgo.version} - false - false - - - geminiweb:org.eclipse.virgo.util.common:${virgo.version} - false - false - - - geminiweb:org.eclipse.virgo.util.io:${virgo.version} - false - false - - - geminiweb:org.eclipse.virgo.util.math:${virgo.version} - false - false - - - geminiweb:org.eclipse.virgo.util.osgi:${virgo.version} - false - false - - - geminiweb:org.eclipse.virgo.util.osgi.manifest:${virgo.version} - false - false - - - geminiweb:org.eclipse.virgo.util.parser.manifest:${virgo.version} - false - false - - - org.apache.felix:org.apache.felix.dependencymanager:3.1.0 - false - false - - - org.apache.felix:org.apache.felix.dependencymanager.shell:3.0.1 - false - false - - - com.google.code.gson:gson:2.1 - false - false - - - org.jboss.spec.javax.transaction:jboss-transaction-api_1.1_spec:1.0.1.Final - false - false - - - org.apache.commons:commons-lang3:3.1 - false - false - - - virgomirror:org.eclipse.jdt.core.compiler.batch:3.8.0.I20120518-2145 - false - false - - - eclipselink:javax.persistence:2.0.4.v201112161009 - false - false - - - orbit:javax.activation:1.1.0.v201211130549 - false - false - - - orbit:javax.annotation:1.1.0.v201209060031 - false - false - - - orbit:javax.ejb:3.1.1.v201204261316 - false - false - - - orbit:javax.el:2.2.0.v201108011116 - false - false - - - orbit:javax.mail.glassfish:1.4.1.v201108011116 - false - false - - - orbit:javax.xml.rpc:1.1.0.v201005080400 - false - false - - - orbit:org.apache.catalina:7.0.32.v201211201336 - false - false - - - orbit:org.apache.catalina.ha:7.0.32.v201211201952 - false - false - - - orbit:org.apache.catalina.tribes:7.0.32.v201211201952 - false - false - - - orbit:org.apache.coyote:7.0.32.v201211201952 - false - false - - - orbit:org.apache.el:7.0.32.v201211081135 - false - false - - - orbit:org.apache.jasper:7.0.32.v201211201952 - false - false - - - orbit:org.apache.juli.extras:7.0.32.v201211081135 - false - false - - - orbit:org.apache.tomcat.api:7.0.32.v201211081135 - false - false - - - orbit:org.apache.tomcat.util:7.0.32.v201211201952 - false - false - - - orbit:javax.servlet.jsp.jstl:1.2.0.v201105211821 - false - false - - - orbit:javax.servlet.jsp.jstl.impl:1.2.0.v201210211230 - false - false - - - org.springframework:org.springframework.asm:${spring.version} - false - false - - - org.springframework:org.springframework.aop:${spring.version} - false - false - - - org.springframework:org.springframework.context:${spring.version} - false - false - - - org.springframework:org.springframework.context.support:${spring.version} - false - false - - - org.springframework:org.springframework.core:${spring.version} - false - false - - - org.springframework:org.springframework.beans:${spring.version} - false - false - - - org.springframework:org.springframework.expression:${spring.version} - false - false - - - org.springframework:org.springframework.web:${spring.version} - false - false - - - org.aopalliance:com.springsource.org.aopalliance:1.0.0 - false - false - - - org.springframework:org.springframework.web.servlet:${spring.version} - false - false - - - org.springframework.security:spring-security-config:${spring-security.version} - false - false - - - org.springframework.security:spring-security-core:${spring-security.version} - false - false - - - org.springframework.security:spring-security-web:${spring-security.version} - false - false - - - org.springframework.security:spring-security-taglibs:${spring-security.version} - false - false - - - org.springframework:org.springframework.transaction:${spring-security.version} - false - false - - - org.ow2.chameleon.management:chameleon-mbeans:1.0.0 - false - false - - - com.sun.jersey:jersey-core:${jersey.version} - false - false - - - com.sun.jersey:jersey-server:${jersey.version} - false - false - - - com.sun.jersey:jersey-client:${jersey.version} - false - false - - - com.sun.jersey:jersey-json:${jersey.version} - false - false - - - - - - - - org.mortbay.jetty - jetty-maven-plugin - 8.1.5.v20120716 - - 10 - ${basedir}/target/repository/ - - /site - - - - - - diff --git a/opendaylight/distribution/sanitytest/pom.xml b/opendaylight/distribution/sanitytest/pom.xml deleted file mode 100644 index 9955afa274..0000000000 --- a/opendaylight/distribution/sanitytest/pom.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.5.0-SNAPSHOT - ../../commons/opendaylight - - - sanitytest - 0.5.0-SNAPSHOT - bundle - - - org.osgi - org.osgi.core - provided - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sanitytest - javax.xml.bind.annotation, - org.osgi.service.component, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.eclipse.osgi.baseadaptor, - org.eclipse.osgi.framework.adaptor, - org.osgi.framework.wiring - org.opendaylight.controller.sanitytest.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/distribution/sanitytest/src/main/java/org/opendaylight/controller/distribution/Sanity.java b/opendaylight/distribution/sanitytest/src/main/java/org/opendaylight/controller/distribution/Sanity.java deleted file mode 100644 index 9e6d43a06b..0000000000 --- a/opendaylight/distribution/sanitytest/src/main/java/org/opendaylight/controller/distribution/Sanity.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.distribution; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import java.util.ArrayList; -import java.util.List; - -public class Sanity { - - static void copy(InputStream in, OutputStream out) throws IOException { - while (true) { - int c = in.read(); - if (c == -1) break; - out.write((char)c); - } - } - - public static void main(String[] args) throws IOException, InterruptedException { - String cwd = System.getProperty("user.dir"); - - System.out.println("Current working directory = " + cwd); - - String os = System.getProperty("os.name").toLowerCase(); - List script = new ArrayList(); - - if(os.contains("windows")){ - script.add("cmd.exe"); - script.add("/c"); - script.add("runsanity.bat"); - } else { - script.add("./runsanity.sh"); - } - - ProcessBuilder processBuilder = new ProcessBuilder(); - processBuilder.inheritIO().command(script); - Process p = processBuilder.start(); - - copy(p.getInputStream(), System.out); - - p.waitFor(); - - System.out.println("Test exited with exitValue = " + p.exitValue()); - - System.exit(p.exitValue()); - } -} diff --git a/opendaylight/distribution/sanitytest/src/main/java/org/opendaylight/controller/sanitytest/internal/Activator.java b/opendaylight/distribution/sanitytest/src/main/java/org/opendaylight/controller/sanitytest/internal/Activator.java deleted file mode 100644 index 60db1b31e6..0000000000 --- a/opendaylight/distribution/sanitytest/src/main/java/org/opendaylight/controller/sanitytest/internal/Activator.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sanitytest.internal; - -import java.util.Timer; -import java.util.TimerTask; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.wiring.BundleRevision; - -public class Activator implements BundleActivator { - //10 Second initial, 1 second subsequent - private static final int INITIAL_DELAY = 10000; - private static final int SUBSEQUENT_DELAY = 1000; - private static final int MAX_ATTEMPTS = 120; - - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - case Bundle.STARTING: - return "STARTING"; - default: - return "Not CONVERTED: state value is " + state; - } - } - - public void start(final BundleContext bundleContext) throws Exception { - Timer monitorTimer = new Timer("monitor timer", true); - monitorTimer.schedule(new TimerTask() { - @Override - public void run() { - int countup = 0; - boolean failed = false; - boolean resolved = false; - while (!resolved) { - resolved = true; - failed = false; - for(Bundle bundle : bundleContext.getBundles()){ - /* - * A bundle should be ACTIVE, unless it a fragment, in which case it should be RESOLVED - */ - int state = bundle.getState(); - if ((bundle.adapt(BundleRevision.class).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { - //fragment - if (state != Bundle.RESOLVED) { - System.out.println("------ Failed to activate/resolve fragment = " + bundle.getSymbolicName() + " state = " + stateToString(bundle.getState())); - failed = true; - if (state == Bundle.STARTING) - resolved = false; - } - } else { - if(state != Bundle.ACTIVE) { - System.out.println("------ Failed to activate/resolve bundle = " + bundle.getSymbolicName() + " state = " + stateToString(bundle.getState())); - failed = true; - if (state == Bundle.STARTING) - resolved = false; - } - } - } - if (!resolved) { - countup++; - if (countup < MAX_ATTEMPTS) { - System.out.println("all bundles haven't finished starting, will repeat"); - try { - Thread.sleep(SUBSEQUENT_DELAY); - } catch (Exception e) { - System.out.println("Thread.sleep interuptted."); - break; - } - } else - resolved = true; - } - } - - if(failed){ - System.out.flush(); - System.out.println("exiting with 1 as failed"); - System.out.close(); - Runtime.getRuntime().exit(1); - } else { - System.out.flush(); - System.out.println("exiting with 0 as succeeded"); - System.out.close(); - Runtime.getRuntime().exit(0); - } - } - }, INITIAL_DELAY); - } - - public void stop(BundleContext bundleContext) throws Exception { - - } -} diff --git a/opendaylight/karaf-branding/pom.xml b/opendaylight/karaf-branding/pom.xml index dfdc3b76cb..7b2bd864f2 100644 --- a/opendaylight/karaf-branding/pom.xml +++ b/opendaylight/karaf-branding/pom.xml @@ -8,7 +8,6 @@ 0.2.0-SNAPSHOT ../.. - org.opendaylight.controller karaf.branding 1.1.0-SNAPSHOT bundle diff --git a/opendaylight/md-sal/benchmark-data-store/pom.xml b/opendaylight/md-sal/benchmark-data-store/pom.xml index ac384319b8..b196c3180f 100644 --- a/opendaylight/md-sal/benchmark-data-store/pom.xml +++ b/opendaylight/md-sal/benchmark-data-store/pom.xml @@ -16,7 +16,6 @@ and is available at http://www.eclipse.org/legal/epl-v10.html 4.0.0 - org.opendaylight.controller benchmark-data-store @@ -40,6 +39,14 @@ and is available at http://www.eclipse.org/legal/epl-v10.html org.opendaylight.controller sal-inmemory-datastore + + org.opendaylight.controller + sal-broker-impl + + + org.slf4j + slf4j-simple + @@ -69,4 +76,4 @@ and is available at http://www.eclipse.org/legal/epl-v10.html - \ No newline at end of file + diff --git a/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryBrokerWriteTransactionBenchmark.java b/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryBrokerWriteTransactionBenchmark.java new file mode 100644 index 0000000000..fdd715e54f --- /dev/null +++ b/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryBrokerWriteTransactionBenchmark.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.dom.store.benchmark; + +import java.util.concurrent.TimeUnit; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; +import org.opendaylight.controller.md.sal.dom.broker.impl.DOMDataBrokerImpl; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Warmup; + +/** + * @author Lukas Sedlak + */ +public abstract class AbstractInMemoryBrokerWriteTransactionBenchmark extends AbstractInMemoryWriteTransactionBenchmark { + + protected DOMDataBrokerImpl domBroker; + + protected void initTestNode() throws Exception { + final YangInstanceIdentifier testPath = YangInstanceIdentifier.builder(BenchmarkModel.TEST_PATH) + .build(); + DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction(); + writeTx.put(LogicalDatastoreType.OPERATIONAL, testPath, provideOuterListNode()); + + writeTx.submit().get(); + } + + @Benchmark + @Warmup(iterations = WARMUP_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + @Measurement(iterations = MEASUREMENT_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + public void write100KSingleNodeWithOneInnerItemInOneCommitBenchmark() throws Exception { + + DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction(); + for (int outerListKey = 0; outerListKey < OUTER_LIST_100K; ++outerListKey) { + writeTx.put(LogicalDatastoreType.OPERATIONAL, OUTER_LIST_100K_PATHS[outerListKey], OUTER_LIST_ONE_ITEM_INNER_LIST[outerListKey]); + } + + writeTx.submit().get(); + } + + @Benchmark + @Warmup(iterations = WARMUP_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + @Measurement(iterations = MEASUREMENT_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + public void write100KSingleNodeWithOneInnerItemInCommitPerWriteBenchmark() throws Exception { + for (int outerListKey = 0; outerListKey < OUTER_LIST_100K; ++outerListKey) { + DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction(); + writeTx.put(LogicalDatastoreType.OPERATIONAL, OUTER_LIST_100K_PATHS[outerListKey], OUTER_LIST_ONE_ITEM_INNER_LIST[outerListKey]); + + writeTx.submit().get(); + } + } + + @Benchmark + @Warmup(iterations = WARMUP_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + @Measurement(iterations = MEASUREMENT_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + public void write50KSingleNodeWithTwoInnerItemsInOneCommitBenchmark() throws Exception { + DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction(); + for (int outerListKey = 0; outerListKey < OUTER_LIST_50K; ++outerListKey) { + writeTx.put(LogicalDatastoreType.OPERATIONAL, OUTER_LIST_50K_PATHS[outerListKey], OUTER_LIST_TWO_ITEM_INNER_LIST[outerListKey]); + } + + writeTx.submit().get(); + } + + @Benchmark + @Warmup(iterations = WARMUP_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + @Measurement(iterations = MEASUREMENT_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + public void write50KSingleNodeWithTwoInnerItemsInCommitPerWriteBenchmark() throws Exception { + for (int outerListKey = 0; outerListKey < OUTER_LIST_50K; ++outerListKey) { + DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction(); + writeTx.put(LogicalDatastoreType.OPERATIONAL, OUTER_LIST_50K_PATHS[outerListKey], OUTER_LIST_TWO_ITEM_INNER_LIST[outerListKey]); + writeTx.submit().get(); + } + } + + @Benchmark + @Warmup(iterations = WARMUP_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + @Measurement(iterations = MEASUREMENT_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + public void write10KSingleNodeWithTenInnerItemsInOneCommitBenchmark() throws Exception { + DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction(); + for (int outerListKey = 0; outerListKey < OUTER_LIST_10K; ++outerListKey) { + writeTx.put(LogicalDatastoreType.OPERATIONAL, OUTER_LIST_10K_PATHS[outerListKey], OUTER_LIST_TEN_ITEM_INNER_LIST[outerListKey]); + } + writeTx.submit().get(); + } + + @Benchmark + @Warmup(iterations = WARMUP_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + @Measurement(iterations = MEASUREMENT_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) + public void write10KSingleNodeWithTenInnerItemsInCommitPerWriteBenchmark() throws Exception { + for (int outerListKey = 0; outerListKey < OUTER_LIST_10K; ++outerListKey) { + DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction(); + writeTx.put(LogicalDatastoreType.OPERATIONAL, OUTER_LIST_10K_PATHS[outerListKey], OUTER_LIST_TEN_ITEM_INNER_LIST[outerListKey]); + writeTx.submit().get(); + } + } +} diff --git a/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryDatastoreWriteTransactionBenchmark.java b/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryDatastoreWriteTransactionBenchmark.java index aa5ef61ce4..fce0642860 100644 --- a/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryDatastoreWriteTransactionBenchmark.java +++ b/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryDatastoreWriteTransactionBenchmark.java @@ -12,14 +12,6 @@ import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore; import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction; import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; -import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; -import org.opendaylight.yangtools.yang.data.api.schema.MapNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; -import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder; -import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Warmup; @@ -27,67 +19,10 @@ import org.openjdk.jmh.annotations.Warmup; /** * @author Lukas Sedlak */ -public abstract class AbstractInMemoryDatastoreWriteTransactionBenchmark { +public abstract class AbstractInMemoryDatastoreWriteTransactionBenchmark extends AbstractInMemoryWriteTransactionBenchmark { - private static final int WARMUP_ITERATIONS = 20; - private static final int MEASUREMENT_ITERATIONS = 20; - - private static final int OUTER_LIST_100K = 100000; - private static final int OUTER_LIST_50K = 50000; - private static final int OUTER_LIST_10K = 10000; - - private static final YangInstanceIdentifier[] OUTER_LIST_100K_PATHS = initOuterListPaths(OUTER_LIST_100K); - private static final YangInstanceIdentifier[] OUTER_LIST_50K_PATHS = initOuterListPaths(OUTER_LIST_50K); - private static final YangInstanceIdentifier[] OUTER_LIST_10K_PATHS = initOuterListPaths(OUTER_LIST_10K); - - private static YangInstanceIdentifier[] initOuterListPaths(final int outerListPathsCount) { - final YangInstanceIdentifier[] paths = new YangInstanceIdentifier[outerListPathsCount]; - - for (int outerListKey = 0; outerListKey < outerListPathsCount; ++outerListKey) { - paths[outerListKey] = YangInstanceIdentifier.builder(BenchmarkModel.OUTER_LIST_PATH) - .nodeWithKey(BenchmarkModel.OUTER_LIST_QNAME, BenchmarkModel.ID_QNAME, outerListKey) - .build(); - } - return paths; - } - - private static final MapNode ONE_ITEM_INNER_LIST = initInnerListItems(1); - private static final MapNode TWO_ITEM_INNER_LIST = initInnerListItems(2); - private static final MapNode TEN_ITEM_INNER_LIST = initInnerListItems(10); - - private static MapNode initInnerListItems(final int count) { - final CollectionNodeBuilder mapEntryBuilder = ImmutableNodes - .mapNodeBuilder(BenchmarkModel.INNER_LIST_QNAME); - - for (int i = 1; i <= count; ++i) { - mapEntryBuilder - .withChild(ImmutableNodes.mapEntry(BenchmarkModel.INNER_LIST_QNAME, BenchmarkModel.NAME_QNAME, i)); - } - return mapEntryBuilder.build(); - } - - private static final NormalizedNode[] OUTER_LIST_ONE_ITEM_INNER_LIST = initOuterListItems(OUTER_LIST_100K, ONE_ITEM_INNER_LIST); - private static final NormalizedNode[] OUTER_LIST_TWO_ITEM_INNER_LIST = initOuterListItems(OUTER_LIST_50K, TWO_ITEM_INNER_LIST); - private static final NormalizedNode[] OUTER_LIST_TEN_ITEM_INNER_LIST = initOuterListItems(OUTER_LIST_10K, TEN_ITEM_INNER_LIST); - - private static NormalizedNode[] initOuterListItems(int outerListItemsCount, MapNode innerList) { - final NormalizedNode[] outerListItems = new NormalizedNode[outerListItemsCount]; - - for (int i = 0; i < outerListItemsCount; ++i) { - int outerListKey = i; - outerListItems[i] = ImmutableNodes.mapEntryBuilder(BenchmarkModel.OUTER_LIST_QNAME, BenchmarkModel.ID_QNAME, outerListKey) - .withChild(innerList).build(); - } - return outerListItems; - } - - protected SchemaContext schemaContext; protected InMemoryDOMDataStore domStore; - abstract public void setUp() throws Exception; - - abstract public void tearDown(); - protected void initTestNode() throws Exception { final YangInstanceIdentifier testPath = YangInstanceIdentifier.builder(BenchmarkModel.TEST_PATH) .build(); @@ -100,15 +35,6 @@ public abstract class AbstractInMemoryDatastoreWriteTransactionBenchmark { cohort.commit().get(); } - private DataContainerChild provideOuterListNode() { - return ImmutableContainerNodeBuilder - .create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(BenchmarkModel.TEST_QNAME)) - .withChild( - ImmutableNodes.mapNodeBuilder(BenchmarkModel.OUTER_LIST_QNAME) - .build()).build(); - } - @Benchmark @Warmup(iterations = WARMUP_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) @Measurement(iterations = MEASUREMENT_ITERATIONS, timeUnit = TimeUnit.MILLISECONDS) diff --git a/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryWriteTransactionBenchmark.java b/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryWriteTransactionBenchmark.java new file mode 100644 index 0000000000..6c256eb7af --- /dev/null +++ b/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/AbstractInMemoryWriteTransactionBenchmark.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.dom.store.benchmark; + +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; +import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; + +public abstract class AbstractInMemoryWriteTransactionBenchmark { + protected static final int OUTER_LIST_100K = 100000; + protected static final int OUTER_LIST_50K = 50000; + protected static final int OUTER_LIST_10K = 10000; + + protected static final YangInstanceIdentifier[] OUTER_LIST_100K_PATHS = initOuterListPaths(OUTER_LIST_100K); + protected static final YangInstanceIdentifier[] OUTER_LIST_50K_PATHS = initOuterListPaths(OUTER_LIST_50K); + protected static final YangInstanceIdentifier[] OUTER_LIST_10K_PATHS = initOuterListPaths(OUTER_LIST_10K); + + private static YangInstanceIdentifier[] initOuterListPaths(final int outerListPathsCount) { + final YangInstanceIdentifier[] paths = new YangInstanceIdentifier[outerListPathsCount]; + + for (int outerListKey = 0; outerListKey < outerListPathsCount; ++outerListKey) { + paths[outerListKey] = YangInstanceIdentifier.builder(BenchmarkModel.OUTER_LIST_PATH) + .nodeWithKey(BenchmarkModel.OUTER_LIST_QNAME, BenchmarkModel.ID_QNAME, outerListKey) + .build(); + } + return paths; + } + + protected static final int WARMUP_ITERATIONS = 20; + protected static final int MEASUREMENT_ITERATIONS = 20; + + protected static final MapNode ONE_ITEM_INNER_LIST = initInnerListItems(1); + protected static final MapNode TWO_ITEM_INNER_LIST = initInnerListItems(2); + protected static final MapNode TEN_ITEM_INNER_LIST = initInnerListItems(10); + + private static MapNode initInnerListItems(final int count) { + final CollectionNodeBuilder mapEntryBuilder = ImmutableNodes + .mapNodeBuilder(BenchmarkModel.INNER_LIST_QNAME); + + for (int i = 1; i <= count; ++i) { + mapEntryBuilder + .withChild(ImmutableNodes.mapEntry(BenchmarkModel.INNER_LIST_QNAME, BenchmarkModel.NAME_QNAME, i)); + } + return mapEntryBuilder.build(); + } + + protected static final NormalizedNode[] OUTER_LIST_ONE_ITEM_INNER_LIST = initOuterListItems(OUTER_LIST_100K, ONE_ITEM_INNER_LIST); + protected static final NormalizedNode[] OUTER_LIST_TWO_ITEM_INNER_LIST = initOuterListItems(OUTER_LIST_50K, TWO_ITEM_INNER_LIST); + protected static final NormalizedNode[] OUTER_LIST_TEN_ITEM_INNER_LIST = initOuterListItems(OUTER_LIST_10K, TEN_ITEM_INNER_LIST); + + private static NormalizedNode[] initOuterListItems(final int outerListItemsCount, final MapNode innerList) { + final NormalizedNode[] outerListItems = new NormalizedNode[outerListItemsCount]; + + for (int i = 0; i < outerListItemsCount; ++i) { + int outerListKey = i; + outerListItems[i] = ImmutableNodes.mapEntryBuilder(BenchmarkModel.OUTER_LIST_QNAME, BenchmarkModel.ID_QNAME, outerListKey) + .withChild(innerList).build(); + } + return outerListItems; + } + + protected SchemaContext schemaContext; + abstract public void setUp() throws Exception; + abstract public void tearDown(); + + protected static DataContainerChild provideOuterListNode() { + return ImmutableContainerNodeBuilder + .create() + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(BenchmarkModel.TEST_QNAME)) + .withChild( + ImmutableNodes.mapNodeBuilder(BenchmarkModel.OUTER_LIST_QNAME) + .build()).build(); + } +} diff --git a/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/InMemoryBrokerWriteTransactionBenchmark.java b/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/InMemoryBrokerWriteTransactionBenchmark.java new file mode 100644 index 0000000000..a46a6d1e79 --- /dev/null +++ b/opendaylight/md-sal/benchmark-data-store/src/main/java/org/opendaylight/controller/md/sal/dom/store/benchmark/InMemoryBrokerWriteTransactionBenchmark.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.dom.store.benchmark; + +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.dom.broker.impl.DOMDataBrokerImpl; +import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore; +import org.opendaylight.controller.sal.core.spi.data.DOMStore; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; + +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Fork(1) +public class InMemoryBrokerWriteTransactionBenchmark extends AbstractInMemoryBrokerWriteTransactionBenchmark { + private ListeningExecutorService executor; + + @Setup(Level.Trial) + @Override + public void setUp() throws Exception { + ListeningExecutorService dsExec = MoreExecutors.sameThreadExecutor(); + executor = MoreExecutors.listeningDecorator( + MoreExecutors.getExitingExecutorService((ThreadPoolExecutor)Executors.newFixedThreadPool(1), 1L, TimeUnit.SECONDS)); + + InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", dsExec, + MoreExecutors.sameThreadExecutor()); + InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", dsExec, + MoreExecutors.sameThreadExecutor()); + Map datastores = ImmutableMap.of( + LogicalDatastoreType.OPERATIONAL, (DOMStore)operStore, + LogicalDatastoreType.CONFIGURATION, configStore); + + domBroker = new DOMDataBrokerImpl(datastores, executor); + schemaContext = BenchmarkModel.createTestContext(); + configStore.onGlobalContextUpdated(schemaContext); + operStore.onGlobalContextUpdated(schemaContext); + initTestNode(); + } + + @Override + public void tearDown() { + domBroker.close(); + executor.shutdown(); + } +} diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FromSalConversionsUtils.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FromSalConversionsUtils.java index ecf1a94c18..8468c2d7f5 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FromSalConversionsUtils.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FromSalConversionsUtils.java @@ -331,11 +331,11 @@ public final class FromSalConversionsUtils { final Inet4Address inetDestAddress) { String inetSourceAddressStr = InetAddresses .toAddrString(inetSourceAddress); - Ipv4Prefix ipv4SourcePrefix = new Ipv4Prefix(inetSourceAddressStr); + Ipv4Prefix ipv4SourcePrefix = new Ipv4Prefix(inetSourceAddressStr + "/32"); String inetDestAddressValue = InetAddresses .toAddrString(inetDestAddress); - Ipv4Prefix ipv4DestPrefix = new Ipv4Prefix(inetDestAddressValue); + Ipv4Prefix ipv4DestPrefix = new Ipv4Prefix(inetDestAddressValue + "/32"); ArpMatchBuilder arpMatchBuilder = new ArpMatchBuilder(); @@ -375,13 +375,13 @@ public final class FromSalConversionsUtils { if(inetSourceAddress != null) { String inetSrcAddressString = InetAddresses .toAddrString(inetSourceAddress); - layer4MatchBuild.setIpv4Source(new Ipv4Prefix(inetSrcAddressString)); + layer4MatchBuild.setIpv4Source(new Ipv4Prefix(inetSrcAddressString + "/32")); } if(inetDestAddress != null) { String inetDstAddressString = InetAddresses .toAddrString(inetDestAddress); layer4MatchBuild - .setIpv4Destination(new Ipv4Prefix(inetDstAddressString)); + .setIpv4Destination(new Ipv4Prefix(inetDstAddressString + "/32")); } return layer4MatchBuild.build(); @@ -394,13 +394,13 @@ public final class FromSalConversionsUtils { if(inetSourceAddress != null) { String inetSrcAddressString = InetAddresses .toAddrString(inetSourceAddress); - layer6MatchBuild.setIpv6Source(new Ipv6Prefix(inetSrcAddressString)); + layer6MatchBuild.setIpv6Source(new Ipv6Prefix(inetSrcAddressString + "/128")); } if(inetDestAddress != null) { String inetDstAddressString = InetAddresses .toAddrString(inetDestAddress); layer6MatchBuild - .setIpv6Destination(new Ipv6Prefix(inetDstAddressString)); + .setIpv6Destination(new Ipv6Prefix(inetDstAddressString + "/128")); } return layer6MatchBuild.build(); } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java index bbb6673a8e..560d8a1d3f 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java @@ -7,16 +7,10 @@ */ package org.opendaylight.controller.sal.compatibility; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; +import com.google.common.base.Optional; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.collect.Iterables; import org.opendaylight.controller.md.sal.binding.util.TypeSafeDataReader; import org.opendaylight.controller.sal.binding.api.data.DataBrokerService; @@ -46,6 +40,9 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.ta import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsUpdate; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowStatisticsData; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableInputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableOutput; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsListener; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsService; @@ -59,6 +56,8 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev13 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.statistics.FlowTableStatistics; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819.FlowTopologyDiscoveryService; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819.Link; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionAware; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.TransactionId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRemoved; @@ -81,21 +80,36 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.N import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsListener; import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsService; import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMap; +import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument; +import org.opendaylight.yangtools.yang.common.RpcResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.Iterables; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInInventoryService, OpendaylightFlowStatisticsListener, OpendaylightFlowTableStatisticsListener, OpendaylightPortStatisticsListener { private static final Logger LOG = LoggerFactory.getLogger(InventoryAndReadAdapter.class); private static final short OPENFLOWV10_TABLE_ID = 0; + private static final int SLEEP_FOR_NOTIFICATIONS_MILLIS = 500; private final InventoryNotificationProvider inventoryNotificationProvider = new InventoryNotificationProvider(); private final Map> nodeToNodeConnectorsMap = new ConcurrentHashMap<>(); private List inventoryPublisher = new CopyOnWriteArrayList<>(); private List statisticsPublisher = new CopyOnWriteArrayList<>(); + private Cache> txCache; private OpendaylightFlowTableStatisticsService flowTableStatisticsService; private OpendaylightPortStatisticsService nodeConnectorStatisticsService; @@ -171,6 +185,7 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI public void startAdapter() { inventoryNotificationProvider.setDataProviderService(getDataProviderService()); inventoryNotificationProvider.setInventoryPublisher(getInventoryPublisher()); + txCache = CacheBuilder.newBuilder().expireAfterWrite(60L, TimeUnit.SECONDS).maximumSize(10000).build(); // inventoryNotificationProvider.start(); } @@ -251,22 +266,97 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI @Override public List readAllFlow(final Node node, final boolean cached) { - final ArrayList output = new ArrayList<>(); - final Table table = readOperationalTable(node, OPENFLOWV10_TABLE_ID); - if (table != null) { - final List flows = table.getFlow(); - LOG.trace("Number of flows installed in table 0 of node {} : {}", node, flows.size()); + final ArrayList ret= new ArrayList<>(); + if (cached) { + final Table table = readOperationalTable(node, OPENFLOWV10_TABLE_ID); + if (table != null) { + final List flows = table.getFlow(); + LOG.trace("Number of flows installed in table 0 of node {} : {}", node, flows.size()); + + for (final Flow flow : flows) { + final FlowStatisticsData statsFromDataStore = flow.getAugmentation(FlowStatisticsData.class); + if (statsFromDataStore != null) { + final FlowOnNode it = new FlowOnNode(ToSalConversionsUtils.toFlow(flow, node)); + ret.add(addFlowStats(it, statsFromDataStore.getFlowStatistics())); + } + } + } + } else { + LOG.debug("readAllFlow cached:{}", cached); + GetAllFlowStatisticsFromFlowTableInput input = + new GetAllFlowStatisticsFromFlowTableInputBuilder() + .setNode(NodeMapping.toNodeRef(node)) + .setTableId(new TableId(OPENFLOWV10_TABLE_ID)) + .build(); + + Future> future = + getFlowStatisticsService().getAllFlowStatisticsFromFlowTable(input); - for (final Flow flow : flows) { - final FlowStatisticsData statsFromDataStore = flow.getAugmentation(FlowStatisticsData.class); - if (statsFromDataStore != null) { - final FlowOnNode it = new FlowOnNode(ToSalConversionsUtils.toFlow(flow, node)); - output.add(addFlowStats(it, statsFromDataStore.getFlowStatistics())); + RpcResult result = null; + try { + // having a blocking call is fine here, as we need to join + // the notifications and return the result + result = future.get(); + } catch (Exception e) { + LOG.error("Exception in getAllFlowStatisticsFromFlowTable ", e); + return ret; + } + + GetAllFlowStatisticsFromFlowTableOutput output = result.getResult(); + if (output == null) { + return ret; + } + + TransactionId transactionId = output.getTransactionId(); + String cacheKey = buildCacheKey(transactionId, NodeMapping.toNodeId(node)); + LOG.info("readAllFlow transactionId:{} cacheKey:{}", transactionId, cacheKey); + + // insert an entry in tempcache, will get updated when notification is received + txCache.put(cacheKey, new TransactionNotificationList( + transactionId, node.getNodeIDString())); + + TransactionNotificationList txnList = + (TransactionNotificationList) txCache.getIfPresent(cacheKey); + + // this loop would not be infinite as the cache will remove an entry + // after defined time if not written to + while (txnList != null && !txnList.areAllNotificationsGathered()) { + LOG.debug("readAllFlow waiting for notification..."); + waitForNotification(); + txnList = (TransactionNotificationList) txCache.getIfPresent(cacheKey); + } + + if (txnList == null) { + return ret; + } + + List notifications = txnList.getNotifications(); + for (FlowsStatisticsUpdate flowsStatisticsUpdate : notifications) { + List flowAndStatisticsMapList = flowsStatisticsUpdate.getFlowAndStatisticsMapList(); + if (flowAndStatisticsMapList != null) { + for (FlowAndStatisticsMapList flowAndStatistics : flowAndStatisticsMapList) { + final FlowOnNode it = new FlowOnNode(ToSalConversionsUtils.toFlow(flowAndStatistics, node)); + ret.add(addFlowStats(it, flowAndStatistics)); + } } } } + return ret; + } + + private String buildCacheKey(final TransactionId id, final NodeId nodeId) { + return String.valueOf(id.getValue()) + "-" + nodeId.getValue(); + } - return output; + private void waitForNotification() { + try { + // going for a simple sleep approach,as wait-notify on a monitor would require + // us to maintain monitors per txn-node combo + Thread.sleep(SLEEP_FOR_NOTIFICATIONS_MILLIS); + LOG.trace("statCollector is waking up from a wait stat Response sleep"); + } catch (final InterruptedException e) { + LOG.warn("statCollector has been interrupted waiting stat Response sleep", e); + } } @Override @@ -623,6 +713,8 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI for (final IPluginOutReadService statsPublisher : getStatisticsPublisher()) { statsPublisher.nodeFlowStatisticsUpdated(aDNode, adsalFlowsStatistics); } + + updateTransactionCache(notification, notification.getId(), !notification.isMoreReplies()); } /** @@ -778,4 +870,48 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI private List removeNodeConnectors(final InstanceIdentifier nodeIdentifier) { return this.nodeToNodeConnectorsMap.remove(Iterables.get(nodeIdentifier.getPathArguments(), 1)); } + + private void updateTransactionCache(T notification, NodeId nodeId, boolean lastNotification) { + + String cacheKey = buildCacheKey(notification.getTransactionId(), nodeId); + TransactionNotificationList txnList = (TransactionNotificationList) txCache.getIfPresent(cacheKey); + final Optional> optional = Optional.>fromNullable(txnList); + if (optional.isPresent()) { + LOG.info("updateTransactionCache cacheKey:{}, lastNotification:{}, txnList-present:{}", cacheKey, lastNotification, optional.isPresent()); + TransactionNotificationList txn = optional.get(); + txn.addNotification(notification); + txn.setAllNotificationsGathered(lastNotification); + } + } + + private class TransactionNotificationList { + private TransactionId id; + private String nId; + private List notifications; + private boolean allNotificationsGathered; + + public TransactionNotificationList(TransactionId id, String nId) { + this.nId = nId; + this.id = id; + notifications = new ArrayList(); + } + + public void addNotification(T notification) { + notifications.add(notification); + } + + public void setAllNotificationsGathered(boolean allNotificationsGathered) { + this.allNotificationsGathered = allNotificationsGathered; + } + + public boolean areAllNotificationsGathered() { + return allNotificationsGathered; + } + + public List getNotifications() { + return notifications; + } + + } + } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java index 00511bc744..d3b96d010d 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java @@ -429,12 +429,12 @@ public final class MDFlowMapping { public static Address toInetAddress(final InetAddress address) { if (address instanceof Inet4Address) { return new Ipv4Builder() - .setIpv4Address(new Ipv4Prefix(InetAddresses.toAddrString(address))) + .setIpv4Address(new Ipv4Prefix(InetAddresses.toAddrString(address) + "/32")) .build(); } if (address instanceof Inet6Address) { return new Ipv6Builder() - .setIpv6Address(new Ipv6Prefix(InetAddresses.toAddrString(address))) + .setIpv6Address(new Ipv6Prefix(InetAddresses.toAddrString(address) + "/128")) .build(); } diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java index bcb2367e7a..2bc3e60309 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java @@ -10,11 +10,6 @@ package org.opendaylight.controller.sal.compatibility; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Preconditions; -import java.math.BigInteger; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.regex.Pattern; import org.opendaylight.controller.sal.common.util.Arguments; import org.opendaylight.controller.sal.core.AdvertisedBandwidth; import org.opendaylight.controller.sal.core.Bandwidth; @@ -65,6 +60,12 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.math.BigInteger; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.regex.Pattern; + public final class NodeMapping { private static final Logger LOG = LoggerFactory @@ -167,7 +168,7 @@ public final class NodeMapping { * @param aDNode * @return */ - private static NodeId toNodeId(org.opendaylight.controller.sal.core.Node aDNode) { + public static NodeId toNodeId(org.opendaylight.controller.sal.core.Node aDNode) { String targetPrefix = null; if (NodeIDType.OPENFLOW.equals(aDNode.getType())) { targetPrefix = OPENFLOW_ID_PREFIX; diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java index dcc1a4660b..99e5a80a82 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java @@ -52,6 +52,7 @@ import org.opendaylight.controller.sal.action.SetVlanPcp; import org.opendaylight.controller.sal.action.SwPath; import org.opendaylight.controller.sal.core.ConstructionException; import org.opendaylight.controller.sal.core.Node; +import org.opendaylight.controller.sal.core.Node.NodeIDType; import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.flowprogrammer.Flow; import org.opendaylight.controller.sal.match.Match; @@ -207,10 +208,16 @@ public class ToSalConversionsUtils { Uri nodeConnector = ((OutputActionCase) sourceAction).getOutputAction().getOutputNodeConnector(); if (nodeConnector != null) { - //for (Uri uri : nodeConnectors) { - Uri fullNodeConnector = new Uri(node.getType()+":"+node.getID()+":"+nodeConnector.getValue()); + // TODO: We should really have a bi-directional map from AD-SAL node types to + // MD-SAL node types, but lets fix that later. + String type = node.getType(); + if( type.equals(NodeIDType.OPENFLOW) ){ + type = NodeMapping.OPENFLOW_ID_PREFIX; + }else{ + type = type + ":"; + } + Uri fullNodeConnector = new Uri(type+node.getID()+":"+nodeConnector.getValue()); targetAction.add(new Output(fromNodeConnectorRef(fullNodeConnector, node))); - //} } } else if (sourceAction instanceof PopMplsActionCase) { // TODO: define maping diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java index 78e82c32de..2490ace648 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java @@ -7,8 +7,7 @@ */ package org.opendaylight.controller.sal.compatibility.test; -import junit.framework.Assert; - +import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.sal.action.Action; import org.opendaylight.controller.sal.action.PushVlan; diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestFromSalConversionsUtils.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestFromSalConversionsUtils.java index 98df90112d..35555daff2 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestFromSalConversionsUtils.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestFromSalConversionsUtils.java @@ -129,9 +129,9 @@ public class TestFromSalConversionsUtils { Layer3Match layer3Match = match.getLayer3Match(); boolean arpFound = false; if (layer3Match instanceof ArpMatch) { - assertEquals("Source IP address is wrong.", "192.168.100.100", ((ArpMatch) layer3Match) + assertEquals("Source IP address is wrong.", "192.168.100.100/32", ((ArpMatch) layer3Match) .getArpSourceTransportAddress().getValue()); - assertEquals("Destination IP address is wrong.", "192.168.100.101", ((ArpMatch) layer3Match) + assertEquals("Destination IP address is wrong.", "192.168.100.101/32", ((ArpMatch) layer3Match) .getArpTargetTransportAddress().getValue()); assertEquals("Source MAC address is wrong.", "ff:ee:dd:cc:bb:aa", ((ArpMatch) layer3Match) .getArpSourceHardwareAddress().getAddress().getValue()); @@ -147,9 +147,9 @@ public class TestFromSalConversionsUtils { boolean ipv4Found = false; layer3Match = match.getLayer3Match(); if (layer3Match instanceof Ipv4Match) { - assertEquals("Source IP address is wrong.", "192.168.100.102", ((Ipv4Match) layer3Match) + assertEquals("Source IP address is wrong.", "192.168.100.102/32", ((Ipv4Match) layer3Match) .getIpv4Source().getValue()); - assertEquals("Destination IP address is wrong.", "192.168.100.103", ((Ipv4Match) layer3Match) + assertEquals("Destination IP address is wrong.", "192.168.100.103/32", ((Ipv4Match) layer3Match) .getIpv4Destination().getValue()); } assertNotNull("Ipv4 wasn't found", ipv4Found); @@ -160,9 +160,9 @@ public class TestFromSalConversionsUtils { boolean ipv6Found = false; layer3Match = match.getLayer3Match(); if (layer3Match instanceof Ipv6Match) { - assertEquals("Source IP address is wrong.", "2001:db8:85a3::8a2e:370:7335", ((Ipv6Match) layer3Match) + assertEquals("Source IP address is wrong.", "2001:db8:85a3::8a2e:370:7335/128", ((Ipv6Match) layer3Match) .getIpv6Source().getValue()); - assertEquals("Destination IP address is wrong.", "2001:db8:85a3::8a2e:370:7336", + assertEquals("Destination IP address is wrong.", "2001:db8:85a3::8a2e:370:7336/128", ((Ipv6Match) layer3Match).getIpv6Destination().getValue()); } assertNotNull("Ipv6 wasn't found", ipv6Found); @@ -288,7 +288,7 @@ public class TestFromSalConversionsUtils { boolean ipv4AddressFound = false; if (address instanceof Ipv4) { ipv4AddressFound = true; - assertEquals("Wrong IP address type in SetNextHopAction.", "192.168.100.100", ((Ipv4) address) + assertEquals("Wrong IP address type in SetNextHopAction.", "192.168.100.100/32", ((Ipv4) address) .getIpv4Address().getValue()); } assertTrue("Ipv4 address wasn't found.", ipv4AddressFound); @@ -299,7 +299,7 @@ public class TestFromSalConversionsUtils { boolean ipv4AddressFound = false; if (address instanceof Ipv4) { ipv4AddressFound = true; - assertEquals("Wrong IP address type in SetNwDstAction.", "192.168.100.101", ((Ipv4) address) + assertEquals("Wrong IP address type in SetNwDstAction.", "192.168.100.101/32", ((Ipv4) address) .getIpv4Address().getValue()); } assertTrue("Ipv4 address wasn't found.", ipv4AddressFound); @@ -308,7 +308,7 @@ public class TestFromSalConversionsUtils { boolean ipv4AddressFound = false; if (address instanceof Ipv4) { ipv4AddressFound = true; - assertEquals("Wrong IP address type in SetNwSrcAction.", "192.168.100.102", ((Ipv4) address) + assertEquals("Wrong IP address type in SetNwSrcAction.", "192.168.100.102/32", ((Ipv4) address) .getIpv4Address().getValue()); } assertTrue("Ipv4 address wasn't found.", ipv4AddressFound); diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java index 16d0bb424d..7c20c24bec 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java @@ -8,6 +8,7 @@ package org.opendaylight.controller.sal.compatibility.test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.opendaylight.controller.sal.compatibility.ProtocolConstants.CRUDP; import static org.opendaylight.controller.sal.compatibility.ProtocolConstants.ETHERNET_ARP; @@ -22,8 +23,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import junit.framework.Assert; - import org.junit.Test; import org.opendaylight.controller.sal.action.Flood; import org.opendaylight.controller.sal.action.FloodAll; @@ -198,7 +197,30 @@ public class TestToSalConversionsUtils { public void testFromNodeConnectorRef() throws ConstructionException { Node node = new Node(NodeIDType.OPENFLOW, 42L); NodeConnector nodeConnector = ToSalConversionsUtils.fromNodeConnectorRef(new Uri("1"), node); - Assert.assertEquals("OF|1@OF|00:00:00:00:00:00:00:2a", nodeConnector.toString()); + assertEquals("OF|1@OF|00:00:00:00:00:00:00:2a", nodeConnector.toString()); + } + + @Test + public void testActionFrom() throws ConstructionException { + // Bug 2021: Convert AD-SAL notation into MD-SAL notation before calling NodeConnector + Node node = new Node(NodeIDType.OPENFLOW, 42L); + List odActions = new ArrayList<>(); + + OutputActionBuilder outputActionBuilder = new OutputActionBuilder(); + outputActionBuilder.setOutputNodeConnector(new Uri("CONTROLLER")); + OutputActionCaseBuilder outputActionCaseBuilder = new OutputActionCaseBuilder(); + outputActionCaseBuilder.setOutputAction(outputActionBuilder.build()); + odActions.add(new ActionBuilder().setAction(outputActionCaseBuilder.build()).build()); + + List targetAction = + ToSalConversionsUtils.actionFrom(odActions, node); + assertNotNull(targetAction); + assertTrue( Output.class.isInstance(targetAction.get(0)) ); + Output targetActionOutput = (Output) targetAction.get(0); + NodeConnector port = targetActionOutput.getPort(); + assertNotNull(port); + assertEquals(port.getType(), NodeConnectorIDType.CONTROLLER); + assertEquals(port.getID(), org.opendaylight.controller.sal.core.NodeConnector.SPECIALNODECONNECTORID); } private void checkSalMatch(org.opendaylight.controller.sal.match.Match match, MtchType mt) throws ConstructionException { @@ -542,7 +564,7 @@ public class TestToSalConversionsUtils { private Address prapareIpv4Address(String ipv4Address) { Ipv4Builder ipv4Builder = new Ipv4Builder(); - ipv4Builder.setIpv4Address(new Ipv4Prefix(ipv4Address)); + ipv4Builder.setIpv4Address(new Ipv4Prefix(ipv4Address + "/32")); return ipv4Builder.build(); } @@ -647,8 +669,8 @@ public class TestToSalConversionsUtils { private Layer3Match prepLayer3MatchIpv4() { Ipv4MatchBuilder ipv4MatchBuilder = new Ipv4MatchBuilder(); - ipv4MatchBuilder.setIpv4Source(new Ipv4Prefix("192.168.1.104")); - ipv4MatchBuilder.setIpv4Destination(new Ipv4Prefix("192.168.1.105")); + ipv4MatchBuilder.setIpv4Source(new Ipv4Prefix("192.168.1.104/32")); + ipv4MatchBuilder.setIpv4Destination(new Ipv4Prefix("192.168.1.105/32")); return ipv4MatchBuilder.build(); } @@ -661,8 +683,8 @@ public class TestToSalConversionsUtils { private Layer3Match prepLayer3MatchArp() { ArpMatchBuilder arpMatchBuilder = new ArpMatchBuilder(); - arpMatchBuilder.setArpSourceTransportAddress(new Ipv4Prefix("192.168.1.101")); - arpMatchBuilder.setArpTargetTransportAddress(new Ipv4Prefix("192.168.1.102")); + arpMatchBuilder.setArpSourceTransportAddress(new Ipv4Prefix("192.168.1.101/32")); + arpMatchBuilder.setArpTargetTransportAddress(new Ipv4Prefix("192.168.1.102/32")); ArpSourceHardwareAddressBuilder arpSourAddressBuild = new ArpSourceHardwareAddressBuilder(); arpSourAddressBuild.setAddress(new MacAddress("22:44:66:88:AA:CC")); diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java index 9369217d78..2a0d47e9c2 100644 --- a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java +++ b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java @@ -7,7 +7,7 @@ */ package org.opendaylight.controller.sal.compatibility.topology.test; -import junit.framework.Assert; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.opendaylight.controller.sal.compatibility.topology.TopologyMapping; @@ -30,7 +30,7 @@ public class TopologyMappingTest { NodeId nodeId = new NodeId("openflow:1"); String observedNodeId = TopologyMapping.toADNodeId(nodeId); - Assert.assertEquals("1", observedNodeId); + assertEquals("1", observedNodeId); } /** @@ -43,7 +43,7 @@ public class TopologyMappingTest { TpId source = new TpId("foo:2"); NodeConnector observedNodeConnector = TopologyMapping.toADNodeConnector(source, nodeId); - Assert.assertEquals("OF|2@OF|00:00:00:00:00:00:00:01", observedNodeConnector.toString()); + assertEquals("OF|2@OF|00:00:00:00:00:00:00:01", observedNodeConnector.toString()); } /** @@ -54,7 +54,7 @@ public class TopologyMappingTest { TpId source = new TpId("foo:2"); String observedNodeConnectorId = TopologyMapping.toADNodeConnectorId(source); - Assert.assertEquals("2", observedNodeConnectorId); + assertEquals("2", observedNodeConnectorId); } /** @@ -66,7 +66,7 @@ public class TopologyMappingTest { NodeId nodeId = new NodeId("openflow:1"); Node observedNode = TopologyMapping.toADNode(nodeId); - Assert.assertEquals("OF|00:00:00:00:00:00:00:01", observedNode.toString()); + assertEquals("OF|00:00:00:00:00:00:00:01", observedNode.toString()); } /** @@ -79,7 +79,7 @@ public class TopologyMappingTest { TpId source = new TpId("192.168.0.1"); NodeConnector observedNodeConnector = TopologyMapping.toADNodeConnector(source, nodeId); - Assert.assertEquals("MD_SAL_DEPRECATED|192.168.0.1@MD_SAL_DEPRECATED|some_unknown_node", observedNodeConnector.toString()); + assertEquals("MD_SAL_DEPRECATED|192.168.0.1@MD_SAL_DEPRECATED|some_unknown_node", observedNodeConnector.toString()); } } diff --git a/opendaylight/md-sal/forwardingrules-manager/src/main/java/org/opendaylight/controller/frm/impl/FlowForwarder.java b/opendaylight/md-sal/forwardingrules-manager/src/main/java/org/opendaylight/controller/frm/impl/FlowForwarder.java index 698dbcb0d1..0d973d6f3b 100644 --- a/opendaylight/md-sal/forwardingrules-manager/src/main/java/org/opendaylight/controller/frm/impl/FlowForwarder.java +++ b/opendaylight/md-sal/forwardingrules-manager/src/main/java/org/opendaylight/controller/frm/impl/FlowForwarder.java @@ -1,4 +1,4 @@ -/**ab +/** * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the @@ -99,7 +99,13 @@ public class FlowForwarder extends AbstractListeningCommiter { builder.setFlowRef(new FlowRef(identifier)); builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class))); builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey))); - builder.setTransactionUri(new Uri(provider.getNewTransactionId())); + + // This method is called only when a given flow object has been + // removed from datastore. So FRM always needs to set strict flag + // into remove-flow input so that only a flow entry associated with + // a given flow object is removed. + builder.setTransactionUri(new Uri(provider.getNewTransactionId())). + setStrict(Boolean.TRUE); provider.getSalFlowService().removeFlow(builder.build()); } } @@ -116,8 +122,13 @@ public class FlowForwarder extends AbstractListeningCommiter { builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class))); builder.setFlowRef(new FlowRef(identifier)); builder.setTransactionUri(new Uri(provider.getNewTransactionId())); - builder.setUpdatedFlow((new UpdatedFlowBuilder(update)).build()); - builder.setOriginalFlow((new OriginalFlowBuilder(original)).build()); + + // This method is called only when a given flow object in datastore + // has been updated. So FRM always needs to set strict flag into + // update-flow input so that only a flow entry associated with + // a given flow object is updated. + builder.setUpdatedFlow((new UpdatedFlowBuilder(update)).setStrict(Boolean.TRUE).build()); + builder.setOriginalFlow((new OriginalFlowBuilder(original)).setStrict(Boolean.TRUE).build()); provider.getSalFlowService().updateFlow(builder.build()); } diff --git a/opendaylight/md-sal/forwardingrules-manager/src/test/java/test/mock/FlowListenerTest.java b/opendaylight/md-sal/forwardingrules-manager/src/test/java/test/mock/FlowListenerTest.java index 85f4b14472..91904cf8e9 100644 --- a/opendaylight/md-sal/forwardingrules-manager/src/test/java/test/mock/FlowListenerTest.java +++ b/opendaylight/md-sal/forwardingrules-manager/src/test/java/test/mock/FlowListenerTest.java @@ -124,6 +124,8 @@ public class FlowListenerTest extends FRMTest { assertEquals(1, updateFlowCalls.size()); assertEquals("DOM-1", updateFlowCalls.get(0).getTransactionUri().getValue()); assertEquals(flowII, updateFlowCalls.get(0).getFlowRef().getValue()); + assertEquals(Boolean.TRUE, updateFlowCalls.get(0).getOriginalFlow().isStrict()); + assertEquals(Boolean.TRUE, updateFlowCalls.get(0).getUpdatedFlow().isStrict()); forwardingRulesManager.close(); } @@ -204,6 +206,7 @@ public class FlowListenerTest extends FRMTest { assertEquals(1, removeFlowCalls.size()); assertEquals("DOM-1", removeFlowCalls.get(0).getTransactionUri().getValue()); assertEquals(flowII, removeFlowCalls.get(0).getFlowRef().getValue()); + assertEquals(Boolean.TRUE, removeFlowCalls.get(0).isStrict()); forwardingRulesManager.close(); } diff --git a/opendaylight/md-sal/inventory-manager/src/main/java/org/opendaylight/controller/md/inventory/manager/NodeChangeCommiter.java b/opendaylight/md-sal/inventory-manager/src/main/java/org/opendaylight/controller/md/inventory/manager/NodeChangeCommiter.java index b14bfd429c..ec184ad101 100644 --- a/opendaylight/md-sal/inventory-manager/src/main/java/org/opendaylight/controller/md/inventory/manager/NodeChangeCommiter.java +++ b/opendaylight/md-sal/inventory-manager/src/main/java/org/opendaylight/controller/md/inventory/manager/NodeChangeCommiter.java @@ -32,7 +32,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.No import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder; import org.slf4j.Logger; @@ -112,10 +111,10 @@ class NodeChangeCommiter implements OpendaylightInventoryListener { InstanceIdentifierBuilder builder = ((InstanceIdentifier) ref.getValue()).builder(); InstanceIdentifierBuilder augmentation = builder.augmentation(FlowCapableNode.class); final InstanceIdentifier path = augmentation.build(); - CheckedFuture readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, path); - Futures.addCallback(readFuture, new FutureCallback>() { + CheckedFuture, ?> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, path); + Futures.addCallback(readFuture, new FutureCallback>() { @Override - public void onSuccess(Optional optional) { + public void onSuccess(Optional optional) { enqueueWriteNodeDataTx(node, flowNode, path); if (!optional.isPresent()) { enqueuePutTable0Tx(ref); diff --git a/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-meter-types.yang b/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-meter-types.yang index 6d1405019c..95f2b7cc39 100644 --- a/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-meter-types.yang +++ b/opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-meter-types.yang @@ -94,7 +94,7 @@ module opendaylight-meter-types { type uint32; } - leaf perc_level { + leaf prec_level { description "Number of drop precedence level to add"; type uint8; } diff --git a/opendaylight/md-sal/sal-akka-raft/pom.xml b/opendaylight/md-sal/sal-akka-raft/pom.xml index 53353cded1..4b6091b429 100644 --- a/opendaylight/md-sal/sal-akka-raft/pom.xml +++ b/opendaylight/md-sal/sal-akka-raft/pom.xml @@ -13,7 +13,6 @@ org.opendaylight.controller sal-clustering-commons - 1.2.0-SNAPSHOT com.google.guava @@ -81,7 +80,6 @@ org.slf4j slf4j-simple - ${slf4j.version} test diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ClientActor.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ClientActor.java index 2560f16588..59bec91511 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ClientActor.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ClientActor.java @@ -29,6 +29,7 @@ public class ClientActor extends UntypedActor { public static Props props(final ActorRef target){ return Props.create(new Creator(){ + private static final long serialVersionUID = 1L; @Override public ClientActor create() throws Exception { return new ClientActor(target); diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java index 97b912ef74..6dfa4afd6b 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java @@ -11,45 +11,48 @@ package org.opendaylight.controller.cluster.example; import akka.actor.ActorRef; import akka.actor.Props; import akka.japi.Creator; - import com.google.common.base.Optional; import com.google.protobuf.ByteString; - +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.Map; +import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.example.messages.KeyValue; import org.opendaylight.controller.cluster.example.messages.KeyValueSaved; import org.opendaylight.controller.cluster.example.messages.PrintRole; import org.opendaylight.controller.cluster.example.messages.PrintState; import org.opendaylight.controller.cluster.raft.ConfigParams; import org.opendaylight.controller.cluster.raft.RaftActor; +import org.opendaylight.controller.cluster.raft.RaftState; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply; +import org.opendaylight.controller.cluster.raft.behaviors.Leader; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.HashMap; -import java.util.Map; - /** * A sample actor showing how the RaftActor is to be extended */ public class ExampleActor extends RaftActor { - private final Map state = new HashMap(); + private final Map state = new HashMap<>(); + private final DataPersistenceProvider dataPersistenceProvider; private long persistIdentifier = 1; - public ExampleActor(String id, Map peerAddresses, - Optional configParams) { + public ExampleActor(final String id, final Map peerAddresses, + final Optional configParams) { super(id, peerAddresses, configParams); + this.dataPersistenceProvider = new PersistentDataProvider(); } public static Props props(final String id, final Map peerAddresses, final Optional configParams){ return Props.create(new Creator(){ + private static final long serialVersionUID = 1L; @Override public ExampleActor create() throws Exception { return new ExampleActor(id, peerAddresses, configParams); @@ -57,7 +60,7 @@ public class ExampleActor extends RaftActor { }); } - @Override public void onReceiveCommand(Object message){ + @Override public void onReceiveCommand(final Object message) throws Exception{ if(message instanceof KeyValue){ if(isLeader()) { String persistId = Long.toString(persistIdentifier++); @@ -76,7 +79,15 @@ public class ExampleActor extends RaftActor { } else if (message instanceof PrintRole) { if(LOG.isDebugEnabled()) { - LOG.debug("{} = {}, Peers={}", getId(), getRaftState(), getPeers()); + String followers = ""; + if (getRaftState() == RaftState.Leader || getRaftState() == RaftState.IsolatedLeader) { + followers = ((Leader)this.getCurrentBehavior()).printFollowerStates(); + LOG.debug("{} = {}, Peers={}, followers={}", getId(), getRaftState(), getPeers(), followers); + } else { + LOG.debug("{} = {}, Peers={}", getId(), getRaftState(), getPeers()); + } + + } } else { @@ -84,8 +95,8 @@ public class ExampleActor extends RaftActor { } } - @Override protected void applyState(ActorRef clientActor, String identifier, - Object data) { + @Override protected void applyState(final ActorRef clientActor, final String identifier, + final Object data) { if(data instanceof KeyValue){ KeyValue kv = (KeyValue) data; state.put(kv.getKey(), kv.getValue()); @@ -105,19 +116,19 @@ public class ExampleActor extends RaftActor { getSelf().tell(new CaptureSnapshotReply(bs), null); } - @Override protected void applySnapshot(ByteString snapshot) { + @Override protected void applySnapshot(final ByteString snapshot) { state.clear(); try { - state.putAll((HashMap) toObject(snapshot)); + state.putAll((Map) toObject(snapshot)); } catch (Exception e) { LOG.error(e, "Exception in applying snapshot"); } if(LOG.isDebugEnabled()) { - LOG.debug("Snapshot applied to state : {}", ((HashMap) state).size()); + LOG.debug("Snapshot applied to state : {}", ((Map) state).size()); } } - private ByteString fromObject(Object snapshot) throws Exception { + private ByteString fromObject(final Object snapshot) throws Exception { ByteArrayOutputStream b = null; ObjectOutputStream o = null; try { @@ -137,7 +148,7 @@ public class ExampleActor extends RaftActor { } } - private Object toObject(ByteString bs) throws ClassNotFoundException, IOException { + private Object toObject(final ByteString bs) throws ClassNotFoundException, IOException { Object obj = null; ByteArrayInputStream bis = null; ObjectInputStream ois = null; @@ -160,7 +171,12 @@ public class ExampleActor extends RaftActor { } - @Override public void onReceiveRecover(Object message) { + @Override + protected DataPersistenceProvider persistence() { + return dataPersistenceProvider; + } + + @Override public void onReceiveRecover(final Object message)throws Exception { super.onReceiveRecover(message); } @@ -169,11 +185,11 @@ public class ExampleActor extends RaftActor { } @Override - protected void startLogRecoveryBatch(int maxBatchSize) { + protected void startLogRecoveryBatch(final int maxBatchSize) { } @Override - protected void appendRecoveredLogEntry(Payload data) { + protected void appendRecoveredLogEntry(final Payload data) { } @Override @@ -185,6 +201,6 @@ public class ExampleActor extends RaftActor { } @Override - protected void applyRecoverySnapshot(ByteString snapshot) { + protected void applyRecoverySnapshot(final ByteString snapshot) { } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleConfigParamsImpl.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleConfigParamsImpl.java index 6192cad230..2faae48838 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleConfigParamsImpl.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleConfigParamsImpl.java @@ -15,7 +15,7 @@ import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl; public class ExampleConfigParamsImpl extends DefaultConfigParamsImpl { @Override public long getSnapshotBatchCount() { - return 50; + return 25; } @Override diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java index cb51a8951a..de6169791e 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java @@ -6,7 +6,6 @@ import com.google.common.base.Optional; import org.opendaylight.controller.cluster.example.messages.PrintRole; import org.opendaylight.controller.cluster.example.messages.PrintState; import org.opendaylight.controller.cluster.raft.ConfigParams; -import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -35,7 +34,6 @@ public class TestDriver { * Commands * bye * createNodes:{num} - * addNodes:{num} * stopNode:{nodeName} * reinstateNode:{nodeName} * addClients:{num} @@ -46,6 +44,11 @@ public class TestDriver { * stopLoggingForClient:{nodeName} * printNodes * printState + * + * Note: when run on IDE and on debug log level, the debug logs in + * AbstractUptypedActor and AbstractUptypedPersistentActor would need to be commented out. + * Also RaftActor handleCommand(), debug log which prints for every command other than AE/AER + * * @param args * @throws Exception */ @@ -66,11 +69,6 @@ public class TestDriver { int n = Integer.parseInt(arr[1]); td.createNodes(n); - } else if (command.startsWith("addNodes")) { - String[] arr = command.split(":"); - int n = Integer.parseInt(arr[1]); - td.addNodes(n); - } else if (command.startsWith("addClients")) { String[] arr = command.split(":"); int n = Integer.parseInt(arr[1]); @@ -134,32 +132,6 @@ public class TestDriver { } } - // add new nodes , pass in the count - public void addNodes(int num) { - Map newPeers = new HashMap<>(); - for (int i=0; i < num; i++) { - nameCounter = nameCounter + 1; - newPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter); - allPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter); - - } - Map newActorRefs = new HashMap(num); - for (Map.Entry entry : newPeers.entrySet()) { - ActorRef exampleActor = createExampleActor(entry.getKey()); - newActorRefs.put(entry.getKey(), exampleActor); - - //now also add these new nodes as peers from the previous nodes - for (ActorRef actor : actorRefs.values()) { - actor.tell(new AddRaftPeer(entry.getKey(), entry.getValue()), null); - } - - System.out.println("Added node:" + entry); - } - - actorRefs.putAll(newActorRefs); - } - - // add num clients to all nodes in the system public void addClients(int num) { for(Map.Entry actorRefEntry : actorRefs.entrySet()) { diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/KeyValue.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/KeyValue.java index db3e683130..e0873cc7ba 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/KeyValue.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/KeyValue.java @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.Map; public class KeyValue extends Payload implements Serializable { + private static final long serialVersionUID = 1L; private String key; private String value; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/KeyValueSaved.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/KeyValueSaved.java index 9b2a2e9e3b..63c48ba703 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/KeyValueSaved.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/KeyValueSaved.java @@ -11,4 +11,5 @@ package org.opendaylight.controller.cluster.example.messages; import java.io.Serializable; public class KeyValueSaved implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/PrintRole.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/PrintRole.java index a5105f041a..c888d3f996 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/PrintRole.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/PrintRole.java @@ -11,4 +11,5 @@ package org.opendaylight.controller.cluster.example.messages; import java.io.Serializable; public class PrintRole implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/PrintState.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/PrintState.java index 20ed142d76..540f3768a6 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/PrintState.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/messages/PrintState.java @@ -11,4 +11,5 @@ package org.opendaylight.controller.cluster.example.messages; import java.io.Serializable; public class PrintState implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImpl.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImpl.java index 2be4a0c36f..a2c9d660ad 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImpl.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImpl.java @@ -7,8 +7,6 @@ */ package org.opendaylight.controller.cluster.raft; -import com.google.protobuf.ByteString; - import java.util.ArrayList; import java.util.List; @@ -20,27 +18,23 @@ public abstract class AbstractReplicatedLogImpl implements ReplicatedLog { // We define this as ArrayList so we can use ensureCapacity. protected ArrayList journal; - protected ByteString snapshot; + protected long snapshotIndex = -1; protected long snapshotTerm = -1; // to be used for rollback during save snapshot failure protected ArrayList snapshottedJournal; - protected ByteString previousSnapshot; protected long previousSnapshotIndex = -1; protected long previousSnapshotTerm = -1; - public AbstractReplicatedLogImpl(ByteString state, long snapshotIndex, + public AbstractReplicatedLogImpl(long snapshotIndex, long snapshotTerm, List unAppliedEntries) { - this.snapshot = state; this.snapshotIndex = snapshotIndex; this.snapshotTerm = snapshotTerm; this.journal = new ArrayList<>(unAppliedEntries); } - public AbstractReplicatedLogImpl() { - this.snapshot = null; this.journal = new ArrayList<>(); } @@ -154,11 +148,6 @@ public abstract class AbstractReplicatedLogImpl implements ReplicatedLog { return logEntryIndex <= snapshotIndex && snapshotIndex != -1; } - @Override - public ByteString getSnapshot() { - return snapshot; - } - @Override public long getSnapshotIndex() { return snapshotIndex; @@ -185,18 +174,13 @@ public abstract class AbstractReplicatedLogImpl implements ReplicatedLog { this.snapshotTerm = snapshotTerm; } - @Override - public void setSnapshot(ByteString snapshot) { - this.snapshot = snapshot; - } - @Override public void clear(int startIndex, int endIndex) { journal.subList(startIndex, endIndex).clear(); } @Override - public void snapshotPreCommit(ByteString snapshot, long snapshotCapturedIndex, long snapshotCapturedTerm) { + public void snapshotPreCommit(long snapshotCapturedIndex, long snapshotCapturedTerm) { snapshottedJournal = new ArrayList<>(journal.size()); snapshottedJournal.addAll(journal.subList(0, (int)(snapshotCapturedIndex - snapshotIndex))); @@ -207,9 +191,6 @@ public abstract class AbstractReplicatedLogImpl implements ReplicatedLog { previousSnapshotTerm = snapshotTerm; setSnapshotTerm(snapshotCapturedTerm); - - previousSnapshot = getSnapshot(); - setSnapshot(snapshot); } @Override @@ -217,7 +198,6 @@ public abstract class AbstractReplicatedLogImpl implements ReplicatedLog { snapshottedJournal = null; previousSnapshotIndex = -1; previousSnapshotTerm = -1; - previousSnapshot = null; } @Override @@ -231,9 +211,5 @@ public abstract class AbstractReplicatedLogImpl implements ReplicatedLog { snapshotTerm = previousSnapshotTerm; previousSnapshotTerm = -1; - - snapshot = previousSnapshot; - previousSnapshot = null; - } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ConfigParams.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ConfigParams.java index bff2a27797..433c3f7e4b 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ConfigParams.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ConfigParams.java @@ -62,4 +62,10 @@ public interface ConfigParams { * The number of journal log entries to batch on recovery before applying. */ int getJournalRecoveryLogBatchSize(); + + /** + * The interval in which the leader needs to check itself if its isolated + * @return FiniteDuration + */ + FiniteDuration getIsolatedCheckInterval(); } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/DefaultConfigParamsImpl.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/DefaultConfigParamsImpl.java index dc4145358a..a2092234d5 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/DefaultConfigParamsImpl.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/DefaultConfigParamsImpl.java @@ -44,6 +44,8 @@ public class DefaultConfigParamsImpl implements ConfigParams { private FiniteDuration heartBeatInterval = HEART_BEAT_INTERVAL; private long snapshotBatchCount = SNAPSHOT_BATCH_COUNT; private int journalRecoveryLogBatchSize = JOURNAL_RECOVERY_LOG_BATCH_SIZE; + private FiniteDuration isolatedLeaderCheckInterval = + new FiniteDuration(HEART_BEAT_INTERVAL.length() * 1000, HEART_BEAT_INTERVAL.unit()); public void setHeartBeatInterval(FiniteDuration heartBeatInterval) { this.heartBeatInterval = heartBeatInterval; @@ -57,6 +59,10 @@ public class DefaultConfigParamsImpl implements ConfigParams { this.journalRecoveryLogBatchSize = journalRecoveryLogBatchSize; } + public void setIsolatedLeaderCheckInterval(FiniteDuration isolatedLeaderCheckInterval) { + this.isolatedLeaderCheckInterval = isolatedLeaderCheckInterval; + } + @Override public long getSnapshotBatchCount() { return snapshotBatchCount; @@ -87,4 +93,9 @@ public class DefaultConfigParamsImpl implements ConfigParams { public int getJournalRecoveryLogBatchSize() { return journalRecoveryLogBatchSize; } + + @Override + public FiniteDuration getIsolatedCheckInterval() { + return isolatedLeaderCheckInterval; + } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/FollowerLogInformation.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/FollowerLogInformation.java index f3de983538..2c4304d404 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/FollowerLogInformation.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/FollowerLogInformation.java @@ -61,5 +61,16 @@ public interface FollowerLogInformation { */ public AtomicLong getMatchIndex(); + /** + * Checks if the follower is active by comparing the last updated with the duration + * @return boolean + */ + public boolean isFollowerActive(); + + /** + * restarts the timeout clock of the follower + */ + public void markFollowerActive(); + } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/FollowerLogInformationImpl.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/FollowerLogInformationImpl.java index 94f9a53a85..c0cfd7e862 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/FollowerLogInformationImpl.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/FollowerLogInformationImpl.java @@ -8,6 +8,10 @@ package org.opendaylight.controller.cluster.raft; +import com.google.common.base.Stopwatch; +import scala.concurrent.duration.FiniteDuration; + +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; public class FollowerLogInformationImpl implements FollowerLogInformation{ @@ -18,11 +22,17 @@ public class FollowerLogInformationImpl implements FollowerLogInformation{ private final AtomicLong matchIndex; + private final Stopwatch stopwatch; + + private final long followerTimeoutMillis; + public FollowerLogInformationImpl(String id, AtomicLong nextIndex, - AtomicLong matchIndex) { + AtomicLong matchIndex, FiniteDuration followerTimeoutDuration) { this.id = id; this.nextIndex = nextIndex; this.matchIndex = matchIndex; + this.stopwatch = new Stopwatch(); + this.followerTimeoutMillis = followerTimeoutDuration.toMillis(); } public long incrNextIndex(){ @@ -57,4 +67,17 @@ public class FollowerLogInformationImpl implements FollowerLogInformation{ return matchIndex; } + @Override + public boolean isFollowerActive() { + long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS); + return (stopwatch.isRunning()) && (elapsed <= followerTimeoutMillis); + } + + @Override + public void markFollowerActive() { + if (stopwatch.isRunning()) { + stopwatch.reset(); + } + stopwatch.start(); + } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java index 66a46ef3bd..042b9fb569 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java @@ -18,10 +18,12 @@ import akka.persistence.SaveSnapshotFailure; import akka.persistence.SaveSnapshotSuccess; import akka.persistence.SnapshotOffer; import akka.persistence.SnapshotSelectionCriteria; -import akka.persistence.UntypedPersistentActor; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Stopwatch; import com.google.protobuf.ByteString; +import org.opendaylight.controller.cluster.DataPersistenceProvider; +import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor; import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries; import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot; import org.opendaylight.controller.cluster.raft.base.messages.ApplyState; @@ -29,15 +31,16 @@ import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply; import org.opendaylight.controller.cluster.raft.base.messages.Replicate; import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat; +import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot; +import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior; import org.opendaylight.controller.cluster.raft.behaviors.Follower; import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior; -import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer; import org.opendaylight.controller.cluster.raft.client.messages.FindLeader; import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply; -import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer; import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages; + import java.io.Serializable; import java.util.Map; @@ -81,7 +84,7 @@ import java.util.Map; *
  • when a snapshot should be saved
  • * */ -public abstract class RaftActor extends UntypedPersistentActor { +public abstract class RaftActor extends AbstractUntypedPersistentActor { protected final LoggingAdapter LOG = Logging.getLogger(getContext().system(), this); @@ -135,24 +138,40 @@ public abstract class RaftActor extends UntypedPersistentActor { public void preStart() throws Exception { LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(), context.getConfigParams().getJournalRecoveryLogBatchSize()); + super.preStart(); } @Override - public void onReceiveRecover(Object message) { - if (message instanceof SnapshotOffer) { - onRecoveredSnapshot((SnapshotOffer)message); - } else if (message instanceof ReplicatedLogEntry) { - onRecoveredJournalLogEntry((ReplicatedLogEntry)message); - } else if (message instanceof ApplyLogEntries) { - onRecoveredApplyLogEntries((ApplyLogEntries)message); - } else if (message instanceof DeleteEntries) { - replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex()); - } else if (message instanceof UpdateElectionTerm) { - context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), - ((UpdateElectionTerm) message).getVotedFor()); - } else if (message instanceof RecoveryCompleted) { - onRecoveryCompletedMessage(); + public void handleRecover(Object message) { + if(persistence().isRecoveryApplicable()) { + if (message instanceof SnapshotOffer) { + onRecoveredSnapshot((SnapshotOffer) message); + } else if (message instanceof ReplicatedLogEntry) { + onRecoveredJournalLogEntry((ReplicatedLogEntry) message); + } else if (message instanceof ApplyLogEntries) { + onRecoveredApplyLogEntries((ApplyLogEntries) message); + } else if (message instanceof DeleteEntries) { + replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex()); + } else if (message instanceof UpdateElectionTerm) { + context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), + ((UpdateElectionTerm) message).getVotedFor()); + } else if (message instanceof RecoveryCompleted) { + onRecoveryCompletedMessage(); + } + } else { + if (message instanceof RecoveryCompleted) { + // Delete all the messages from the akka journal so that we do not end up with consistency issues + // Note I am not using the dataPersistenceProvider and directly using the akka api here + deleteMessages(lastSequenceNr()); + + // Delete all the akka snapshots as they will not be needed + deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue())); + + onRecoveryComplete(); + currentBehavior = new Follower(context); + onStateChanged(); + } } } @@ -254,7 +273,7 @@ public abstract class RaftActor extends UntypedPersistentActor { onStateChanged(); } - @Override public void onReceiveCommand(Object message) { + @Override public void handleCommand(Object message) { if (message instanceof ApplyState){ ApplyState applyState = (ApplyState) message; @@ -272,7 +291,7 @@ public abstract class RaftActor extends UntypedPersistentActor { if(LOG.isDebugEnabled()) { LOG.debug("Persisting ApplyLogEntries with index={}", ale.getToIndex()); } - persist(new ApplyLogEntries(ale.getToIndex()), new Procedure() { + persistence().persist(new ApplyLogEntries(ale.getToIndex()), new Procedure() { @Override public void apply(ApplyLogEntries param) throws Exception { } @@ -304,10 +323,9 @@ public abstract class RaftActor extends UntypedPersistentActor { SaveSnapshotSuccess success = (SaveSnapshotSuccess) message; LOG.info("SaveSnapshotSuccess received for snapshot"); - context.getReplicatedLog().snapshotCommit(); + long sequenceNumber = success.metadata().sequenceNr(); - // TODO: Not sure if we want to be this aggressive with trimming stuff - trimPersistentData(success.metadata().sequenceNr()); + commitSnapshot(sequenceNumber); } else if (message instanceof SaveSnapshotFailure) { SaveSnapshotFailure saveSnapshotFailure = (SaveSnapshotFailure) message; @@ -323,20 +341,6 @@ public abstract class RaftActor extends UntypedPersistentActor { context.getReplicatedLog().getSnapshotTerm(), context.getReplicatedLog().size()); - } else if (message instanceof AddRaftPeer){ - - // FIXME : Do not add raft peers like this. - // When adding a new Peer we have to ensure that the a majority of - // the peers know about the new Peer. Doing it this way may cause - // a situation where multiple Leaders may emerge - AddRaftPeer arp = (AddRaftPeer)message; - context.addToPeers(arp.getName(), arp.getAddress()); - - } else if (message instanceof RemoveRaftPeer){ - - RemoveRaftPeer rrp = (RemoveRaftPeer)message; - context.removePeer(rrp.getName()); - } else if (message instanceof CaptureSnapshot) { LOG.info("CaptureSnapshot received by actor"); CaptureSnapshot cs = (CaptureSnapshot)message; @@ -371,6 +375,7 @@ public abstract class RaftActor extends UntypedPersistentActor { } public java.util.Set getPeers() { + return context.getPeerAddresses().keySet(); } @@ -485,7 +490,12 @@ public abstract class RaftActor extends UntypedPersistentActor { context.setPeerAddress(peerId, peerAddress); } + protected void commitSnapshot(long sequenceNumber) { + context.getReplicatedLog().snapshotCommit(); + // TODO: Not sure if we want to be this aggressive with trimming stuff + trimPersistentData(sequenceNumber); + } /** * The applyState method will be called by the RaftActor when some data @@ -515,7 +525,7 @@ public abstract class RaftActor extends UntypedPersistentActor { /** * This method is called during recovery to append state data to the current batch. This method - * is called 1 or more times after {@link #startRecoveryStateBatch}. + * is called 1 or more times after {@link #startLogRecoveryBatch}. * * @param data the state data */ @@ -530,7 +540,7 @@ public abstract class RaftActor extends UntypedPersistentActor { /** * This method is called during recovery at the end of a batch to apply the current batched - * log entries. This method is called after {@link #appendRecoveryLogEntry}. + * log entries. This method is called after {@link #appendRecoveredLogEntry}. */ protected abstract void applyCurrentLogRecoveryBatch(); @@ -566,17 +576,19 @@ public abstract class RaftActor extends UntypedPersistentActor { */ protected abstract void onStateChanged(); + protected abstract DataPersistenceProvider persistence(); + protected void onLeaderChanged(String oldLeader, String newLeader){}; private void trimPersistentData(long sequenceNumber) { // Trim akka snapshots // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied // For now guessing that it is ANDed. - deleteSnapshots(new SnapshotSelectionCriteria( + persistence().deleteSnapshots(new SnapshotSelectionCriteria( sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000)); // Trim akka journal - deleteMessages(sequenceNumber); + persistence().deleteMessages(sequenceNumber); } private String getLeaderAddress(){ @@ -605,14 +617,14 @@ public abstract class RaftActor extends UntypedPersistentActor { captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(), captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm()); - saveSnapshot(sn); + persistence().saveSnapshot(sn); LOG.info("Persisting of snapshot done:{}", sn.getLogMessage()); //be greedy and remove entries from in-mem journal which are in the snapshot // and update snapshotIndex and snapshotTerm without waiting for the success, - context.getReplicatedLog().snapshotPreCommit(stateInBytes, + context.getReplicatedLog().snapshotPreCommit( captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm()); @@ -620,16 +632,19 @@ public abstract class RaftActor extends UntypedPersistentActor { "and term:{}", captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm()); + if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) { + // this would be call straight to the leader and won't initiate in serialization + currentBehavior.handleMessage(getSelf(), new SendInstallSnapshot(stateInBytes)); + } + captureSnapshot = null; hasSnapshotCaptureInitiated = false; } - private class ReplicatedLogImpl extends AbstractReplicatedLogImpl { public ReplicatedLogImpl(Snapshot snapshot) { - super(ByteString.copyFrom(snapshot.getState()), - snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(), + super(snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(), snapshot.getUnAppliedEntries()); } @@ -647,7 +662,7 @@ public abstract class RaftActor extends UntypedPersistentActor { // FIXME: Maybe this should be done after the command is saved journal.subList(adjustedIndex , journal.size()).clear(); - persist(new DeleteEntries(adjustedIndex), new Procedure(){ + persistence().persist(new DeleteEntries(adjustedIndex), new Procedure(){ @Override public void apply(DeleteEntries param) throws Exception { @@ -677,7 +692,7 @@ public abstract class RaftActor extends UntypedPersistentActor { // persist call and the execution(s) of the associated event // handler. This also holds for multiple persist calls in context // of a single command. - persist(replicatedLogEntry, + persistence().persist(replicatedLogEntry, new Procedure() { @Override public void apply(ReplicatedLogEntry evt) throws Exception { @@ -723,10 +738,10 @@ public abstract class RaftActor extends UntypedPersistentActor { } - private static class DeleteEntries implements Serializable { + static class DeleteEntries implements Serializable { + private static final long serialVersionUID = 1L; private final int fromIndex; - public DeleteEntries(int fromIndex) { this.fromIndex = fromIndex; } @@ -766,7 +781,7 @@ public abstract class RaftActor extends UntypedPersistentActor { public void updateAndPersist(long currentTerm, String votedFor){ update(currentTerm, votedFor); // FIXME : Maybe first persist then update the state - persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure(){ + persistence().persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure(){ @Override public void apply(UpdateElectionTerm param) throws Exception { @@ -776,7 +791,8 @@ public abstract class RaftActor extends UntypedPersistentActor { } } - private static class UpdateElectionTerm implements Serializable { + static class UpdateElectionTerm implements Serializable { + private static final long serialVersionUID = 1L; private final long currentTerm; private final String votedFor; @@ -794,4 +810,37 @@ public abstract class RaftActor extends UntypedPersistentActor { } } + protected class NonPersistentRaftDataProvider extends NonPersistentDataProvider { + + public NonPersistentRaftDataProvider(){ + + } + + /** + * The way snapshotting works is, + *
      + *
    1. RaftActor calls createSnapshot on the Shard + *
    2. Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot + *
    3. When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save the snapshot. + * The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the RaftActor gets SaveSnapshot + * success it commits the snapshot to the in-memory journal. This commitSnapshot is mimicking what is done + * in SaveSnapshotSuccess. + *
    + * @param o + */ + @Override + public void saveSnapshot(Object o) { + // Make saving Snapshot successful + commitSnapshot(-1L); + } + } + + @VisibleForTesting + void setCurrentBehavior(AbstractRaftActorBehavior behavior) { + currentBehavior = behavior; + } + + protected RaftActorBehavior getCurrentBehavior() { + return currentBehavior; + } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftState.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftState.java index 65114eb659..216ad4103d 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftState.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftState.java @@ -3,5 +3,6 @@ package org.opendaylight.controller.cluster.raft; public enum RaftState { Candidate, Follower, - Leader + Leader, + IsolatedLeader; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ReplicatedLog.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ReplicatedLog.java index 85893333c2..7ee85322a6 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ReplicatedLog.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ReplicatedLog.java @@ -8,8 +8,6 @@ package org.opendaylight.controller.cluster.raft; -import com.google.protobuf.ByteString; - import java.util.List; /** @@ -122,13 +120,6 @@ public interface ReplicatedLog { */ boolean isInSnapshot(long index); - /** - * Get the snapshot - * - * @return an object representing the snapshot if it exists. null otherwise - */ - ByteString getSnapshot(); - /** * Get the index of the snapshot * @@ -156,12 +147,6 @@ public interface ReplicatedLog { */ public void setSnapshotTerm(long snapshotTerm); - /** - * sets the snapshot in bytes - * @param snapshot - */ - public void setSnapshot(ByteString snapshot); - /** * Clears the journal entries with startIndex(inclusive) and endIndex (exclusive) * @param startIndex @@ -172,12 +157,10 @@ public interface ReplicatedLog { /** * Handles all the bookkeeping in order to perform a rollback in the * event of SaveSnapshotFailure - * @param snapshot * @param snapshotCapturedIndex * @param snapshotCapturedTerm */ - public void snapshotPreCommit(ByteString snapshot, - long snapshotCapturedIndex, long snapshotCapturedTerm); + public void snapshotPreCommit(long snapshotCapturedIndex, long snapshotCapturedTerm); /** * Sets the Replicated log to state after snapshot success. diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ReplicatedLogImplEntry.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ReplicatedLogImplEntry.java index fc2ec5cff9..ceb5633d4d 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ReplicatedLogImplEntry.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ReplicatedLogImplEntry.java @@ -14,6 +14,7 @@ import java.io.Serializable; public class ReplicatedLogImplEntry implements ReplicatedLogEntry, Serializable { + private static final long serialVersionUID = 1L; private final long index; private final long term; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/Snapshot.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/Snapshot.java index 8e0fcca9f7..77bf103701 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/Snapshot.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/Snapshot.java @@ -12,6 +12,7 @@ import java.util.List; public class Snapshot implements Serializable { + private static final long serialVersionUID = 1L; private final byte[] state; private final List unAppliedEntries; private final long lastIndex; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplyLogEntries.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplyLogEntries.java index af3c4fd87d..c395915a0f 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplyLogEntries.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplyLogEntries.java @@ -20,6 +20,7 @@ import java.io.Serializable; * */ public class ApplyLogEntries implements Serializable { + private static final long serialVersionUID = 1L; private final int toIndex; public ApplyLogEntries(int toIndex) { diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplySnapshot.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplySnapshot.java index c356804223..54ee02a057 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplySnapshot.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplySnapshot.java @@ -16,6 +16,7 @@ import java.io.Serializable; * Internal message, issued by follower to its actor */ public class ApplySnapshot implements Serializable { + private static final long serialVersionUID = 1L; private final Snapshot snapshot; public ApplySnapshot(Snapshot snapshot) { diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplyState.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplyState.java index b904335be3..0a7a632880 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplyState.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ApplyState.java @@ -14,6 +14,7 @@ import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry; import java.io.Serializable; public class ApplyState implements Serializable { + private static final long serialVersionUID = 1L; private final ActorRef clientActor; private final String identifier; private final ReplicatedLogEntry replicatedLogEntry; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/CaptureSnapshot.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/CaptureSnapshot.java index bb86e1a37d..d4dd3350f3 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/CaptureSnapshot.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/CaptureSnapshot.java @@ -13,13 +13,20 @@ public class CaptureSnapshot { private long lastAppliedTerm; private long lastIndex; private long lastTerm; + private boolean installSnapshotInitiated; public CaptureSnapshot(long lastIndex, long lastTerm, long lastAppliedIndex, long lastAppliedTerm) { + this(lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm, false); + } + + public CaptureSnapshot(long lastIndex, long lastTerm,long lastAppliedIndex, + long lastAppliedTerm, boolean installSnapshotInitiated) { this.lastIndex = lastIndex; this.lastTerm = lastTerm; this.lastAppliedIndex = lastAppliedIndex; this.lastAppliedTerm = lastAppliedTerm; + this.installSnapshotInitiated = installSnapshotInitiated; } public long getLastAppliedIndex() { @@ -37,4 +44,8 @@ public class CaptureSnapshot { public long getLastTerm() { return lastTerm; } + + public boolean isInstallSnapshotInitiated() { + return installSnapshotInitiated; + } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/CommitEntry.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/CommitEntry.java index 07e376fca3..6335e3272e 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/CommitEntry.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/CommitEntry.java @@ -14,4 +14,5 @@ import java.io.Serializable; * Message sent to commit an entry to the log */ public class CommitEntry implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ElectionTimeout.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ElectionTimeout.java index a844849f15..84fa8b7590 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ElectionTimeout.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/ElectionTimeout.java @@ -11,4 +11,5 @@ package org.opendaylight.controller.cluster.raft.base.messages; import java.io.Serializable; public class ElectionTimeout implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/InitiateInstallSnapshot.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/InitiateInstallSnapshot.java new file mode 100644 index 0000000000..7844914873 --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/InitiateInstallSnapshot.java @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.raft.base.messages; + +/** + * Internal message by Leader to initiate an install snapshot + */ +public class InitiateInstallSnapshot { +} + diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/IsolatedLeaderCheck.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/IsolatedLeaderCheck.java new file mode 100644 index 0000000000..36fd813664 --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/IsolatedLeaderCheck.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.raft.base.messages; + +/** + * Message sent by the IsolatedLeaderCheck scheduler in the Leader to itself + * in order to check if its isolated. + */ +public class IsolatedLeaderCheck { +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/PersistEntry.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/PersistEntry.java index 6a62817e90..68ecc1289b 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/PersistEntry.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/PersistEntry.java @@ -14,4 +14,5 @@ import java.io.Serializable; * Message sent to Persist an entry into the transaction journal */ public class PersistEntry implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/Replicate.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/Replicate.java index 9bc737a0e3..611c6eaf1f 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/Replicate.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/Replicate.java @@ -14,6 +14,7 @@ import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry; import java.io.Serializable; public class Replicate implements Serializable { + private static final long serialVersionUID = 1L; private final ActorRef clientActor; private final String identifier; private final ReplicatedLogEntry replicatedLogEntry; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SaveSnapshot.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SaveSnapshot.java index 861f5ee715..7b7f085856 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SaveSnapshot.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SaveSnapshot.java @@ -15,4 +15,5 @@ import java.io.Serializable; * it and use it to save it's state */ public class SaveSnapshot implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SendHeartBeat.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SendHeartBeat.java index 3c8c845f5d..7eb7522b85 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SendHeartBeat.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SendHeartBeat.java @@ -17,4 +17,5 @@ import java.io.Serializable; * Typically the Leader to itself on a schedule */ public class SendHeartBeat implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SendInstallSnapshot.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SendInstallSnapshot.java index 6c3313f316..83c85d9135 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SendInstallSnapshot.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/base/messages/SendInstallSnapshot.java @@ -8,7 +8,16 @@ package org.opendaylight.controller.cluster.raft.base.messages; -import java.io.Serializable; +import com.google.protobuf.ByteString; -public class SendInstallSnapshot implements Serializable { +public class SendInstallSnapshot { + private ByteString snapshot; + + public SendInstallSnapshot(ByteString snapshot) { + this.snapshot = snapshot; + } + + public ByteString getSnapshot() { + return snapshot; + } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeader.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeader.java new file mode 100644 index 0000000000..d85ac8ef67 --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeader.java @@ -0,0 +1,738 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.raft.behaviors; + +import akka.actor.ActorRef; +import akka.actor.ActorSelection; +import akka.actor.Cancellable; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import org.opendaylight.controller.cluster.raft.ClientRequestTracker; +import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl; +import org.opendaylight.controller.cluster.raft.FollowerLogInformation; +import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl; +import org.opendaylight.controller.cluster.raft.RaftActorContext; +import org.opendaylight.controller.cluster.raft.RaftState; +import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry; +import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; +import org.opendaylight.controller.cluster.raft.base.messages.InitiateInstallSnapshot; +import org.opendaylight.controller.cluster.raft.base.messages.Replicate; +import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat; +import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot; +import org.opendaylight.controller.cluster.raft.messages.AppendEntries; +import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply; +import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot; +import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply; +import org.opendaylight.controller.cluster.raft.messages.RaftRPC; +import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply; +import scala.concurrent.duration.FiniteDuration; + +/** + * The behavior of a RaftActor when it is in the Leader state + *

    + * Leaders: + *

      + *
    • Upon election: send initial empty AppendEntries RPCs + * (heartbeat) to each server; repeat during idle periods to + * prevent election timeouts (§5.2) + *
    • If command received from client: append entry to local log, + * respond after entry applied to state machine (§5.3) + *
    • If last log index ≥ nextIndex for a follower: send + * AppendEntries RPC with log entries starting at nextIndex + *
        + *
      • If successful: update nextIndex and matchIndex for + * follower (§5.3) + *
      • If AppendEntries fails because of log inconsistency: + * decrement nextIndex and retry (§5.3) + *
      + *
    • If there exists an N such that N > commitIndex, a majority + * of matchIndex[i] ≥ N, and log[N].term == currentTerm: + * set commitIndex = N (§5.3, §5.4). + */ +public abstract class AbstractLeader extends AbstractRaftActorBehavior { + protected final Map followerToLog = new HashMap<>(); + protected final Map mapFollowerToSnapshot = new HashMap<>(); + + protected final Set followers; + + private Cancellable heartbeatSchedule = null; + + private List trackerList = new ArrayList<>(); + + protected final int minReplicationCount; + + protected final int minIsolatedLeaderPeerCount; + + private Optional snapshot; + + public AbstractLeader(RaftActorContext context) { + super(context); + + followers = context.getPeerAddresses().keySet(); + + for (String followerId : followers) { + FollowerLogInformation followerLogInformation = + new FollowerLogInformationImpl(followerId, + new AtomicLong(context.getCommitIndex()), + new AtomicLong(-1), + context.getConfigParams().getElectionTimeOutInterval()); + + followerToLog.put(followerId, followerLogInformation); + } + + leaderId = context.getId(); + + if(LOG.isDebugEnabled()) { + LOG.debug("Election:Leader has following peers: {}", followers); + } + + minReplicationCount = getMajorityVoteCount(followers.size()); + + // the isolated Leader peer count will be 1 less than the majority vote count. + // this is because the vote count has the self vote counted in it + // for e.g + // 0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0 + // 2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1 + // 4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2 + minIsolatedLeaderPeerCount = minReplicationCount > 0 ? (minReplicationCount - 1) : 0; + + snapshot = Optional.absent(); + + // Immediately schedule a heartbeat + // Upon election: send initial empty AppendEntries RPCs + // (heartbeat) to each server; repeat during idle periods to + // prevent election timeouts (§5.2) + scheduleHeartBeat(new FiniteDuration(0, TimeUnit.SECONDS)); + } + + private Optional getSnapshot() { + return snapshot; + } + + @VisibleForTesting + void setSnapshot(Optional snapshot) { + this.snapshot = snapshot; + } + + @Override + protected RaftActorBehavior handleAppendEntries(ActorRef sender, + AppendEntries appendEntries) { + + if(LOG.isDebugEnabled()) { + LOG.debug(appendEntries.toString()); + } + + return this; + } + + @Override + protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, + AppendEntriesReply appendEntriesReply) { + + if(! appendEntriesReply.isSuccess()) { + if(LOG.isDebugEnabled()) { + LOG.debug(appendEntriesReply.toString()); + } + } + + // Update the FollowerLogInformation + String followerId = appendEntriesReply.getFollowerId(); + FollowerLogInformation followerLogInformation = + followerToLog.get(followerId); + + if(followerLogInformation == null){ + LOG.error("Unknown follower {}", followerId); + return this; + } + + followerLogInformation.markFollowerActive(); + + if (appendEntriesReply.isSuccess()) { + followerLogInformation + .setMatchIndex(appendEntriesReply.getLogLastIndex()); + followerLogInformation + .setNextIndex(appendEntriesReply.getLogLastIndex() + 1); + } else { + + // TODO: When we find that the follower is out of sync with the + // Leader we simply decrement that followers next index by 1. + // Would it be possible to do better than this? The RAFT spec + // does not explicitly deal with it but may be something for us to + // think about + + followerLogInformation.decrNextIndex(); + } + + // Now figure out if this reply warrants a change in the commitIndex + // If there exists an N such that N > commitIndex, a majority + // of matchIndex[i] ≥ N, and log[N].term == currentTerm: + // set commitIndex = N (§5.3, §5.4). + for (long N = context.getCommitIndex() + 1; ; N++) { + int replicatedCount = 1; + + for (FollowerLogInformation info : followerToLog.values()) { + if (info.getMatchIndex().get() >= N) { + replicatedCount++; + } + } + + if (replicatedCount >= minReplicationCount) { + ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N); + if (replicatedLogEntry != null && + replicatedLogEntry.getTerm() == currentTerm()) { + context.setCommitIndex(N); + } + } else { + break; + } + } + + // Apply the change to the state machine + if (context.getCommitIndex() > context.getLastApplied()) { + applyLogToStateMachine(context.getCommitIndex()); + } + + return this; + } + + protected ClientRequestTracker removeClientRequestTracker(long logIndex) { + + ClientRequestTracker toRemove = findClientRequestTracker(logIndex); + if(toRemove != null) { + trackerList.remove(toRemove); + } + + return toRemove; + } + + protected ClientRequestTracker findClientRequestTracker(long logIndex) { + for (ClientRequestTracker tracker : trackerList) { + if (tracker.getIndex() == logIndex) { + return tracker; + } + } + return null; + } + + @Override + protected RaftActorBehavior handleRequestVoteReply(ActorRef sender, + RequestVoteReply requestVoteReply) { + return this; + } + + @Override + public RaftState state() { + return RaftState.Leader; + } + + @Override + public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) { + Preconditions.checkNotNull(sender, "sender should not be null"); + + Object message = fromSerializableMessage(originalMessage); + + if (message instanceof RaftRPC) { + RaftRPC rpc = (RaftRPC) message; + // If RPC request or response contains term T > currentTerm: + // set currentTerm = T, convert to follower (§5.1) + // This applies to all RPC messages and responses + if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) { + context.getTermInformation().updateAndPersist(rpc.getTerm(), null); + + return switchBehavior(new Follower(context)); + } + } + + try { + if (message instanceof SendHeartBeat) { + sendHeartBeat(); + return this; + + } else if(message instanceof InitiateInstallSnapshot) { + installSnapshotIfNeeded(); + + } else if(message instanceof SendInstallSnapshot) { + // received from RaftActor + setSnapshot(Optional.of(((SendInstallSnapshot) message).getSnapshot())); + sendInstallSnapshot(); + + } else if (message instanceof Replicate) { + replicate((Replicate) message); + + } else if (message instanceof InstallSnapshotReply){ + handleInstallSnapshotReply((InstallSnapshotReply) message); + + } + } finally { + scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval()); + } + + return super.handleMessage(sender, message); + } + + private void handleInstallSnapshotReply(InstallSnapshotReply reply) { + String followerId = reply.getFollowerId(); + FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId); + FollowerLogInformation followerLogInformation = followerToLog.get(followerId); + followerLogInformation.markFollowerActive(); + + if (followerToSnapshot != null && + followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) { + + if (reply.isSuccess()) { + if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) { + //this was the last chunk reply + if(LOG.isDebugEnabled()) { + LOG.debug("InstallSnapshotReply received, " + + "last chunk received, Chunk:{}. Follower:{} Setting nextIndex:{}", + reply.getChunkIndex(), followerId, + context.getReplicatedLog().getSnapshotIndex() + 1 + ); + } + + followerLogInformation.setMatchIndex( + context.getReplicatedLog().getSnapshotIndex()); + followerLogInformation.setNextIndex( + context.getReplicatedLog().getSnapshotIndex() + 1); + mapFollowerToSnapshot.remove(followerId); + + if(LOG.isDebugEnabled()) { + LOG.debug("followerToLog.get(followerId).getNextIndex().get()=" + + followerToLog.get(followerId).getNextIndex().get()); + } + + if (mapFollowerToSnapshot.isEmpty()) { + // once there are no pending followers receiving snapshots + // we can remove snapshot from the memory + setSnapshot(Optional.absent()); + } + + } else { + followerToSnapshot.markSendStatus(true); + } + } else { + LOG.info("InstallSnapshotReply received, " + + "sending snapshot chunk failed, Will retry, Chunk:{}", + reply.getChunkIndex() + ); + followerToSnapshot.markSendStatus(false); + } + + } else { + LOG.error("ERROR!!" + + "FollowerId in InstallSnapshotReply not known to Leader" + + " or Chunk Index in InstallSnapshotReply not matching {} != {}", + followerToSnapshot.getChunkIndex(), reply.getChunkIndex() + ); + } + } + + private void replicate(Replicate replicate) { + long logIndex = replicate.getReplicatedLogEntry().getIndex(); + + if(LOG.isDebugEnabled()) { + LOG.debug("Replicate message {}", logIndex); + } + + // Create a tracker entry we will use this later to notify the + // client actor + trackerList.add( + new ClientRequestTrackerImpl(replicate.getClientActor(), + replicate.getIdentifier(), + logIndex) + ); + + if (followers.size() == 0) { + context.setCommitIndex(logIndex); + applyLogToStateMachine(logIndex); + } else { + sendAppendEntries(); + } + } + + private void sendAppendEntries() { + // Send an AppendEntries to all followers + for (String followerId : followers) { + ActorSelection followerActor = context.getPeerActorSelection(followerId); + + if (followerActor != null) { + FollowerLogInformation followerLogInformation = followerToLog.get(followerId); + long followerNextIndex = followerLogInformation.getNextIndex().get(); + boolean isFollowerActive = followerLogInformation.isFollowerActive(); + List entries = null; + + if (mapFollowerToSnapshot.get(followerId) != null) { + // if install snapshot is in process , then sent next chunk if possible + if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) { + sendSnapshotChunk(followerActor, followerId); + } else { + // we send a heartbeat even if we have not received a reply for the last chunk + sendAppendEntriesToFollower(followerActor, followerNextIndex, + Collections.emptyList()); + } + + } else { + long leaderLastIndex = context.getReplicatedLog().lastIndex(); + long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex(); + + if (isFollowerActive && + context.getReplicatedLog().isPresent(followerNextIndex)) { + // FIXME : Sending one entry at a time + entries = context.getReplicatedLog().getFrom(followerNextIndex, 1); + + } else if (isFollowerActive && followerNextIndex >= 0 && + leaderLastIndex >= followerNextIndex ) { + // if the followers next index is not present in the leaders log, and + // if the follower is just not starting and if leader's index is more than followers index + // then snapshot should be sent + + if(LOG.isDebugEnabled()) { + LOG.debug("InitiateInstallSnapshot to follower:{}," + + "follower-nextIndex:{}, leader-snapshot-index:{}, " + + "leader-last-index:{}", followerId, + followerNextIndex, leaderSnapShotIndex, leaderLastIndex + ); + } + actor().tell(new InitiateInstallSnapshot(), actor()); + + // we would want to sent AE as the capture snapshot might take time + entries = Collections.emptyList(); + + } else { + //we send an AppendEntries, even if the follower is inactive + // in-order to update the followers timestamp, in case it becomes active again + entries = Collections.emptyList(); + } + + sendAppendEntriesToFollower(followerActor, followerNextIndex, entries); + + } + } + } + } + + private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex, + List entries) { + followerActor.tell( + new AppendEntries(currentTerm(), context.getId(), + prevLogIndex(followerNextIndex), + prevLogTerm(followerNextIndex), entries, + context.getCommitIndex()).toSerializable(), + actor() + ); + } + + /** + * An installSnapshot is scheduled at a interval that is a multiple of + * a HEARTBEAT_INTERVAL. This is to avoid the need to check for installing + * snapshots at every heartbeat. + * + * Install Snapshot works as follows + * 1. Leader sends a InitiateInstallSnapshot message to self + * 2. Leader then initiates the capture snapshot by sending a CaptureSnapshot message to actor + * 3. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log + * and makes a call to Leader's handleMessage , with SendInstallSnapshot message. + * 4. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower + * 5. On complete, Follower sends back a InstallSnapshotReply. + * 6. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower + * and replenishes the memory by deleting the snapshot in Replicated log. + * + */ + private void installSnapshotIfNeeded() { + for (String followerId : followers) { + ActorSelection followerActor = + context.getPeerActorSelection(followerId); + + if(followerActor != null) { + FollowerLogInformation followerLogInformation = + followerToLog.get(followerId); + + long nextIndex = followerLogInformation.getNextIndex().get(); + + if (!context.getReplicatedLog().isPresent(nextIndex) && + context.getReplicatedLog().isInSnapshot(nextIndex)) { + LOG.info("{} follower needs a snapshot install", followerId); + if (snapshot.isPresent()) { + // if a snapshot is present in the memory, most likely another install is in progress + // no need to capture snapshot + sendSnapshotChunk(followerActor, followerId); + + } else { + initiateCaptureSnapshot(); + //we just need 1 follower who would need snapshot to be installed. + // when we have the snapshot captured, we would again check (in SendInstallSnapshot) + // who needs an install and send to all who need + break; + } + + } + } + } + } + + // on every install snapshot, we try to capture the snapshot. + // Once a capture is going on, another one issued will get ignored by RaftActor. + private void initiateCaptureSnapshot() { + LOG.info("Initiating Snapshot Capture to Install Snapshot, Leader:{}", getLeaderId()); + ReplicatedLogEntry lastAppliedEntry = context.getReplicatedLog().get(context.getLastApplied()); + long lastAppliedIndex = -1; + long lastAppliedTerm = -1; + + if (lastAppliedEntry != null) { + lastAppliedIndex = lastAppliedEntry.getIndex(); + lastAppliedTerm = lastAppliedEntry.getTerm(); + } else if (context.getReplicatedLog().getSnapshotIndex() > -1) { + lastAppliedIndex = context.getReplicatedLog().getSnapshotIndex(); + lastAppliedTerm = context.getReplicatedLog().getSnapshotTerm(); + } + + boolean isInstallSnapshotInitiated = true; + actor().tell(new CaptureSnapshot(lastIndex(), lastTerm(), + lastAppliedIndex, lastAppliedTerm, isInstallSnapshotInitiated), + actor()); + } + + + private void sendInstallSnapshot() { + for (String followerId : followers) { + ActorSelection followerActor = context.getPeerActorSelection(followerId); + + if(followerActor != null) { + FollowerLogInformation followerLogInformation = followerToLog.get(followerId); + long nextIndex = followerLogInformation.getNextIndex().get(); + + if (!context.getReplicatedLog().isPresent(nextIndex) && + context.getReplicatedLog().isInSnapshot(nextIndex)) { + sendSnapshotChunk(followerActor, followerId); + } + } + } + } + + /** + * Sends a snapshot chunk to a given follower + * InstallSnapshot should qualify as a heartbeat too. + */ + private void sendSnapshotChunk(ActorSelection followerActor, String followerId) { + try { + if (snapshot.isPresent()) { + followerActor.tell( + new InstallSnapshot(currentTerm(), context.getId(), + context.getReplicatedLog().getSnapshotIndex(), + context.getReplicatedLog().getSnapshotTerm(), + getNextSnapshotChunk(followerId,snapshot.get()), + mapFollowerToSnapshot.get(followerId).incrementChunkIndex(), + mapFollowerToSnapshot.get(followerId).getTotalChunks() + ).toSerializable(), + actor() + ); + LOG.info("InstallSnapshot sent to follower {}, Chunk: {}/{}", + followerActor.path(), mapFollowerToSnapshot.get(followerId).getChunkIndex(), + mapFollowerToSnapshot.get(followerId).getTotalChunks()); + } + } catch (IOException e) { + LOG.error(e, "InstallSnapshot failed for Leader."); + } + } + + /** + * Acccepts snaphot as ByteString, enters into map for future chunks + * creates and return a ByteString chunk + */ + private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException { + FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId); + if (followerToSnapshot == null) { + followerToSnapshot = new FollowerToSnapshot(snapshotBytes); + mapFollowerToSnapshot.put(followerId, followerToSnapshot); + } + ByteString nextChunk = followerToSnapshot.getNextChunk(); + if (LOG.isDebugEnabled()) { + LOG.debug("Leader's snapshot nextChunk size:{}", nextChunk.size()); + } + return nextChunk; + } + + private void sendHeartBeat() { + if (followers.size() > 0) { + sendAppendEntries(); + } + } + + private void stopHeartBeat() { + if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) { + heartbeatSchedule.cancel(); + } + } + + private void scheduleHeartBeat(FiniteDuration interval) { + if(followers.size() == 0){ + // Optimization - do not bother scheduling a heartbeat as there are + // no followers + return; + } + + stopHeartBeat(); + + // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat + // message is sent to itself. + // Scheduling the heartbeat only once here because heartbeats do not + // need to be sent if there are other messages being sent to the remote + // actor. + heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce( + interval, context.getActor(), new SendHeartBeat(), + context.getActorSystem().dispatcher(), context.getActor()); + } + + @Override + public void close() throws Exception { + stopHeartBeat(); + } + + @Override + public String getLeaderId() { + return context.getId(); + } + + protected boolean isLeaderIsolated() { + int minPresent = minIsolatedLeaderPeerCount; + for (FollowerLogInformation followerLogInformation : followerToLog.values()) { + if (followerLogInformation.isFollowerActive()) { + --minPresent; + if (minPresent == 0) { + break; + } + } + } + return (minPresent != 0); + } + + /** + * Encapsulates the snapshot bytestring and handles the logic of sending + * snapshot chunks + */ + protected class FollowerToSnapshot { + private ByteString snapshotBytes; + private int offset = 0; + // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset + private int replyReceivedForOffset; + // if replyStatus is false, the previous chunk is attempted + private boolean replyStatus = false; + private int chunkIndex; + private int totalChunks; + + public FollowerToSnapshot(ByteString snapshotBytes) { + this.snapshotBytes = snapshotBytes; + replyReceivedForOffset = -1; + chunkIndex = 1; + int size = snapshotBytes.size(); + totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) + + ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0); + if(LOG.isDebugEnabled()) { + LOG.debug("Snapshot {} bytes, total chunks to send:{}", + size, totalChunks); + } + } + + public ByteString getSnapshotBytes() { + return snapshotBytes; + } + + public int incrementOffset() { + if(replyStatus) { + // if prev chunk failed, we would want to sent the same chunk again + offset = offset + context.getConfigParams().getSnapshotChunkSize(); + } + return offset; + } + + public int incrementChunkIndex() { + if (replyStatus) { + // if prev chunk failed, we would want to sent the same chunk again + chunkIndex = chunkIndex + 1; + } + return chunkIndex; + } + + public int getChunkIndex() { + return chunkIndex; + } + + public int getTotalChunks() { + return totalChunks; + } + + public boolean canSendNextChunk() { + // we only send a false if a chunk is sent but we have not received a reply yet + return replyReceivedForOffset == offset; + } + + public boolean isLastChunk(int chunkIndex) { + return totalChunks == chunkIndex; + } + + public void markSendStatus(boolean success) { + if (success) { + // if the chunk sent was successful + replyReceivedForOffset = offset; + replyStatus = true; + } else { + // if the chunk sent was failure + replyReceivedForOffset = offset; + replyStatus = false; + } + } + + public ByteString getNextChunk() { + int snapshotLength = getSnapshotBytes().size(); + int start = incrementOffset(); + int size = context.getConfigParams().getSnapshotChunkSize(); + if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) { + size = snapshotLength; + } else { + if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) { + size = snapshotLength - start; + } + } + + if(LOG.isDebugEnabled()) { + LOG.debug("length={}, offset={},size={}", + snapshotLength, start, size); + } + return getSnapshotBytes().substring(start, start + size); + + } + } + + // called from example-actor for printing the follower-states + public String printFollowerStates() { + StringBuilder sb = new StringBuilder(); + for(FollowerLogInformation followerLogInformation : followerToLog.values()) { + boolean isFollowerActive = followerLogInformation.isFollowerActive(); + sb.append("{"+followerLogInformation.getId() + " state:" + isFollowerActive + "},"); + + } + return "[" + sb.toString() + "]"; + } + + @VisibleForTesting + void markFollowerActive(String followerId) { + followerToLog.get(followerId).markFollowerActive(); + } +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java index eed74bba82..f235221da9 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java @@ -390,7 +390,7 @@ public abstract class AbstractRaftActorBehavior implements RaftActorBehavior { } protected RaftActorBehavior switchBehavior(RaftActorBehavior behavior) { - LOG.info("Switching from behavior {} to {}", this.state(), behavior.state()); + LOG.info("{} :- Switching from behavior {} to {}", context.getId(), this.state(), behavior.state()); try { close(); } catch (Exception e) { @@ -399,4 +399,27 @@ public abstract class AbstractRaftActorBehavior implements RaftActorBehavior { return behavior; } + + protected int getMajorityVoteCount(int numPeers) { + // Votes are required from a majority of the peers including self. + // The numMajority field therefore stores a calculated value + // of the number of votes required for this candidate to win an + // election based on it's known peers. + // If a peer was added during normal operation and raft replicas + // came to know about them then the new peer would also need to be + // taken into consideration when calculating this value. + // Here are some examples for what the numMajority would be for n + // peers + // 0 peers = 1 numMajority -: (0 + 1) / 2 + 1 = 1 + // 2 peers = 2 numMajority -: (2 + 1) / 2 + 1 = 2 + // 4 peers = 3 numMajority -: (4 + 1) / 2 + 1 = 3 + + int numMajority = 0; + if (numPeers > 0) { + int self = 1; + numMajority = (numPeers + self) / 2 + 1; + } + return numMajority; + + } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Candidate.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Candidate.java index 4a3e2c5d66..702417273f 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Candidate.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Candidate.java @@ -56,25 +56,7 @@ public class Candidate extends AbstractRaftActorBehavior { LOG.debug("Election:Candidate has following peers: {}", peers); } - if(peers.size() > 0) { - // Votes are required from a majority of the peers including self. - // The votesRequired field therefore stores a calculated value - // of the number of votes required for this candidate to win an - // election based on it's known peers. - // If a peer was added during normal operation and raft replicas - // came to know about them then the new peer would also need to be - // taken into consideration when calculating this value. - // Here are some examples for what the votesRequired would be for n - // peers - // 0 peers = 1 votesRequired (0 + 1) / 2 + 1 = 1 - // 2 peers = 2 votesRequired (2 + 1) / 2 + 1 = 2 - // 4 peers = 3 votesRequired (4 + 1) / 2 + 1 = 3 - int noOfPeers = peers.size(); - int self = 1; - votesRequired = (noOfPeers + self) / 2 + 1; - } else { - votesRequired = 0; - } + votesRequired = getMajorityVoteCount(peers.size()); startNewTerm(); scheduleElection(electionDuration()); diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeader.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeader.java new file mode 100644 index 0000000000..4f77711a4d --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeader.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.raft.behaviors; + +import akka.actor.ActorRef; +import org.opendaylight.controller.cluster.raft.RaftActorContext; +import org.opendaylight.controller.cluster.raft.RaftState; +import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply; + +/** + * Leader which is termed as isolated. + *

      + * If the reply from the majority of the followers is not received then the leader changes its behavior + * to IsolatedLeader. An isolated leader may have followers and they would continue to receive replicated messages. + *

      + * A schedule is run, at an interval of (10 * Heartbeat-time-interval), in the Leader + * to check if its isolated or not. + *

      + * In the Isolated Leader , on every AppendEntriesReply, we aggressively check if the leader is isolated. + * If no, then the state is switched back to Leader. + * + */ +public class IsolatedLeader extends AbstractLeader { + public IsolatedLeader(RaftActorContext context) { + super(context); + } + + // we received an Append Entries reply, we should switch the Behavior to Leader + @Override + protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, + AppendEntriesReply appendEntriesReply) { + RaftActorBehavior ret = super.handleAppendEntriesReply(sender, appendEntriesReply); + + // it can happen that this isolated leader interacts with a new leader in the cluster and + // changes its state to Follower, hence we only need to switch to Leader if the state is still Isolated + if (ret.state() == RaftState.IsolatedLeader && !isLeaderIsolated()) { + LOG.info("IsolatedLeader {} switching from IsolatedLeader to Leader", leaderId); + return switchBehavior(new Leader(context)); + } + return ret; + } + + @Override + public RaftState state() { + return RaftState.IsolatedLeader; + } +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java index 9edba85865..0dd3900113 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java @@ -9,38 +9,14 @@ package org.opendaylight.controller.cluster.raft.behaviors; import akka.actor.ActorRef; -import akka.actor.ActorSelection; import akka.actor.Cancellable; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import com.google.protobuf.ByteString; -import org.opendaylight.controller.cluster.raft.ClientRequestTracker; -import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl; -import org.opendaylight.controller.cluster.raft.FollowerLogInformation; -import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl; import org.opendaylight.controller.cluster.raft.RaftActorContext; -import org.opendaylight.controller.cluster.raft.RaftState; -import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry; -import org.opendaylight.controller.cluster.raft.base.messages.Replicate; -import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat; -import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot; -import org.opendaylight.controller.cluster.raft.messages.AppendEntries; -import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply; -import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot; -import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply; -import org.opendaylight.controller.cluster.raft.messages.RaftRPC; -import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply; +import org.opendaylight.controller.cluster.raft.base.messages.InitiateInstallSnapshot; +import org.opendaylight.controller.cluster.raft.base.messages.IsolatedLeaderCheck; import scala.concurrent.duration.FiniteDuration; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - /** * The behavior of a RaftActor when it is in the Leader state *

      @@ -63,448 +39,41 @@ import java.util.concurrent.atomic.AtomicLong; * of matchIndex[i] ≥ N, and log[N].term == currentTerm: * set commitIndex = N (§5.3, §5.4). */ -public class Leader extends AbstractRaftActorBehavior { - - - protected final Map followerToLog = - new HashMap(); - protected final Map mapFollowerToSnapshot = new HashMap<>(); - - private final Set followers; - - private Cancellable heartbeatSchedule = null; - private Cancellable appendEntriesSchedule = null; +public class Leader extends AbstractLeader { private Cancellable installSnapshotSchedule = null; - - private List trackerList = new ArrayList<>(); - - private final int minReplicationCount; + private Cancellable isolatedLeaderCheckSchedule = null; public Leader(RaftActorContext context) { super(context); - followers = context.getPeerAddresses().keySet(); - - for (String followerId : followers) { - FollowerLogInformation followerLogInformation = - new FollowerLogInformationImpl(followerId, - new AtomicLong(context.getCommitIndex()), - new AtomicLong(-1)); - - followerToLog.put(followerId, followerLogInformation); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("Election:Leader has following peers: {}", followers); - } - - if (followers.size() > 0) { - minReplicationCount = (followers.size() + 1) / 2 + 1; - } else { - minReplicationCount = 0; - } - - - // Immediately schedule a heartbeat - // Upon election: send initial empty AppendEntries RPCs - // (heartbeat) to each server; repeat during idle periods to - // prevent election timeouts (§5.2) - scheduleHeartBeat(new FiniteDuration(0, TimeUnit.SECONDS)); - - scheduleInstallSnapshotCheck( - new FiniteDuration(context.getConfigParams().getHeartBeatInterval().length() * 1000, - context.getConfigParams().getHeartBeatInterval().unit()) - ); - - } - - @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender, - AppendEntries appendEntries) { - - if(LOG.isDebugEnabled()) { - LOG.debug(appendEntries.toString()); - } - - return this; - } - - @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, - AppendEntriesReply appendEntriesReply) { - - if(! appendEntriesReply.isSuccess()) { - if(LOG.isDebugEnabled()) { - LOG.debug(appendEntriesReply.toString()); - } - } - - // Update the FollowerLogInformation - String followerId = appendEntriesReply.getFollowerId(); - FollowerLogInformation followerLogInformation = - followerToLog.get(followerId); - - if(followerLogInformation == null){ - LOG.error("Unknown follower {}", followerId); - return this; - } - - if (appendEntriesReply.isSuccess()) { - followerLogInformation - .setMatchIndex(appendEntriesReply.getLogLastIndex()); - followerLogInformation - .setNextIndex(appendEntriesReply.getLogLastIndex() + 1); - } else { - - // TODO: When we find that the follower is out of sync with the - // Leader we simply decrement that followers next index by 1. - // Would it be possible to do better than this? The RAFT spec - // does not explicitly deal with it but may be something for us to - // think about - - followerLogInformation.decrNextIndex(); - } - - // Now figure out if this reply warrants a change in the commitIndex - // If there exists an N such that N > commitIndex, a majority - // of matchIndex[i] ≥ N, and log[N].term == currentTerm: - // set commitIndex = N (§5.3, §5.4). - for (long N = context.getCommitIndex() + 1; ; N++) { - int replicatedCount = 1; - - for (FollowerLogInformation info : followerToLog.values()) { - if (info.getMatchIndex().get() >= N) { - replicatedCount++; - } - } - - if (replicatedCount >= minReplicationCount) { - ReplicatedLogEntry replicatedLogEntry = - context.getReplicatedLog().get(N); - if (replicatedLogEntry != null - && replicatedLogEntry.getTerm() - == currentTerm()) { - context.setCommitIndex(N); - } - } else { - break; - } - } - - // Apply the change to the state machine - if (context.getCommitIndex() > context.getLastApplied()) { - applyLogToStateMachine(context.getCommitIndex()); - } - - return this; - } - - protected ClientRequestTracker removeClientRequestTracker(long logIndex) { - - ClientRequestTracker toRemove = findClientRequestTracker(logIndex); - if(toRemove != null) { - trackerList.remove(toRemove); - } - - return toRemove; - } - - protected ClientRequestTracker findClientRequestTracker(long logIndex) { - for (ClientRequestTracker tracker : trackerList) { - if (tracker.getIndex() == logIndex) { - return tracker; - } - } - - return null; - } - - @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender, - RequestVoteReply requestVoteReply) { - return this; - } + scheduleInstallSnapshotCheck(context.getConfigParams().getIsolatedCheckInterval()); - @Override public RaftState state() { - return RaftState.Leader; + scheduleIsolatedLeaderCheck( + new FiniteDuration(context.getConfigParams().getHeartBeatInterval().length() * 10, + context.getConfigParams().getHeartBeatInterval().unit())); } @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) { Preconditions.checkNotNull(sender, "sender should not be null"); - Object message = fromSerializableMessage(originalMessage); - - if (message instanceof RaftRPC) { - RaftRPC rpc = (RaftRPC) message; - // If RPC request or response contains term T > currentTerm: - // set currentTerm = T, convert to follower (§5.1) - // This applies to all RPC messages and responses - if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) { - context.getTermInformation().updateAndPersist(rpc.getTerm(), null); - - return switchBehavior(new Follower(context)); - } - } - - try { - if (message instanceof SendHeartBeat) { - sendHeartBeat(); - return this; - } else if(message instanceof SendInstallSnapshot) { - installSnapshotIfNeeded(); - } else if (message instanceof Replicate) { - replicate((Replicate) message); - } else if (message instanceof InstallSnapshotReply){ - handleInstallSnapshotReply( - (InstallSnapshotReply) message); - } - } finally { - scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval()); - } - - return super.handleMessage(sender, message); - } - - private void handleInstallSnapshotReply(InstallSnapshotReply reply) { - String followerId = reply.getFollowerId(); - FollowerToSnapshot followerToSnapshot = - mapFollowerToSnapshot.get(followerId); - - if (followerToSnapshot != null && - followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) { - - if (reply.isSuccess()) { - if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) { - //this was the last chunk reply - if(LOG.isDebugEnabled()) { - LOG.debug("InstallSnapshotReply received, " + - "last chunk received, Chunk:{}. Follower:{} Setting nextIndex:{}", - reply.getChunkIndex(), followerId, - context.getReplicatedLog().getSnapshotIndex() + 1 - ); - } - - FollowerLogInformation followerLogInformation = - followerToLog.get(followerId); - followerLogInformation.setMatchIndex( - context.getReplicatedLog().getSnapshotIndex()); - followerLogInformation.setNextIndex( - context.getReplicatedLog().getSnapshotIndex() + 1); - mapFollowerToSnapshot.remove(followerId); - - if(LOG.isDebugEnabled()) { - LOG.debug("followerToLog.get(followerId).getNextIndex().get()=" + - followerToLog.get(followerId).getNextIndex().get()); - } - - } else { - followerToSnapshot.markSendStatus(true); - } - } else { - LOG.info("InstallSnapshotReply received, " + - "sending snapshot chunk failed, Will retry, Chunk:{}", - reply.getChunkIndex() - ); - followerToSnapshot.markSendStatus(false); + if (originalMessage instanceof IsolatedLeaderCheck) { + if (isLeaderIsolated()) { + LOG.info("At least {} followers need to be active, Switching {} from Leader to IsolatedLeader", + minIsolatedLeaderPeerCount, leaderId); + return switchBehavior(new IsolatedLeader(context)); } - - } else { - LOG.error("ERROR!!" + - "FollowerId in InstallSnapshotReply not known to Leader" + - " or Chunk Index in InstallSnapshotReply not matching {} != {}", - followerToSnapshot.getChunkIndex(), reply.getChunkIndex() - ); - } - } - - private void replicate(Replicate replicate) { - long logIndex = replicate.getReplicatedLogEntry().getIndex(); - - if(LOG.isDebugEnabled()) { - LOG.debug("Replicate message {}", logIndex); } - // Create a tracker entry we will use this later to notify the - // client actor - trackerList.add( - new ClientRequestTrackerImpl(replicate.getClientActor(), - replicate.getIdentifier(), - logIndex) - ); - - if (followers.size() == 0) { - context.setCommitIndex(logIndex); - applyLogToStateMachine(logIndex); - } else { - sendAppendEntries(); - } + return super.handleMessage(sender, originalMessage); } - private void sendAppendEntries() { - // Send an AppendEntries to all followers - for (String followerId : followers) { - ActorSelection followerActor = context.getPeerActorSelection(followerId); - - if (followerActor != null) { - FollowerLogInformation followerLogInformation = followerToLog.get(followerId); - long followerNextIndex = followerLogInformation.getNextIndex().get(); - List entries = Collections.emptyList(); - - if (mapFollowerToSnapshot.get(followerId) != null) { - if (mapFollowerToSnapshot.get(followerId).canSendNextChunk()) { - sendSnapshotChunk(followerActor, followerId); - } - - } else { - - if (context.getReplicatedLog().isPresent(followerNextIndex)) { - // FIXME : Sending one entry at a time - entries = context.getReplicatedLog().getFrom(followerNextIndex, 1); - - followerActor.tell( - new AppendEntries(currentTerm(), context.getId(), - prevLogIndex(followerNextIndex), - prevLogTerm(followerNextIndex), entries, - context.getCommitIndex()).toSerializable(), - actor() - ); - - } else { - // if the followers next index is not present in the leaders log, then snapshot should be sent - long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex(); - long leaderLastIndex = context.getReplicatedLog().lastIndex(); - if (followerNextIndex >= 0 && leaderLastIndex >= followerNextIndex ) { - // if the follower is just not starting and leader's index - // is more than followers index - if(LOG.isDebugEnabled()) { - LOG.debug("SendInstallSnapshot to follower:{}," + - "follower-nextIndex:{}, leader-snapshot-index:{}, " + - "leader-last-index:{}", followerId, - followerNextIndex, leaderSnapShotIndex, leaderLastIndex - ); - } - - actor().tell(new SendInstallSnapshot(), actor()); - } else { - followerActor.tell( - new AppendEntries(currentTerm(), context.getId(), - prevLogIndex(followerNextIndex), - prevLogTerm(followerNextIndex), entries, - context.getCommitIndex()).toSerializable(), - actor() - ); - } - } - } - } - } - } - - /** - * An installSnapshot is scheduled at a interval that is a multiple of - * a HEARTBEAT_INTERVAL. This is to avoid the need to check for installing - * snapshots at every heartbeat. - */ - private void installSnapshotIfNeeded(){ - for (String followerId : followers) { - ActorSelection followerActor = - context.getPeerActorSelection(followerId); - - if(followerActor != null) { - FollowerLogInformation followerLogInformation = - followerToLog.get(followerId); - - long nextIndex = followerLogInformation.getNextIndex().get(); - - if (!context.getReplicatedLog().isPresent(nextIndex) && - context.getReplicatedLog().isInSnapshot(nextIndex)) { - sendSnapshotChunk(followerActor, followerId); - } - } - } - } - - /** - * Sends a snapshot chunk to a given follower - * InstallSnapshot should qualify as a heartbeat too. - */ - private void sendSnapshotChunk(ActorSelection followerActor, String followerId) { - try { - followerActor.tell( - new InstallSnapshot(currentTerm(), context.getId(), - context.getReplicatedLog().getSnapshotIndex(), - context.getReplicatedLog().getSnapshotTerm(), - getNextSnapshotChunk(followerId, - context.getReplicatedLog().getSnapshot()), - mapFollowerToSnapshot.get(followerId).incrementChunkIndex(), - mapFollowerToSnapshot.get(followerId).getTotalChunks() - ).toSerializable(), - actor() - ); - LOG.info("InstallSnapshot sent to follower {}, Chunk: {}/{}", - followerActor.path(), mapFollowerToSnapshot.get(followerId).getChunkIndex(), - mapFollowerToSnapshot.get(followerId).getTotalChunks()); - } catch (IOException e) { - LOG.error(e, "InstallSnapshot failed for Leader."); - } - } - - /** - * Acccepts snaphot as ByteString, enters into map for future chunks - * creates and return a ByteString chunk - */ - private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException { - FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId); - if (followerToSnapshot == null) { - followerToSnapshot = new FollowerToSnapshot(snapshotBytes); - mapFollowerToSnapshot.put(followerId, followerToSnapshot); - } - ByteString nextChunk = followerToSnapshot.getNextChunk(); - if(LOG.isDebugEnabled()) { - LOG.debug("Leader's snapshot nextChunk size:{}", nextChunk.size()); - } - - return nextChunk; - } - - private void sendHeartBeat() { - if (followers.size() > 0) { - sendAppendEntries(); - } - } - - private void stopHeartBeat() { - if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) { - heartbeatSchedule.cancel(); - } - } - - private void stopInstallSnapshotSchedule() { + protected void stopInstallSnapshotSchedule() { if (installSnapshotSchedule != null && !installSnapshotSchedule.isCancelled()) { installSnapshotSchedule.cancel(); } } - private void scheduleHeartBeat(FiniteDuration interval) { - if(followers.size() == 0){ - // Optimization - do not bother scheduling a heartbeat as there are - // no followers - return; - } - - stopHeartBeat(); - - // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat - // message is sent to itself. - // Scheduling the heartbeat only once here because heartbeats do not - // need to be sent if there are other messages being sent to the remote - // actor. - heartbeatSchedule = - context.getActorSystem().scheduler().scheduleOnce( - interval, - context.getActor(), new SendHeartBeat(), - context.getActorSystem().dispatcher(), context.getActor()); - } - - - private void scheduleInstallSnapshotCheck(FiniteDuration interval) { + protected void scheduleInstallSnapshotCheck(FiniteDuration interval) { if(followers.size() == 0){ // Optimization - do not bother scheduling a heartbeat as there are // no followers @@ -518,115 +87,30 @@ public class Leader extends AbstractRaftActorBehavior { installSnapshotSchedule = context.getActorSystem().scheduler().scheduleOnce( interval, - context.getActor(), new SendInstallSnapshot(), + context.getActor(), new InitiateInstallSnapshot(), context.getActorSystem().dispatcher(), context.getActor()); } - - - @Override public void close() throws Exception { - stopHeartBeat(); + protected void stopIsolatedLeaderCheckSchedule() { + if (isolatedLeaderCheckSchedule != null && !isolatedLeaderCheckSchedule.isCancelled()) { + isolatedLeaderCheckSchedule.cancel(); + } } - @Override public String getLeaderId() { - return context.getId(); + protected void scheduleIsolatedLeaderCheck(FiniteDuration isolatedCheckInterval) { + isolatedLeaderCheckSchedule = context.getActorSystem().scheduler().schedule(isolatedCheckInterval, isolatedCheckInterval, + context.getActor(), new IsolatedLeaderCheck(), + context.getActorSystem().dispatcher(), context.getActor()); } - /** - * Encapsulates the snapshot bytestring and handles the logic of sending - * snapshot chunks - */ - protected class FollowerToSnapshot { - private ByteString snapshotBytes; - private int offset = 0; - // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset - private int replyReceivedForOffset; - // if replyStatus is false, the previous chunk is attempted - private boolean replyStatus = false; - private int chunkIndex; - private int totalChunks; - - public FollowerToSnapshot(ByteString snapshotBytes) { - this.snapshotBytes = snapshotBytes; - replyReceivedForOffset = -1; - chunkIndex = 1; - int size = snapshotBytes.size(); - totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) + - ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0); - if(LOG.isDebugEnabled()) { - LOG.debug("Snapshot {} bytes, total chunks to send:{}", - size, totalChunks); - } - } - - public ByteString getSnapshotBytes() { - return snapshotBytes; - } - - public int incrementOffset() { - if(replyStatus) { - // if prev chunk failed, we would want to sent the same chunk again - offset = offset + context.getConfigParams().getSnapshotChunkSize(); - } - return offset; - } - - public int incrementChunkIndex() { - if (replyStatus) { - // if prev chunk failed, we would want to sent the same chunk again - chunkIndex = chunkIndex + 1; - } - return chunkIndex; - } - - public int getChunkIndex() { - return chunkIndex; - } - - public int getTotalChunks() { - return totalChunks; - } - - public boolean canSendNextChunk() { - // we only send a false if a chunk is sent but we have not received a reply yet - return replyReceivedForOffset == offset; - } - - public boolean isLastChunk(int chunkIndex) { - return totalChunks == chunkIndex; - } - - public void markSendStatus(boolean success) { - if (success) { - // if the chunk sent was successful - replyReceivedForOffset = offset; - replyStatus = true; - } else { - // if the chunk sent was failure - replyReceivedForOffset = offset; - replyStatus = false; - } - } - - public ByteString getNextChunk() { - int snapshotLength = getSnapshotBytes().size(); - int start = incrementOffset(); - int size = context.getConfigParams().getSnapshotChunkSize(); - if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) { - size = snapshotLength; - } else { - if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) { - size = snapshotLength - start; - } - } - - if(LOG.isDebugEnabled()) { - LOG.debug("length={}, offset={},size={}", - snapshotLength, start, size); - } - return getSnapshotBytes().substring(start, start + size); - - } + @Override public void close() throws Exception { + stopInstallSnapshotSchedule(); + stopIsolatedLeaderCheckSchedule(); + super.close(); } + @VisibleForTesting + void markFollowerActive(String followerId) { + followerToLog.get(followerId).markFollowerActive(); + } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/AddRaftPeer.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/AddRaftPeer.java deleted file mode 100644 index d1f4c43c86..0000000000 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/AddRaftPeer.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.opendaylight.controller.cluster.raft.client.messages; - -/** - * Created by kramesha on 7/17/14. - */ -public class AddRaftPeer { - - private String name; - private String address; - - public AddRaftPeer(String name, String address) { - this.name = name; - this.address = address; - } - - public String getName() { - return name; - } - - public String getAddress() { - return address; - } -} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/FindLeader.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/FindLeader.java index 98dd0d4653..eebbde3393 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/FindLeader.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/FindLeader.java @@ -11,5 +11,6 @@ package org.opendaylight.controller.cluster.raft.client.messages; import java.io.Serializable; public class FindLeader implements Serializable{ + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/FindLeaderReply.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/FindLeaderReply.java index 64c7350896..8b2e45aa06 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/FindLeaderReply.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/FindLeaderReply.java @@ -11,6 +11,7 @@ package org.opendaylight.controller.cluster.raft.client.messages; import java.io.Serializable; public class FindLeaderReply implements Serializable { + private static final long serialVersionUID = 1L; private final String leaderActor; public FindLeaderReply(String leaderActor) { diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/RemoveRaftPeer.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/RemoveRaftPeer.java deleted file mode 100644 index 4b766e04b7..0000000000 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/client/messages/RemoveRaftPeer.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.opendaylight.controller.cluster.raft.client.messages; - -/** - * Created by kramesha on 7/17/14. - */ -public class RemoveRaftPeer { - private String name; - - public RemoveRaftPeer(String name) { - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AbstractRaftRPC.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AbstractRaftRPC.java index 33d8a68686..0122d45c30 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AbstractRaftRPC.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AbstractRaftRPC.java @@ -9,6 +9,7 @@ package org.opendaylight.controller.cluster.raft.messages; public class AbstractRaftRPC implements RaftRPC { + private static final long serialVersionUID = 1L; // term protected long term; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AppendEntries.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AppendEntries.java index 5149cf9f34..e5aebaa6be 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AppendEntries.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AppendEntries.java @@ -24,10 +24,10 @@ import java.util.Map; * heartbeat (§5.2). */ public class AppendEntries extends AbstractRaftRPC { - - public static final Class SERIALIZABLE_CLASS = AppendEntriesMessages.AppendEntries.class; + public static final Class SERIALIZABLE_CLASS = AppendEntriesMessages.AppendEntries.class; private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(AppendEntries.class); + private static final long serialVersionUID = 1L; // So that follower can redirect clients private final String leaderId; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AppendEntriesReply.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AppendEntriesReply.java index b923baa716..a782eda565 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AppendEntriesReply.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/AppendEntriesReply.java @@ -12,6 +12,7 @@ package org.opendaylight.controller.cluster.raft.messages; * Reply for the AppendEntriesRpc message */ public class AppendEntriesReply extends AbstractRaftRPC { + private static final long serialVersionUID = 1L; // true if follower contained entry matching // prevLogIndex and prevLogTerm diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshot.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshot.java index c084cba822..3c4e8117c7 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshot.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshot.java @@ -13,7 +13,8 @@ import org.opendaylight.controller.protobuff.messages.cluster.raft.InstallSnapsh public class InstallSnapshot extends AbstractRaftRPC { - public static final Class SERIALIZABLE_CLASS = InstallSnapshotMessages.InstallSnapshot.class; + public static final Class SERIALIZABLE_CLASS = InstallSnapshotMessages.InstallSnapshot.class; + private static final long serialVersionUID = 1L; private final String leaderId; private final long lastIncludedIndex; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshotReply.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshotReply.java index d293a47c8e..71e7ecc189 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshotReply.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/InstallSnapshotReply.java @@ -9,6 +9,7 @@ package org.opendaylight.controller.cluster.raft.messages; public class InstallSnapshotReply extends AbstractRaftRPC { + private static final long serialVersionUID = 1L; // The followerId - this will be used to figure out which follower is // responding diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/RequestVote.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/RequestVote.java index 6ef2a06285..8321d0c25b 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/RequestVote.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/RequestVote.java @@ -12,6 +12,7 @@ package org.opendaylight.controller.cluster.raft.messages; * Invoked by candidates to gather votes (§5.2). */ public class RequestVote extends AbstractRaftRPC { + private static final long serialVersionUID = 1L; // candidate requesting vote private String candidateId; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/RequestVoteReply.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/RequestVoteReply.java index df80b4e5e2..da3ba5c39f 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/RequestVoteReply.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/messages/RequestVoteReply.java @@ -9,6 +9,7 @@ package org.opendaylight.controller.cluster.raft.messages; public class RequestVoteReply extends AbstractRaftRPC { + private static final long serialVersionUID = 1L; // true means candidate received vot private final boolean voteGranted; diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImplTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImplTest.java index 913665861d..398a2e9b36 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImplTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImplTest.java @@ -7,21 +7,19 @@ */ package org.opendaylight.controller.cluster.raft; -import junit.framework.Assert; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload; -import static org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockReplicatedLogEntry; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload; +import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockReplicatedLogEntry; /** * */ @@ -65,7 +63,7 @@ public class AbstractReplicatedLogImplTest { // now create a snapshot of 3 entries, with 1 unapplied entry left in the log // It removes the entries which have made it to snapshot // and updates the snapshot index and term - Map state = takeSnapshot(3); + Map state = takeSnapshot(3); // check the values after the snapshot. // each index value passed in the test is the logical index (log entry index) @@ -131,8 +129,8 @@ public class AbstractReplicatedLogImplTest { } // create a snapshot for test - public Map takeSnapshot(int numEntries) { - Map map = new HashMap(numEntries); + public Map takeSnapshot(final int numEntries) { + Map map = new HashMap<>(numEntries); List entries = replicatedLogImpl.getEntriesTill(numEntries); for (ReplicatedLogEntry entry : entries) { map.put(entry.getIndex(), entry.getData().toString()); @@ -149,22 +147,24 @@ public class AbstractReplicatedLogImplTest { } class MockAbstractReplicatedLogImpl extends AbstractReplicatedLogImpl { @Override - public void appendAndPersist(ReplicatedLogEntry replicatedLogEntry) { + public void appendAndPersist(final ReplicatedLogEntry replicatedLogEntry) { } @Override - public void removeFromAndPersist(long index) { + public void removeFromAndPersist(final long index) { } - public void setSnapshotIndex(long snapshotIndex) { + @Override + public void setSnapshotIndex(final long snapshotIndex) { this.snapshotIndex = snapshotIndex; } - public void setSnapshotTerm(long snapshotTerm) { + @Override + public void setSnapshotTerm(final long snapshotTerm) { this.snapshotTerm = snapshotTerm; } - public List getEntriesTill(int index) { + public List getEntriesTill(final int index) { return journal.subList(0, index); } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/FollowerLogInformationImplTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/FollowerLogInformationImplTest.java new file mode 100644 index 0000000000..7df9f3713f --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/FollowerLogInformationImplTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.raft; + + +import com.google.common.base.Stopwatch; +import com.google.common.util.concurrent.Uninterruptibles; +import org.junit.Test; +import scala.concurrent.duration.FiniteDuration; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class FollowerLogInformationImplTest { + + @Test + public void testIsFollowerActive() { + + FiniteDuration timeoutDuration = + new FiniteDuration(500, TimeUnit.MILLISECONDS); + + FollowerLogInformation followerLogInformation = + new FollowerLogInformationImpl( + "follower1", new AtomicLong(10), new AtomicLong(9), timeoutDuration); + + + + assertFalse("Follower should be termed inactive before stopwatch starts", + followerLogInformation.isFollowerActive()); + + followerLogInformation.markFollowerActive(); + if (sleepWithElaspsedTimeReturned(200) > 200) { + return; + } + assertTrue("Follower should be active", followerLogInformation.isFollowerActive()); + + if (sleepWithElaspsedTimeReturned(400) > 400) { + return; + } + assertFalse("Follower should be inactive after time lapsed", + followerLogInformation.isFollowerActive()); + + followerLogInformation.markFollowerActive(); + assertTrue("Follower should be active from inactive", + followerLogInformation.isFollowerActive()); + } + + // we cannot rely comfortably that the sleep will indeed sleep for the desired time + // hence getting the actual elapsed time and do a match. + // if the sleep has spilled over, then return the test gracefully + private long sleepWithElaspsedTimeReturned(long millis) { + Stopwatch stopwatch = new Stopwatch(); + stopwatch.start(); + Uninterruptibles.sleepUninterruptibly(millis, TimeUnit.MILLISECONDS); + stopwatch.stop(); + return stopwatch.elapsed(TimeUnit.MILLISECONDS); + } +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java index 0d5f644b3d..562ca213a9 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java @@ -33,7 +33,7 @@ public class MockRaftActorContext implements RaftActorContext { private long lastApplied = 0; private final ElectionTerm electionTerm; private ReplicatedLog replicatedLog; - private Map peerAddresses = new HashMap(); + private Map peerAddresses = new HashMap<>(); private ConfigParams configParams; public MockRaftActorContext(){ @@ -198,6 +198,7 @@ public class MockRaftActorContext implements RaftActorContext { } public static class MockPayload extends Payload implements Serializable { + private static final long serialVersionUID = 1L; private String value = ""; public MockPayload(){ @@ -231,6 +232,7 @@ public class MockRaftActorContext implements RaftActorContext { } public static class MockReplicatedLogEntry implements ReplicatedLogEntry, Serializable { + private static final long serialVersionUID = 1L; private final long term; private final long index; diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/RaftActorTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/RaftActorTest.java index c15c9198bd..9eb2fb757b 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/RaftActorTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/RaftActorTest.java @@ -5,21 +5,44 @@ import akka.actor.ActorSystem; import akka.actor.PoisonPill; import akka.actor.Props; import akka.actor.Terminated; -import akka.event.Logging; import akka.japi.Creator; +import akka.japi.Procedure; +import akka.pattern.Patterns; +import akka.persistence.RecoveryCompleted; +import akka.persistence.SaveSnapshotFailure; +import akka.persistence.SaveSnapshotSuccess; +import akka.persistence.SnapshotMetadata; +import akka.persistence.SnapshotOffer; +import akka.persistence.SnapshotSelectionCriteria; import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; +import akka.util.Timeout; import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.protobuf.ByteString; import org.junit.After; +import org.junit.Assert; import org.junit.Test; +import org.opendaylight.controller.cluster.DataPersistenceProvider; +import org.opendaylight.controller.cluster.datastore.DataPersistenceProviderMonitor; import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries; +import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot; +import org.opendaylight.controller.cluster.raft.base.messages.ApplyState; +import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; +import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply; +import org.opendaylight.controller.cluster.raft.behaviors.Follower; +import org.opendaylight.controller.cluster.raft.behaviors.Leader; import org.opendaylight.controller.cluster.raft.client.messages.FindLeader; import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; import org.opendaylight.controller.cluster.raft.utils.MockAkkaJournal; import org.opendaylight.controller.cluster.raft.utils.MockSnapshotStore; +import scala.concurrent.Await; +import scala.concurrent.Future; +import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -32,7 +55,20 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; public class RaftActorTest extends AbstractActorTest { @@ -45,30 +81,43 @@ public class RaftActorTest extends AbstractActorTest { public static class MockRaftActor extends RaftActor { + private final DataPersistenceProvider dataPersistenceProvider; + private final RaftActor delegate; + public static final class MockRaftActorCreator implements Creator { + private static final long serialVersionUID = 1L; private final Map peerAddresses; private final String id; private final Optional config; + private final DataPersistenceProvider dataPersistenceProvider; private MockRaftActorCreator(Map peerAddresses, String id, - Optional config) { + Optional config, DataPersistenceProvider dataPersistenceProvider) { this.peerAddresses = peerAddresses; this.id = id; this.config = config; + this.dataPersistenceProvider = dataPersistenceProvider; } @Override public MockRaftActor create() throws Exception { - return new MockRaftActor(id, peerAddresses, config); + return new MockRaftActor(id, peerAddresses, config, dataPersistenceProvider); } } private final CountDownLatch recoveryComplete = new CountDownLatch(1); + private final List state; - public MockRaftActor(String id, Map peerAddresses, Optional config) { + public MockRaftActor(String id, Map peerAddresses, Optional config, DataPersistenceProvider dataPersistenceProvider) { super(id, peerAddresses, config); state = new ArrayList<>(); + this.delegate = mock(RaftActor.class); + if(dataPersistenceProvider == null){ + this.dataPersistenceProvider = new PersistentDataProvider(); + } else { + this.dataPersistenceProvider = dataPersistenceProvider; + } } public void waitForRecoveryComplete() { @@ -85,12 +134,23 @@ public class RaftActorTest extends AbstractActorTest { public static Props props(final String id, final Map peerAddresses, Optional config){ - return Props.create(new MockRaftActorCreator(peerAddresses, id, config)); + return Props.create(new MockRaftActorCreator(peerAddresses, id, config, null)); + } + + public static Props props(final String id, final Map peerAddresses, + Optional config, DataPersistenceProvider dataPersistenceProvider){ + return Props.create(new MockRaftActorCreator(peerAddresses, id, config, dataPersistenceProvider)); } + @Override protected void applyState(ActorRef clientActor, String identifier, Object data) { + delegate.applyState(clientActor, identifier, data); + LOG.info("applyState called"); } + + + @Override protected void startLogRecoveryBatch(int maxBatchSize) { } @@ -106,16 +166,18 @@ public class RaftActorTest extends AbstractActorTest { @Override protected void onRecoveryComplete() { + delegate.onRecoveryComplete(); recoveryComplete.countDown(); } @Override protected void applyRecoverySnapshot(ByteString snapshot) { + delegate.applyRecoverySnapshot(snapshot); try { Object data = toObject(snapshot); System.out.println("!!!!!applyRecoverySnapshot: "+data); if (data instanceof List) { - state.addAll((List) data); + state.addAll((List) data); } } catch (Exception e) { e.printStackTrace(); @@ -123,13 +185,20 @@ public class RaftActorTest extends AbstractActorTest { } @Override protected void createSnapshot() { - throw new UnsupportedOperationException("createSnapshot"); + delegate.createSnapshot(); } @Override protected void applySnapshot(ByteString snapshot) { + delegate.applySnapshot(snapshot); } @Override protected void onStateChanged() { + delegate.onStateChanged(); + } + + @Override + protected DataPersistenceProvider persistence() { + return this.dataPersistenceProvider; } @Override public String persistenceId() { @@ -155,6 +224,9 @@ public class RaftActorTest extends AbstractActorTest { return obj; } + public ReplicatedLog getReplicatedLog(){ + return this.getRaftActorContext().getReplicatedLog(); + } } @@ -166,51 +238,69 @@ public class RaftActorTest extends AbstractActorTest { super(actorSystem); raftActor = this.getSystem().actorOf(MockRaftActor.props(actorName, - Collections.EMPTY_MAP, Optional.absent()), actorName); + Collections.emptyMap(), Optional.absent()), actorName); } - public boolean waitForStartup(){ + public ActorRef getRaftActor() { + return raftActor; + } + + public boolean waitForLogMessage(final Class logEventClass, String message){ // Wait for a specific log message to show up return - new JavaTestKit.EventFilter(Logging.Info.class + new JavaTestKit.EventFilter(logEventClass ) { @Override protected Boolean run() { return true; } }.from(raftActor.path().toString()) - .message("Switching from behavior Candidate to Leader") + .message(message) .occurrences(1).exec(); } - public void findLeader(final String expectedLeader){ - raftActor.tell(new FindLeader(), getRef()); - - FindLeaderReply reply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class); - assertEquals("getLeaderActor", expectedLeader, reply.getLeaderActor()); + protected void waitUntilLeader(){ + waitUntilLeader(raftActor); } - public ActorRef getRaftActor() { - return raftActor; + protected void waitUntilLeader(ActorRef actorRef) { + FiniteDuration duration = Duration.create(100, TimeUnit.MILLISECONDS); + for(int i = 0; i < 20 * 5; i++) { + Future future = Patterns.ask(actorRef, new FindLeader(), new Timeout(duration)); + try { + FindLeaderReply resp = (FindLeaderReply) Await.result(future, duration); + if(resp.getLeaderActor() != null) { + return; + } + } catch(TimeoutException e) { + } catch(Exception e) { + System.err.println("FindLeader threw ex"); + e.printStackTrace(); + } + + + Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS); + } + + Assert.fail("Leader not found for actorRef " + actorRef.path()); } + } @Test public void testConstruction() { - boolean started = new RaftActorTestKit(getSystem(), "testConstruction").waitForStartup(); - assertEquals(true, started); + new RaftActorTestKit(getSystem(), "testConstruction").waitUntilLeader(); } @Test public void testFindLeaderWhenLeaderIsSelf(){ RaftActorTestKit kit = new RaftActorTestKit(getSystem(), "testFindLeader"); - kit.waitForStartup(); - kit.findLeader(kit.getRaftActor().path().toString()); + kit.waitUntilLeader(); } @Test @@ -225,7 +315,7 @@ public class RaftActorTest extends AbstractActorTest { config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); ActorRef followerActor = getSystem().actorOf(MockRaftActor.props(persistenceId, - Collections.EMPTY_MAP, Optional.of(config)), persistenceId); + Collections.emptyMap(), Optional.of(config)), persistenceId); watch(followerActor); @@ -279,7 +369,7 @@ public class RaftActorTest extends AbstractActorTest { //reinstate the actor TestActorRef ref = TestActorRef.create(getSystem(), - MockRaftActor.props(persistenceId, Collections.EMPTY_MAP, + MockRaftActor.props(persistenceId, Collections.emptyMap(), Optional.of(config))); ref.underlyingActor().waitForRecoveryComplete(); @@ -294,6 +384,484 @@ public class RaftActorTest extends AbstractActorTest { }}; } + /** + * This test verifies that when recovery is applicable (typically when persistence is true) the RaftActor does + * process recovery messages + * + * @throws Exception + */ + + @Test + public void testHandleRecoveryWhenDataPersistenceRecoveryApplicable() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testHandleRecoveryWhenDataPersistenceRecoveryApplicable"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config)), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + // Wait for akka's recovery to complete so it doesn't interfere. + mockRaftActor.waitForRecoveryComplete(); + + ByteString snapshotBytes = fromObject(Arrays.asList( + new MockRaftActorContext.MockPayload("A"), + new MockRaftActorContext.MockPayload("B"), + new MockRaftActorContext.MockPayload("C"), + new MockRaftActorContext.MockPayload("D"))); + + Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), + Lists.newArrayList(), 3, 1 ,3, 1); + + mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot)); + + verify(mockRaftActor.delegate).applyRecoverySnapshot(eq(snapshotBytes)); + + mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(0, 1, new MockRaftActorContext.MockPayload("A"))); + + ReplicatedLog replicatedLog = mockRaftActor.getReplicatedLog(); + + assertEquals("add replicated log entry", 1, replicatedLog.size()); + + mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(1, 1, new MockRaftActorContext.MockPayload("A"))); + + assertEquals("add replicated log entry", 2, replicatedLog.size()); + + mockRaftActor.onReceiveRecover(new ApplyLogEntries(1)); + + assertEquals("commit index 1", 1, mockRaftActor.getRaftActorContext().getCommitIndex()); + + // The snapshot had 4 items + we added 2 more items during the test + // We start removing from 5 and we should get 1 item in the replicated log + mockRaftActor.onReceiveRecover(new RaftActor.DeleteEntries(5)); + + assertEquals("remove log entries", 1, replicatedLog.size()); + + mockRaftActor.onReceiveRecover(new RaftActor.UpdateElectionTerm(10, "foobar")); + + assertEquals("election term", 10, mockRaftActor.getRaftActorContext().getTermInformation().getCurrentTerm()); + assertEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor()); + + mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class)); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + }}; + } + + /** + * This test verifies that when recovery is not applicable (typically when persistence is false) the RaftActor does + * not process recovery messages + * + * @throws Exception + */ + @Test + public void testHandleRecoveryWhenDataPersistenceRecoveryNotApplicable() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testHandleRecoveryWhenDataPersistenceRecoveryNotApplicable"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), new DataPersistenceProviderMonitor()), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + // Wait for akka's recovery to complete so it doesn't interfere. + mockRaftActor.waitForRecoveryComplete(); + + ByteString snapshotBytes = fromObject(Arrays.asList( + new MockRaftActorContext.MockPayload("A"), + new MockRaftActorContext.MockPayload("B"), + new MockRaftActorContext.MockPayload("C"), + new MockRaftActorContext.MockPayload("D"))); + + Snapshot snapshot = Snapshot.create(snapshotBytes.toByteArray(), + Lists.newArrayList(), 3, 1 ,3, 1); + + mockRaftActor.onReceiveRecover(new SnapshotOffer(new SnapshotMetadata(persistenceId, 100, 100), snapshot)); + + verify(mockRaftActor.delegate, times(0)).applyRecoverySnapshot(any(ByteString.class)); + + mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(0, 1, new MockRaftActorContext.MockPayload("A"))); + + ReplicatedLog replicatedLog = mockRaftActor.getReplicatedLog(); + + assertEquals("add replicated log entry", 0, replicatedLog.size()); + + mockRaftActor.onReceiveRecover(new ReplicatedLogImplEntry(1, 1, new MockRaftActorContext.MockPayload("A"))); + + assertEquals("add replicated log entry", 0, replicatedLog.size()); + + mockRaftActor.onReceiveRecover(new ApplyLogEntries(1)); + + assertEquals("commit index -1", -1, mockRaftActor.getRaftActorContext().getCommitIndex()); + + mockRaftActor.onReceiveRecover(new RaftActor.DeleteEntries(2)); + + assertEquals("remove log entries", 0, replicatedLog.size()); + + mockRaftActor.onReceiveRecover(new RaftActor.UpdateElectionTerm(10, "foobar")); + + assertNotEquals("election term", 10, mockRaftActor.getRaftActorContext().getTermInformation().getCurrentTerm()); + assertNotEquals("voted for", "foobar", mockRaftActor.getRaftActorContext().getTermInformation().getVotedFor()); + + mockRaftActor.onReceiveRecover(mock(RecoveryCompleted.class)); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + }}; + } + + + @Test + public void testUpdatingElectionTermCallsDataPersistence() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testUpdatingElectionTermCallsDataPersistence"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + CountDownLatch persistLatch = new CountDownLatch(1); + DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); + dataPersistenceProviderMonitor.setPersistLatch(persistLatch); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), dataPersistenceProviderMonitor), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + mockRaftActor.getRaftActorContext().getTermInformation().updateAndPersist(10, "foobar"); + + assertEquals("Persist called", true, persistLatch.await(5, TimeUnit.SECONDS)); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + + @Test + public void testAddingReplicatedLogEntryCallsDataPersistence() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testAddingReplicatedLogEntryCallsDataPersistence"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), dataPersistenceProvider), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + MockRaftActorContext.MockReplicatedLogEntry logEntry = new MockRaftActorContext.MockReplicatedLogEntry(10, 10, mock(Payload.class)); + + mockRaftActor.getRaftActorContext().getReplicatedLog().appendAndPersist(logEntry); + + verify(dataPersistenceProvider).persist(eq(logEntry), any(Procedure.class)); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + + @Test + public void testRemovingReplicatedLogEntryCallsDataPersistence() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testRemovingReplicatedLogEntryCallsDataPersistence"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), dataPersistenceProvider), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + mockRaftActor.getReplicatedLog().appendAndPersist(new MockRaftActorContext.MockReplicatedLogEntry(1, 0, mock(Payload.class))); + + mockRaftActor.getRaftActorContext().getReplicatedLog().removeFromAndPersist(0); + + verify(dataPersistenceProvider, times(2)).persist(anyObject(), any(Procedure.class)); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + + @Test + public void testApplyLogEntriesCallsDataPersistence() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testApplyLogEntriesCallsDataPersistence"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), dataPersistenceProvider), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + mockRaftActor.onReceiveCommand(new ApplyLogEntries(10)); + + verify(dataPersistenceProvider, times(1)).persist(anyObject(), any(Procedure.class)); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + + @Test + public void testCaptureSnapshotReplyCallsDataPersistence() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testCaptureSnapshotReplyCallsDataPersistence"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), + MockRaftActor.props(persistenceId,Collections.emptyMap(), + Optional.of(config), dataPersistenceProvider), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + ByteString snapshotBytes = fromObject(Arrays.asList( + new MockRaftActorContext.MockPayload("A"), + new MockRaftActorContext.MockPayload("B"), + new MockRaftActorContext.MockPayload("C"), + new MockRaftActorContext.MockPayload("D"))); + + mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1,1,-1,1)); + + RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext(); + + mockRaftActor.setCurrentBehavior(new Leader(raftActorContext)); + + mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes)); + + verify(dataPersistenceProvider).saveSnapshot(anyObject()); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + + @Test + public void testSaveSnapshotSuccessCallsDataPersistence() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testSaveSnapshotSuccessCallsDataPersistence"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), dataPersistenceProvider), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1,0, mock(Payload.class))); + mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1,1, mock(Payload.class))); + mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1,2, mock(Payload.class))); + mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1,3, mock(Payload.class))); + mockRaftActor.getReplicatedLog().append(new MockRaftActorContext.MockReplicatedLogEntry(1,4, mock(Payload.class))); + + ByteString snapshotBytes = fromObject(Arrays.asList( + new MockRaftActorContext.MockPayload("A"), + new MockRaftActorContext.MockPayload("B"), + new MockRaftActorContext.MockPayload("C"), + new MockRaftActorContext.MockPayload("D"))); + + RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext(); + mockRaftActor.setCurrentBehavior(new Follower(raftActorContext)); + + mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1, 1, 2, 1)); + + verify(mockRaftActor.delegate).createSnapshot(); + + mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes)); + + mockRaftActor.onReceiveCommand(new SaveSnapshotSuccess(new SnapshotMetadata("foo", 100, 100))); + + verify(dataPersistenceProvider).deleteSnapshots(any(SnapshotSelectionCriteria.class)); + + verify(dataPersistenceProvider).deleteMessages(100); + + assertEquals(2, mockRaftActor.getReplicatedLog().size()); + + assertNotNull(mockRaftActor.getReplicatedLog().get(3)); + assertNotNull(mockRaftActor.getReplicatedLog().get(4)); + + // Index 2 will not be in the log because it was removed due to snapshotting + assertNull(mockRaftActor.getReplicatedLog().get(2)); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + + @Test + public void testApplyState() throws Exception { + + new JavaTestKit(getSystem()) { + { + String persistenceId = "testApplyState"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), dataPersistenceProvider), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + ReplicatedLogEntry entry = new MockRaftActorContext.MockReplicatedLogEntry(1, 5, + new MockRaftActorContext.MockPayload("F")); + + mockRaftActor.onReceiveCommand(new ApplyState(mockActorRef, "apply-state", entry)); + + verify(mockRaftActor.delegate).applyState(eq(mockActorRef), eq("apply-state"), anyObject()); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + + @Test + public void testApplySnapshot() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testApplySnapshot"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), dataPersistenceProviderMonitor), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + ReplicatedLog oldReplicatedLog = mockRaftActor.getReplicatedLog(); + + oldReplicatedLog.append(new MockRaftActorContext.MockReplicatedLogEntry(1,0,mock(Payload.class))); + oldReplicatedLog.append(new MockRaftActorContext.MockReplicatedLogEntry(1,1,mock(Payload.class))); + oldReplicatedLog.append( + new MockRaftActorContext.MockReplicatedLogEntry(1, 2, + mock(Payload.class))); + + ByteString snapshotBytes = fromObject(Arrays.asList( + new MockRaftActorContext.MockPayload("A"), + new MockRaftActorContext.MockPayload("B"), + new MockRaftActorContext.MockPayload("C"), + new MockRaftActorContext.MockPayload("D"))); + + Snapshot snapshot = mock(Snapshot.class); + + doReturn(snapshotBytes.toByteArray()).when(snapshot).getState(); + + doReturn(3L).when(snapshot).getLastAppliedIndex(); + + mockRaftActor.onReceiveCommand(new ApplySnapshot(snapshot)); + + verify(mockRaftActor.delegate).applySnapshot(eq(snapshotBytes)); + + assertTrue("The replicatedLog should have changed", + oldReplicatedLog != mockRaftActor.getReplicatedLog()); + + assertEquals("lastApplied should be same as in the snapshot", + (Long) 3L, mockRaftActor.getLastApplied()); + + assertEquals(0, mockRaftActor.getReplicatedLog().size()); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + + @Test + public void testSaveSnapshotFailure() throws Exception { + new JavaTestKit(getSystem()) { + { + String persistenceId = "testSaveSnapshotFailure"; + + DefaultConfigParamsImpl config = new DefaultConfigParamsImpl(); + + config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS)); + + DataPersistenceProviderMonitor dataPersistenceProviderMonitor = new DataPersistenceProviderMonitor(); + + TestActorRef mockActorRef = TestActorRef.create(getSystem(), MockRaftActor.props(persistenceId, + Collections.emptyMap(), Optional.of(config), dataPersistenceProviderMonitor), persistenceId); + + MockRaftActor mockRaftActor = mockActorRef.underlyingActor(); + + ByteString snapshotBytes = fromObject(Arrays.asList( + new MockRaftActorContext.MockPayload("A"), + new MockRaftActorContext.MockPayload("B"), + new MockRaftActorContext.MockPayload("C"), + new MockRaftActorContext.MockPayload("D"))); + + RaftActorContext raftActorContext = mockRaftActor.getRaftActorContext(); + + mockRaftActor.setCurrentBehavior(new Leader(raftActorContext)); + + mockRaftActor.onReceiveCommand(new CaptureSnapshot(-1,1,-1,1)); + + mockRaftActor.onReceiveCommand(new CaptureSnapshotReply(snapshotBytes)); + + mockRaftActor.onReceiveCommand(new SaveSnapshotFailure(new SnapshotMetadata("foobar", 10L, 1234L), + new Exception())); + + assertEquals("Snapshot index should not have advanced because save snapshot failed", -1, + mockRaftActor.getReplicatedLog().getSnapshotIndex()); + + mockActorRef.tell(PoisonPill.getInstance(), getRef()); + + } + }; + } + private ByteString fromObject(Object snapshot) throws Exception { ByteArrayOutputStream b = null; ObjectOutputStream o = null; diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/CandidateTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/CandidateTest.java index a8d47e2c60..485ee4b316 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/CandidateTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/CandidateTest.java @@ -3,23 +3,22 @@ package org.opendaylight.controller.cluster.raft.behaviors; import akka.actor.ActorRef; import akka.actor.Props; import akka.testkit.JavaTestKit; -import junit.framework.Assert; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl; import org.opendaylight.controller.cluster.raft.MockRaftActorContext; import org.opendaylight.controller.cluster.raft.RaftActorContext; +import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry; import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout; import org.opendaylight.controller.cluster.raft.messages.AppendEntries; import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply; import org.opendaylight.controller.cluster.raft.messages.RequestVote; import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply; import org.opendaylight.controller.cluster.raft.utils.DoNothingActor; - import java.util.Collections; import java.util.HashMap; import java.util.Map; - import static org.junit.Assert.assertEquals; public class CandidateTest extends AbstractRaftActorBehaviorTest { @@ -168,7 +167,7 @@ public class CandidateTest extends AbstractRaftActorBehaviorTest { Candidate candidate = new Candidate(createActorContext(getTestActor())); - candidate.handleMessage(getTestActor(), new AppendEntries(0, "test", 0,0,Collections.EMPTY_LIST, 0)); + candidate.handleMessage(getTestActor(), new AppendEntries(0, "test", 0,0,Collections.emptyList(), 0)); final Boolean out = new ExpectMsg(duration("1 seconds"), "AppendEntriesResponse") { // do not put code outside this method, will run afterwards diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/FollowerTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/FollowerTest.java index edeab11e2a..83b9ad3ec7 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/FollowerTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/FollowerTest.java @@ -4,7 +4,6 @@ import akka.actor.ActorRef; import akka.actor.Props; import akka.testkit.JavaTestKit; import com.google.protobuf.ByteString; -import junit.framework.Assert; import org.junit.Test; import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl; import org.opendaylight.controller.cluster.raft.MockRaftActorContext; @@ -87,7 +86,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { RaftActorBehavior raftBehavior = follower.handleMessage(followerActor, new ElectionTimeout()); - Assert.assertTrue(raftBehavior instanceof Candidate); + assertTrue(raftBehavior instanceof Candidate); } @Test diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeaderTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeaderTest.java new file mode 100644 index 0000000000..708068a789 --- /dev/null +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeaderTest.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.raft.behaviors; + +import akka.actor.ActorRef; +import akka.actor.Props; +import akka.testkit.JavaTestKit; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.opendaylight.controller.cluster.raft.MockRaftActorContext; +import org.opendaylight.controller.cluster.raft.RaftActorContext; +import org.opendaylight.controller.cluster.raft.RaftState; +import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply; +import org.opendaylight.controller.cluster.raft.utils.DoNothingActor; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class IsolatedLeaderTest extends AbstractRaftActorBehaviorTest { + + private ActorRef leaderActor = + getSystem().actorOf(Props.create(DoNothingActor.class)); + + private ActorRef senderActor = + getSystem().actorOf(Props.create(DoNothingActor.class)); + + @Override + protected RaftActorBehavior createBehavior( + RaftActorContext actorContext) { + return new Leader(actorContext); + } + + @Override + protected RaftActorContext createActorContext() { + return createActorContext(leaderActor); + } + + + @Test + public void testHandleMessageWithThreeMembers() { + new JavaTestKit(getSystem()) {{ + String followerAddress1 = "akka://test/user/$a"; + String followerAddress2 = "akka://test/user/$b"; + + MockRaftActorContext leaderActorContext = (MockRaftActorContext) createActorContext(); + Map peerAddresses = new HashMap<>(); + peerAddresses.put("follower-1", followerAddress1); + peerAddresses.put("follower-2", followerAddress2); + leaderActorContext.setPeerAddresses(peerAddresses); + + IsolatedLeader isolatedLeader = new IsolatedLeader(leaderActorContext); + assertTrue(isolatedLeader.state() == RaftState.IsolatedLeader); + + // in a 3 node cluster, even if 1 follower is returns a reply, the isolatedLeader is not isolated + RaftActorBehavior behavior = isolatedLeader.handleMessage(senderActor, + new AppendEntriesReply("follower-1", isolatedLeader.lastTerm() - 1, true, + isolatedLeader.lastIndex() - 1, isolatedLeader.lastTerm() - 1)); + + assertEquals(RaftState.Leader, behavior.state()); + + behavior = isolatedLeader.handleMessage(senderActor, + new AppendEntriesReply("follower-2", isolatedLeader.lastTerm() - 1, true, + isolatedLeader.lastIndex() -1, isolatedLeader.lastTerm() -1 )); + + assertEquals(RaftState.Leader, behavior.state()); + }}; + } + + @Test + public void testHandleMessageWithFiveMembers() { + new JavaTestKit(getSystem()) {{ + + String followerAddress1 = "akka://test/user/$a"; + String followerAddress2 = "akka://test/user/$b"; + String followerAddress3 = "akka://test/user/$c"; + String followerAddress4 = "akka://test/user/$d"; + + MockRaftActorContext leaderActorContext = (MockRaftActorContext) createActorContext(); + Map peerAddresses = new HashMap<>(); + peerAddresses.put("follower-1", followerAddress1); + peerAddresses.put("follower-2", followerAddress2); + peerAddresses.put("follower-3", followerAddress3); + peerAddresses.put("follower-4", followerAddress4); + leaderActorContext.setPeerAddresses(peerAddresses); + + IsolatedLeader isolatedLeader = new IsolatedLeader(leaderActorContext); + assertEquals(RaftState.IsolatedLeader, isolatedLeader.state()); + + // in a 5 member cluster, atleast 2 followers need to be active and return a reply + RaftActorBehavior behavior = isolatedLeader.handleMessage(senderActor, + new AppendEntriesReply("follower-1", isolatedLeader.lastTerm() - 1, true, + isolatedLeader.lastIndex() -1, isolatedLeader.lastTerm() -1 )); + + assertEquals(RaftState.IsolatedLeader, behavior.state()); + + behavior = isolatedLeader.handleMessage(senderActor, + new AppendEntriesReply("follower-2", isolatedLeader.lastTerm() - 1, true, + isolatedLeader.lastIndex() -1, isolatedLeader.lastTerm() -1 )); + + assertEquals(RaftState.Leader, behavior.state()); + + behavior = isolatedLeader.handleMessage(senderActor, + new AppendEntriesReply("follower-3", isolatedLeader.lastTerm() - 1, true, + isolatedLeader.lastIndex() -1, isolatedLeader.lastTerm() -1 )); + + assertEquals(RaftState.Leader, behavior.state()); + }}; + } + + @Test + public void testHandleMessageFromAnotherLeader() { + new JavaTestKit(getSystem()) {{ + String followerAddress1 = "akka://test/user/$a"; + String followerAddress2 = "akka://test/user/$b"; + + MockRaftActorContext leaderActorContext = (MockRaftActorContext) createActorContext(); + Map peerAddresses = new HashMap<>(); + peerAddresses.put("follower-1", followerAddress1); + peerAddresses.put("follower-2", followerAddress2); + leaderActorContext.setPeerAddresses(peerAddresses); + + IsolatedLeader isolatedLeader = new IsolatedLeader(leaderActorContext); + assertTrue(isolatedLeader.state() == RaftState.IsolatedLeader); + + // if an append-entries reply is received by the isolated-leader, and that reply + // has a term > than its own term, then IsolatedLeader switches to Follower + // bowing itself to another leader in the cluster + RaftActorBehavior behavior = isolatedLeader.handleMessage(senderActor, + new AppendEntriesReply("follower-1", isolatedLeader.lastTerm() + 1, true, + isolatedLeader.lastIndex() + 1, isolatedLeader.lastTerm() + 1)); + + assertEquals(RaftState.Follower, behavior.state()); + }}; + + } +} diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java index 48543d7de2..6b534deb1f 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java @@ -1,20 +1,34 @@ package org.opendaylight.controller.cluster.raft.behaviors; import akka.actor.ActorRef; -import akka.actor.ActorSystem; +import akka.actor.PoisonPill; import akka.actor.Props; +import akka.actor.Terminated; import akka.testkit.JavaTestKit; +import com.google.common.base.Optional; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.protobuf.ByteString; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl; import org.opendaylight.controller.cluster.raft.FollowerLogInformation; -import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl; import org.opendaylight.controller.cluster.raft.MockRaftActorContext; import org.opendaylight.controller.cluster.raft.RaftActorContext; +import org.opendaylight.controller.cluster.raft.RaftState; import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry; import org.opendaylight.controller.cluster.raft.SerializationUtils; +import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries; import org.opendaylight.controller.cluster.raft.base.messages.ApplyState; +import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; +import org.opendaylight.controller.cluster.raft.base.messages.InitiateInstallSnapshot; +import org.opendaylight.controller.cluster.raft.base.messages.IsolatedLeaderCheck; import org.opendaylight.controller.cluster.raft.base.messages.Replicate; import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat; import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot; @@ -22,18 +36,12 @@ import org.opendaylight.controller.cluster.raft.messages.AppendEntries; import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply; import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot; import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply; +import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply; import org.opendaylight.controller.cluster.raft.utils.DoNothingActor; import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor; import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages; import org.opendaylight.controller.protobuff.messages.cluster.raft.InstallSnapshotMessages; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - +import scala.concurrent.duration.FiniteDuration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -68,10 +76,9 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { ActorRef followerActor = getTestActor(); - MockRaftActorContext actorContext = - (MockRaftActorContext) createActorContext(); + MockRaftActorContext actorContext = (MockRaftActorContext) createActorContext(); - Map peerAddresses = new HashMap(); + Map peerAddresses = new HashMap<>(); peerAddresses.put(followerActor.path().toString(), followerActor.path().toString()); @@ -116,7 +123,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { MockRaftActorContext actorContext = (MockRaftActorContext) createActorContext(); - Map peerAddresses = new HashMap(); + Map peerAddresses = new HashMap<>(); peerAddresses.put(followerActor.path().toString(), followerActor.path().toString()); @@ -151,10 +158,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { }.get(); // this extracts the received message assertEquals("match", out); - } - - }; }}; } @@ -210,229 +214,360 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { } @Test - public void testSendInstallSnapshot() { - new LeaderTestKit(getSystem()) {{ + public void testSendAppendEntriesOnAnInProgressInstallSnapshot() throws Exception { + new JavaTestKit(getSystem()) {{ + ActorRef followerActor = getSystem().actorOf(Props.create(MessageCollectorActor.class)); - new Within(duration("1 seconds")) { - protected void run() { - ActorRef followerActor = getTestActor(); + Map peerAddresses = new HashMap<>(); + peerAddresses.put(followerActor.path().toString(), + followerActor.path().toString()); - Map peerAddresses = new HashMap(); - peerAddresses.put(followerActor.path().toString(), - followerActor.path().toString()); + MockRaftActorContext actorContext = + (MockRaftActorContext) createActorContext(leaderActor); + actorContext.setPeerAddresses(peerAddresses); + Map leadersSnapshot = new HashMap<>(); + leadersSnapshot.put("1", "A"); + leadersSnapshot.put("2", "B"); + leadersSnapshot.put("3", "C"); - MockRaftActorContext actorContext = - (MockRaftActorContext) createActorContext(getRef()); - actorContext.setPeerAddresses(peerAddresses); + //clears leaders log + actorContext.getReplicatedLog().removeFrom(0); + final int followersLastIndex = 2; + final int snapshotIndex = 3; + final int newEntryIndex = 4; + final int snapshotTerm = 1; + final int currentTerm = 2; - Map leadersSnapshot = new HashMap<>(); - leadersSnapshot.put("1", "A"); - leadersSnapshot.put("2", "B"); - leadersSnapshot.put("3", "C"); + // set the snapshot variables in replicatedlog + actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex); + actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm); + actorContext.setCommitIndex(followersLastIndex); + //set follower timeout to 2 mins, helps during debugging + actorContext.setConfigParams(new MockConfigParamsImpl(120000L, 10)); - //clears leaders log - actorContext.getReplicatedLog().removeFrom(0); + MockLeader leader = new MockLeader(actorContext); + + // new entry + ReplicatedLogImplEntry entry = + new ReplicatedLogImplEntry(newEntryIndex, currentTerm, + new MockRaftActorContext.MockPayload("D")); - final int followersLastIndex = 2; - final int snapshotIndex = 3; - final int newEntryIndex = 4; - final int snapshotTerm = 1; - final int currentTerm = 2; + //update follower timestamp + leader.markFollowerActive(followerActor.path().toString()); - // set the snapshot variables in replicatedlog - actorContext.getReplicatedLog().setSnapshot( - toByteString(leadersSnapshot)); - actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex); - actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm); + ByteString bs = toByteString(leadersSnapshot); + leader.setSnapshot(Optional.of(bs)); + leader.createFollowerToSnapshot(followerActor.path().toString(), bs); - MockLeader leader = new MockLeader(actorContext); - // set the follower info in leader - leader.addToFollowerToLog(followerActor.path().toString(), followersLastIndex, -1); + //send first chunk and no InstallSnapshotReply received yet + leader.getFollowerToSnapshot().getNextChunk(); + leader.getFollowerToSnapshot().incrementChunkIndex(); - // new entry - ReplicatedLogImplEntry entry = - new ReplicatedLogImplEntry(newEntryIndex, currentTerm, - new MockRaftActorContext.MockPayload("D")); + leader.handleMessage(leaderActor, new SendHeartBeat()); - // this should invoke a sendinstallsnapshot as followersLastIndex < snapshotIndex - RaftActorBehavior raftBehavior = leader.handleMessage( - senderActor, new Replicate(null, "state-id", entry)); + AppendEntriesMessages.AppendEntries aeproto = (AppendEntriesMessages.AppendEntries)MessageCollectorActor.getFirstMatching( + followerActor, AppendEntries.SERIALIZABLE_CLASS); - assertTrue(raftBehavior instanceof Leader); + assertNotNull("AppendEntries should be sent even if InstallSnapshotReply is not " + + "received", aeproto); - // we might receive some heartbeat messages, so wait till we SendInstallSnapshot - Boolean[] matches = new ReceiveWhile(Boolean.class, duration("2 seconds")) { - @Override - protected Boolean match(Object o) throws Exception { - if (o instanceof SendInstallSnapshot) { - return true; - } - return false; - } - }.get(); + AppendEntries ae = (AppendEntries) SerializationUtils.fromSerializable(aeproto); - boolean sendInstallSnapshotReceived = false; - for (Boolean b: matches) { - sendInstallSnapshotReceived = b | sendInstallSnapshotReceived; - } + assertTrue("AppendEntries should be sent with empty entries", ae.getEntries().isEmpty()); + + //InstallSnapshotReply received + leader.getFollowerToSnapshot().markSendStatus(true); + + leader.handleMessage(senderActor, new SendHeartBeat()); + + InstallSnapshotMessages.InstallSnapshot isproto = (InstallSnapshotMessages.InstallSnapshot) + MessageCollectorActor.getFirstMatching(followerActor, + InstallSnapshot.SERIALIZABLE_CLASS); + + assertNotNull("Installsnapshot should get called for sending the next chunk of snapshot", + isproto); + + InstallSnapshot is = (InstallSnapshot) SerializationUtils.fromSerializable(isproto); + + assertEquals(snapshotIndex, is.getLastIncludedIndex()); + + }}; + } + + @Test + public void testSendAppendEntriesSnapshotScenario() { + new JavaTestKit(getSystem()) {{ + + ActorRef followerActor = getTestActor(); + + Map peerAddresses = new HashMap<>(); + peerAddresses.put(followerActor.path().toString(), + followerActor.path().toString()); + + MockRaftActorContext actorContext = + (MockRaftActorContext) createActorContext(getRef()); + actorContext.setPeerAddresses(peerAddresses); + + Map leadersSnapshot = new HashMap<>(); + leadersSnapshot.put("1", "A"); + leadersSnapshot.put("2", "B"); + leadersSnapshot.put("3", "C"); + + //clears leaders log + actorContext.getReplicatedLog().removeFrom(0); + + final int followersLastIndex = 2; + final int snapshotIndex = 3; + final int newEntryIndex = 4; + final int snapshotTerm = 1; + final int currentTerm = 2; + + // set the snapshot variables in replicatedlog + actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex); + actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm); + actorContext.setCommitIndex(followersLastIndex); + + Leader leader = new Leader(actorContext); + + // new entry + ReplicatedLogImplEntry entry = + new ReplicatedLogImplEntry(newEntryIndex, currentTerm, + new MockRaftActorContext.MockPayload("D")); - assertTrue(sendInstallSnapshotReceived); + //update follower timestamp + leader.markFollowerActive(followerActor.path().toString()); + // this should invoke a sendinstallsnapshot as followersLastIndex < snapshotIndex + RaftActorBehavior raftBehavior = leader.handleMessage( + senderActor, new Replicate(null, "state-id", entry)); + + assertTrue(raftBehavior instanceof Leader); + + // we might receive some heartbeat messages, so wait till we InitiateInstallSnapshot + Boolean[] matches = new ReceiveWhile(Boolean.class, duration("2 seconds")) { + @Override + protected Boolean match(Object o) throws Exception { + if (o instanceof InitiateInstallSnapshot) { + return true; + } + return false; } - }; + }.get(); + + boolean initiateInitiateInstallSnapshot = false; + for (Boolean b: matches) { + initiateInitiateInstallSnapshot = b | initiateInitiateInstallSnapshot; + } + + assertTrue(initiateInitiateInstallSnapshot); }}; } @Test - public void testInstallSnapshot() { - new LeaderTestKit(getSystem()) {{ + public void testInitiateInstallSnapshot() throws Exception { + new JavaTestKit(getSystem()) {{ - new Within(duration("1 seconds")) { - protected void run() { - ActorRef followerActor = getTestActor(); + ActorRef leaderActor = getSystem().actorOf(Props.create(MessageCollectorActor.class)); - Map peerAddresses = new HashMap(); - peerAddresses.put(followerActor.path().toString(), - followerActor.path().toString()); + ActorRef followerActor = getTestActor(); - MockRaftActorContext actorContext = - (MockRaftActorContext) createActorContext(); - actorContext.setPeerAddresses(peerAddresses); + Map peerAddresses = new HashMap<>(); + peerAddresses.put(followerActor.path().toString(), + followerActor.path().toString()); - Map leadersSnapshot = new HashMap<>(); - leadersSnapshot.put("1", "A"); - leadersSnapshot.put("2", "B"); - leadersSnapshot.put("3", "C"); + MockRaftActorContext actorContext = + (MockRaftActorContext) createActorContext(leaderActor); + actorContext.setPeerAddresses(peerAddresses); - //clears leaders log - actorContext.getReplicatedLog().removeFrom(0); + Map leadersSnapshot = new HashMap<>(); + leadersSnapshot.put("1", "A"); + leadersSnapshot.put("2", "B"); + leadersSnapshot.put("3", "C"); - final int followersLastIndex = 2; - final int snapshotIndex = 3; - final int newEntryIndex = 4; - final int snapshotTerm = 1; - final int currentTerm = 2; + //clears leaders log + actorContext.getReplicatedLog().removeFrom(0); - // set the snapshot variables in replicatedlog - actorContext.getReplicatedLog().setSnapshot(toByteString(leadersSnapshot)); - actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex); - actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm); + final int followersLastIndex = 2; + final int snapshotIndex = 3; + final int newEntryIndex = 4; + final int snapshotTerm = 1; + final int currentTerm = 2; - actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString()); + // set the snapshot variables in replicatedlog + actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex); + actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm); + actorContext.setLastApplied(3); + actorContext.setCommitIndex(followersLastIndex); - MockLeader leader = new MockLeader(actorContext); - // set the follower info in leader - leader.addToFollowerToLog(followerActor.path().toString(), followersLastIndex, -1); + Leader leader = new Leader(actorContext); + // set the snapshot as absent and check if capture-snapshot is invoked. + leader.setSnapshot(Optional.absent()); - // new entry - ReplicatedLogImplEntry entry = - new ReplicatedLogImplEntry(newEntryIndex, currentTerm, - new MockRaftActorContext.MockPayload("D")); + // new entry + ReplicatedLogImplEntry entry = + new ReplicatedLogImplEntry(newEntryIndex, currentTerm, + new MockRaftActorContext.MockPayload("D")); - RaftActorBehavior raftBehavior = leader.handleMessage(senderActor, new SendInstallSnapshot()); + actorContext.getReplicatedLog().append(entry); - assertTrue(raftBehavior instanceof Leader); + // this should invoke a sendinstallsnapshot as followersLastIndex < snapshotIndex + RaftActorBehavior raftBehavior = leader.handleMessage( + leaderActor, new InitiateInstallSnapshot()); - // check if installsnapshot gets called with the correct values. - final String out = - new ExpectMsg(duration("1 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - protected String match(Object in) { - if (in instanceof InstallSnapshotMessages.InstallSnapshot) { - InstallSnapshot is = (InstallSnapshot) - SerializationUtils.fromSerializable(in); - if (is.getData() == null) { - return "InstallSnapshot data is null"; - } - if (is.getLastIncludedIndex() != snapshotIndex) { - return is.getLastIncludedIndex() + "!=" + snapshotIndex; - } - if (is.getLastIncludedTerm() != snapshotTerm) { - return is.getLastIncludedTerm() + "!=" + snapshotTerm; - } - if (is.getTerm() == currentTerm) { - return is.getTerm() + "!=" + currentTerm; - } + CaptureSnapshot cs = (CaptureSnapshot) MessageCollectorActor. + getFirstMatching(leaderActor, CaptureSnapshot.class); - return "match"; + assertNotNull(cs); - } else { - return "message mismatch:" + in.getClass(); - } + assertTrue(cs.isInstallSnapshotInitiated()); + assertEquals(3, cs.getLastAppliedIndex()); + assertEquals(1, cs.getLastAppliedTerm()); + assertEquals(4, cs.getLastIndex()); + assertEquals(2, cs.getLastTerm()); + }}; + } + + @Test + public void testInstallSnapshot() { + new JavaTestKit(getSystem()) {{ + + ActorRef followerActor = getTestActor(); + + Map peerAddresses = new HashMap<>(); + peerAddresses.put(followerActor.path().toString(), + followerActor.path().toString()); + + MockRaftActorContext actorContext = + (MockRaftActorContext) createActorContext(); + actorContext.setPeerAddresses(peerAddresses); + + + Map leadersSnapshot = new HashMap<>(); + leadersSnapshot.put("1", "A"); + leadersSnapshot.put("2", "B"); + leadersSnapshot.put("3", "C"); + + //clears leaders log + actorContext.getReplicatedLog().removeFrom(0); + + final int followersLastIndex = 2; + final int snapshotIndex = 3; + final int newEntryIndex = 4; + final int snapshotTerm = 1; + final int currentTerm = 2; + + // set the snapshot variables in replicatedlog + actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex); + actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm); + actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString()); + actorContext.setCommitIndex(followersLastIndex); + + Leader leader = new Leader(actorContext); + + // new entry + ReplicatedLogImplEntry entry = + new ReplicatedLogImplEntry(newEntryIndex, currentTerm, + new MockRaftActorContext.MockPayload("D")); + + RaftActorBehavior raftBehavior = leader.handleMessage(senderActor, + new SendInstallSnapshot(toByteString(leadersSnapshot))); + + assertTrue(raftBehavior instanceof Leader); + + // check if installsnapshot gets called with the correct values. + final String out = + new ExpectMsg(duration("1 seconds"), "match hint") { + // do not put code outside this method, will run afterwards + protected String match(Object in) { + if (in instanceof InstallSnapshotMessages.InstallSnapshot) { + InstallSnapshot is = (InstallSnapshot) + SerializationUtils.fromSerializable(in); + if (is.getData() == null) { + return "InstallSnapshot data is null"; + } + if (is.getLastIncludedIndex() != snapshotIndex) { + return is.getLastIncludedIndex() + "!=" + snapshotIndex; + } + if (is.getLastIncludedTerm() != snapshotTerm) { + return is.getLastIncludedTerm() + "!=" + snapshotTerm; + } + if (is.getTerm() == currentTerm) { + return is.getTerm() + "!=" + currentTerm; } - }.get(); // this extracts the received message - assertEquals("match", out); - } - }; + return "match"; + + } else { + return "message mismatch:" + in.getClass(); + } + } + }.get(); // this extracts the received message + + assertEquals("match", out); }}; } @Test public void testHandleInstallSnapshotReplyLastChunk() { - new LeaderTestKit(getSystem()) {{ - new Within(duration("1 seconds")) { - protected void run() { - ActorRef followerActor = getTestActor(); + new JavaTestKit(getSystem()) {{ - Map peerAddresses = new HashMap(); - peerAddresses.put(followerActor.path().toString(), - followerActor.path().toString()); + ActorRef followerActor = getTestActor(); - MockRaftActorContext actorContext = - (MockRaftActorContext) createActorContext(); - actorContext.setPeerAddresses(peerAddresses); + Map peerAddresses = new HashMap<>(); + peerAddresses.put(followerActor.path().toString(), + followerActor.path().toString()); - final int followersLastIndex = 2; - final int snapshotIndex = 3; - final int newEntryIndex = 4; - final int snapshotTerm = 1; - final int currentTerm = 2; - - MockLeader leader = new MockLeader(actorContext); - // set the follower info in leader - leader.addToFollowerToLog(followerActor.path().toString(), followersLastIndex, -1); - - Map leadersSnapshot = new HashMap<>(); - leadersSnapshot.put("1", "A"); - leadersSnapshot.put("2", "B"); - leadersSnapshot.put("3", "C"); - - // set the snapshot variables in replicatedlog - actorContext.getReplicatedLog().setSnapshot( - toByteString(leadersSnapshot)); - actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex); - actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm); - actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString()); - - ByteString bs = toByteString(leadersSnapshot); - leader.createFollowerToSnapshot(followerActor.path().toString(), bs); - while(!leader.getFollowerToSnapshot().isLastChunk(leader.getFollowerToSnapshot().getChunkIndex())) { - leader.getFollowerToSnapshot().getNextChunk(); - leader.getFollowerToSnapshot().incrementChunkIndex(); - } + final int followersLastIndex = 2; + final int snapshotIndex = 3; + final int newEntryIndex = 4; + final int snapshotTerm = 1; + final int currentTerm = 2; - //clears leaders log - actorContext.getReplicatedLog().removeFrom(0); + MockRaftActorContext actorContext = + (MockRaftActorContext) createActorContext(); + actorContext.setPeerAddresses(peerAddresses); + actorContext.setCommitIndex(followersLastIndex); - RaftActorBehavior raftBehavior = leader.handleMessage(senderActor, - new InstallSnapshotReply(currentTerm, followerActor.path().toString(), - leader.getFollowerToSnapshot().getChunkIndex(), true)); + MockLeader leader = new MockLeader(actorContext); - assertTrue(raftBehavior instanceof Leader); + Map leadersSnapshot = new HashMap<>(); + leadersSnapshot.put("1", "A"); + leadersSnapshot.put("2", "B"); + leadersSnapshot.put("3", "C"); - assertEquals(leader.mapFollowerToSnapshot.size(), 0); - assertEquals(leader.followerToLog.size(), 1); - assertNotNull(leader.followerToLog.get(followerActor.path().toString())); - FollowerLogInformation fli = leader.followerToLog.get(followerActor.path().toString()); - assertEquals(snapshotIndex, fli.getMatchIndex().get()); - assertEquals(snapshotIndex, fli.getMatchIndex().get()); - assertEquals(snapshotIndex + 1, fli.getNextIndex().get()); - } - }; + // set the snapshot variables in replicatedlog + + actorContext.getReplicatedLog().setSnapshotIndex(snapshotIndex); + actorContext.getReplicatedLog().setSnapshotTerm(snapshotTerm); + actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString()); + + ByteString bs = toByteString(leadersSnapshot); + leader.setSnapshot(Optional.of(bs)); + leader.createFollowerToSnapshot(followerActor.path().toString(), bs); + while(!leader.getFollowerToSnapshot().isLastChunk(leader.getFollowerToSnapshot().getChunkIndex())) { + leader.getFollowerToSnapshot().getNextChunk(); + leader.getFollowerToSnapshot().incrementChunkIndex(); + } + + //clears leaders log + actorContext.getReplicatedLog().removeFrom(0); + + RaftActorBehavior raftBehavior = leader.handleMessage(senderActor, + new InstallSnapshotReply(currentTerm, followerActor.path().toString(), + leader.getFollowerToSnapshot().getChunkIndex(), true)); + + assertTrue(raftBehavior instanceof Leader); + + assertEquals(leader.mapFollowerToSnapshot.size(), 0); + assertEquals(leader.followerToLog.size(), 1); + assertNotNull(leader.followerToLog.get(followerActor.path().toString())); + FollowerLogInformation fli = leader.followerToLog.get(followerActor.path().toString()); + assertEquals(snapshotIndex, fli.getMatchIndex().get()); + assertEquals(snapshotIndex, fli.getMatchIndex().get()); + assertEquals(snapshotIndex + 1, fli.getNextIndex().get()); }}; } @@ -557,7 +692,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { ForwardMessageToBehaviorActor.setBehavior(follower); - Map peerAddresses = new HashMap(); + Map peerAddresses = new HashMap<>(); peerAddresses.put(followerActor.path().toString(), followerActor.path().toString()); @@ -580,6 +715,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { followerActorContext.setCommitIndex(1); Leader leader = new Leader(leaderActorContext); + leader.markFollowerActive(followerActor.path().toString()); leader.handleMessage(leaderActor, new SendHeartBeat()); @@ -626,7 +762,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { ForwardMessageToBehaviorActor.setBehavior(follower); - Map peerAddresses = new HashMap(); + Map peerAddresses = new HashMap<>(); peerAddresses.put(followerActor.path().toString(), followerActor.path().toString()); @@ -648,6 +784,7 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { followerActorContext.setCommitIndex(2); Leader leader = new Leader(leaderActorContext); + leader.markFollowerActive(followerActor.path().toString()); leader.handleMessage(leaderActor, new SendHeartBeat()); @@ -673,28 +810,215 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { }}; } - private static class LeaderTestKit extends JavaTestKit { + @Test + public void testHandleAppendEntriesReplyFailure(){ + new JavaTestKit(getSystem()) { + { + + ActorRef leaderActor = + getSystem().actorOf(Props.create(MessageCollectorActor.class)); - private LeaderTestKit(ActorSystem actorSystem) { - super(actorSystem); - } + ActorRef followerActor = + getSystem().actorOf(Props.create(MessageCollectorActor.class)); - protected void waitForLogMessage(final Class logLevel, ActorRef subject, String logMessage){ - // Wait for a specific log message to show up - final boolean result = - new JavaTestKit.EventFilter(logLevel - ) { - @Override - protected Boolean run() { - return true; - } - }.from(subject.path().toString()) - .message(logMessage) - .occurrences(1).exec(); - Assert.assertEquals(true, result); + MockRaftActorContext leaderActorContext = + new MockRaftActorContext("leader", getSystem(), leaderActor); - } + Map peerAddresses = new HashMap<>(); + peerAddresses.put("follower-1", + followerActor.path().toString()); + + leaderActorContext.setPeerAddresses(peerAddresses); + + Leader leader = new Leader(leaderActorContext); + + AppendEntriesReply reply = new AppendEntriesReply("follower-1", 1, false, 10, 1); + + RaftActorBehavior raftActorBehavior = leader.handleAppendEntriesReply(followerActor, reply); + + assertEquals(RaftState.Leader, raftActorBehavior.state()); + + }}; + } + + @Test + public void testHandleAppendEntriesReplySuccess() throws Exception { + new JavaTestKit(getSystem()) { + { + + ActorRef leaderActor = + getSystem().actorOf(Props.create(MessageCollectorActor.class)); + + ActorRef followerActor = + getSystem().actorOf(Props.create(MessageCollectorActor.class)); + + + MockRaftActorContext leaderActorContext = + new MockRaftActorContext("leader", getSystem(), leaderActor); + + leaderActorContext.setReplicatedLog( + new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(0, 3, 1).build()); + + Map peerAddresses = new HashMap<>(); + peerAddresses.put("follower-1", + followerActor.path().toString()); + + leaderActorContext.setPeerAddresses(peerAddresses); + leaderActorContext.setCommitIndex(1); + leaderActorContext.setLastApplied(1); + leaderActorContext.getTermInformation().update(1, "leader"); + + Leader leader = new Leader(leaderActorContext); + + AppendEntriesReply reply = new AppendEntriesReply("follower-1", 1, true, 2, 1); + + RaftActorBehavior raftActorBehavior = leader.handleAppendEntriesReply(followerActor, reply); + + assertEquals(RaftState.Leader, raftActorBehavior.state()); + + assertEquals(2, leaderActorContext.getCommitIndex()); + + ApplyLogEntries applyLogEntries = + (ApplyLogEntries) MessageCollectorActor.getFirstMatching(leaderActor, + ApplyLogEntries.class); + + assertNotNull(applyLogEntries); + + assertEquals(2, leaderActorContext.getLastApplied()); + + assertEquals(2, applyLogEntries.getToIndex()); + + List applyStateList = MessageCollectorActor.getAllMatching(leaderActor, + ApplyState.class); + + assertEquals(1,applyStateList.size()); + + ApplyState applyState = (ApplyState) applyStateList.get(0); + + assertEquals(2, applyState.getReplicatedLogEntry().getIndex()); + + }}; + } + + @Test + public void testHandleAppendEntriesReplyUnknownFollower(){ + new JavaTestKit(getSystem()) { + { + + ActorRef leaderActor = + getSystem().actorOf(Props.create(MessageCollectorActor.class)); + + MockRaftActorContext leaderActorContext = + new MockRaftActorContext("leader", getSystem(), leaderActor); + + Leader leader = new Leader(leaderActorContext); + + AppendEntriesReply reply = new AppendEntriesReply("follower-1", 1, false, 10, 1); + + RaftActorBehavior raftActorBehavior = leader.handleAppendEntriesReply(getRef(), reply); + + assertEquals(RaftState.Leader, raftActorBehavior.state()); + + }}; + } + + @Test + public void testHandleRequestVoteReply(){ + new JavaTestKit(getSystem()) { + { + + ActorRef leaderActor = + getSystem().actorOf(Props.create(MessageCollectorActor.class)); + + MockRaftActorContext leaderActorContext = + new MockRaftActorContext("leader", getSystem(), leaderActor); + + Leader leader = new Leader(leaderActorContext); + + RaftActorBehavior raftActorBehavior = leader.handleRequestVoteReply(getRef(), new RequestVoteReply(1, true)); + + assertEquals(RaftState.Leader, raftActorBehavior.state()); + + raftActorBehavior = leader.handleRequestVoteReply(getRef(), new RequestVoteReply(1, false)); + + assertEquals(RaftState.Leader, raftActorBehavior.state()); + }}; + } + + @Test + public void testIsolatedLeaderCheckNoFollowers() { + new JavaTestKit(getSystem()) {{ + ActorRef leaderActor = getTestActor(); + + MockRaftActorContext leaderActorContext = + new MockRaftActorContext("leader", getSystem(), leaderActor); + + Map peerAddresses = new HashMap<>(); + leaderActorContext.setPeerAddresses(peerAddresses); + + Leader leader = new Leader(leaderActorContext); + RaftActorBehavior behavior = leader.handleMessage(leaderActor, new IsolatedLeaderCheck()); + Assert.assertTrue(behavior instanceof Leader); + }}; + } + + @Test + public void testIsolatedLeaderCheckTwoFollowers() throws Exception { + new JavaTestKit(getSystem()) {{ + + ActorRef followerActor1 = getTestActor(); + ActorRef followerActor2 = getTestActor(); + + MockRaftActorContext leaderActorContext = (MockRaftActorContext) createActorContext(); + + Map peerAddresses = new HashMap<>(); + peerAddresses.put("follower-1", followerActor1.path().toString()); + peerAddresses.put("follower-2", followerActor2.path().toString()); + + leaderActorContext.setPeerAddresses(peerAddresses); + + Leader leader = new Leader(leaderActorContext); + leader.stopIsolatedLeaderCheckSchedule(); + + leader.markFollowerActive("follower-1"); + leader.markFollowerActive("follower-2"); + RaftActorBehavior behavior = leader.handleMessage(leaderActor, new IsolatedLeaderCheck()); + Assert.assertTrue("Behavior not instance of Leader when all followers are active", + behavior instanceof Leader); + + // kill 1 follower and verify if that got killed + final JavaTestKit probe = new JavaTestKit(getSystem()); + probe.watch(followerActor1); + followerActor1.tell(PoisonPill.getInstance(), ActorRef.noSender()); + final Terminated termMsg1 = probe.expectMsgClass(Terminated.class); + assertEquals(termMsg1.getActor(), followerActor1); + + //sleep enough for all the follower stopwatches to lapse + Uninterruptibles.sleepUninterruptibly(leaderActorContext.getConfigParams(). + getElectionTimeOutInterval().toMillis(), TimeUnit.MILLISECONDS); + + leader.markFollowerActive("follower-2"); + behavior = leader.handleMessage(leaderActor, new IsolatedLeaderCheck()); + Assert.assertTrue("Behavior not instance of Leader when majority of followers are active", + behavior instanceof Leader); + + // kill 2nd follower and leader should change to Isolated leader + followerActor2.tell(PoisonPill.getInstance(), null); + probe.watch(followerActor2); + followerActor2.tell(PoisonPill.getInstance(), ActorRef.noSender()); + final Terminated termMsg2 = probe.expectMsgClass(Terminated.class); + assertEquals(termMsg2.getActor(), followerActor2); + + //sleep enough for the remaining the follower stopwatches to lapse + Uninterruptibles.sleepUninterruptibly(leaderActorContext.getConfigParams(). + getElectionTimeOutInterval().toMillis(), TimeUnit.MILLISECONDS); + + behavior = leader.handleMessage(leaderActor, new IsolatedLeaderCheck()); + Assert.assertTrue("Behavior not instance of IsolatedLeader when majority followers are inactive", + behavior instanceof IsolatedLeader); + + }}; } class MockLeader extends Leader { @@ -705,14 +1029,6 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { super(context); } - public void addToFollowerToLog(String followerId, long nextIndex, long matchIndex) { - FollowerLogInformation followerLogInformation = - new FollowerLogInformationImpl(followerId, - new AtomicLong(nextIndex), - new AtomicLong(matchIndex)); - followerToLog.put(followerId, followerLogInformation); - } - public FollowerToSnapshot getFollowerToSnapshot() { return fts; } @@ -723,4 +1039,26 @@ public class LeaderTest extends AbstractRaftActorBehaviorTest { } } + + private class MockConfigParamsImpl extends DefaultConfigParamsImpl { + + private long electionTimeOutIntervalMillis; + private int snapshotChunkSize; + + public MockConfigParamsImpl(long electionTimeOutIntervalMillis, int snapshotChunkSize) { + super(); + this.electionTimeOutIntervalMillis = electionTimeOutIntervalMillis; + this.snapshotChunkSize = snapshotChunkSize; + } + + @Override + public FiniteDuration getElectionTimeOutInterval() { + return new FiniteDuration(electionTimeOutIntervalMillis, TimeUnit.MILLISECONDS); + } + + @Override + public int getSnapshotChunkSize() { + return snapshotChunkSize; + } + } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java index 58928453b4..2a79c8f4bc 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java @@ -12,6 +12,7 @@ import akka.actor.ActorRef; import akka.actor.UntypedActor; import akka.pattern.Patterns; import akka.util.Timeout; +import com.google.common.collect.Lists; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; @@ -53,7 +54,7 @@ public class MessageCollectorActor extends UntypedActor { * @param clazz * @return */ - public static Object getFirstMatching(ActorRef actor, Class clazz) throws Exception { + public static Object getFirstMatching(ActorRef actor, Class clazz) throws Exception { List allMessages = getAllMessages(actor); for(Object message : allMessages){ @@ -65,4 +66,18 @@ public class MessageCollectorActor extends UntypedActor { return null; } + public static List getAllMatching(ActorRef actor, Class clazz) throws Exception { + List allMessages = getAllMessages(actor); + + List output = Lists.newArrayList(); + + for(Object message : allMessages){ + if(message.getClass().equals(clazz)){ + output.add(message); + } + } + + return output; + } + } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/resources/application.conf b/opendaylight/md-sal/sal-akka-raft/src/test/resources/application.conf index 2f53d4a4eb..818ddf7d85 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/resources/application.conf +++ b/opendaylight/md-sal/sal-akka-raft/src/test/resources/application.conf @@ -7,7 +7,7 @@ akka { actor { # enable to test serialization only. - serialize-messages = on + serialize-messages = off serializers { java = "akka.serialization.JavaSerializer" @@ -15,6 +15,7 @@ akka { } serialization-bindings { + "org.opendaylight.controller.cluster.common.actor.Monitor" = java "org.opendaylight.controller.cluster.raft.client.messages.FindLeader" = java "org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry" = java "com.google.protobuf.Message" = proto diff --git a/opendaylight/md-sal/sal-binding-broker/pom.xml b/opendaylight/md-sal/sal-binding-broker/pom.xml index 7482c52fdd..ade3e1b8f6 100644 --- a/opendaylight/md-sal/sal-binding-broker/pom.xml +++ b/opendaylight/md-sal/sal-binding-broker/pom.xml @@ -70,7 +70,6 @@ org.opendaylight.yangtools binding-data-codec - 0.7.0-SNAPSHOT org.opendaylight.yangtools diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/RuntimeMappingModule.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/RuntimeMappingModule.java index 754d14f2c4..0ad0434892 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/RuntimeMappingModule.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/RuntimeMappingModule.java @@ -7,42 +7,25 @@ */ package org.opendaylight.controller.config.yang.md.sal.binding.impl; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.util.Hashtable; -import java.util.Map.Entry; -import java.util.Set; import javassist.ClassPool; import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec; import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder; import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator; import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.yangtools.concepts.Delegator; import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy; import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.RpcService; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.CompositeNode; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService; -import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry; -import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException; import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * */ public final class RuntimeMappingModule extends AbstractRuntimeMappingModule { - private static final Logger LOG = LoggerFactory.getLogger(RuntimeMappingModule.class); - private BundleContext bundleContext; public RuntimeMappingModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, @@ -72,7 +55,7 @@ public final class RuntimeMappingModule extends AbstractRuntimeMappingModule { public java.lang.AutoCloseable createInstance() { final GeneratedClassLoadingStrategy classLoading = getGlobalClassLoadingStrategy(); final BindingIndependentMappingService legacyMapping = getGlobalLegacyMappingService(classLoading); - BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(new StreamWriterGenerator(SingletonHolder.JAVASSIST)); + BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(SingletonHolder.JAVASSIST)); BindingToNormalizedNodeCodec instance = new BindingToNormalizedNodeCodec(classLoading, legacyMapping, codecRegistry); bundleContext.registerService(SchemaContextListener.class, instance, new Hashtable()); return instance; @@ -108,93 +91,4 @@ public final class RuntimeMappingModule extends AbstractRuntimeMappingModule { public void setBundleContext(final BundleContext bundleContext) { this.bundleContext = bundleContext; } - - private static final class RuntimeGeneratedMappingServiceProxy implements // - BindingIndependentMappingService, // - Delegator, // - AutoCloseable { - - private BindingIndependentMappingService delegate; - private ServiceReference reference; - private BundleContext bundleContext; - - public RuntimeGeneratedMappingServiceProxy(final BundleContext bundleContext, - final ServiceReference serviceRef, - final BindingIndependentMappingService delegate) { - this.bundleContext = Preconditions.checkNotNull(bundleContext); - this.reference = Preconditions.checkNotNull(serviceRef); - this.delegate = Preconditions.checkNotNull(delegate); - } - - @Override - public CodecRegistry getCodecRegistry() { - return delegate.getCodecRegistry(); - } - - @Override - public CompositeNode toDataDom(final DataObject data) { - return delegate.toDataDom(data); - } - - @Override - public Entry toDataDom( - final Entry, DataObject> entry) { - return delegate.toDataDom(entry); - } - - @Override - public YangInstanceIdentifier toDataDom(final InstanceIdentifier path) { - return delegate.toDataDom(path); - } - - @Override - public DataObject dataObjectFromDataDom( - final InstanceIdentifier path, - final CompositeNode result) throws DeserializationException { - return delegate.dataObjectFromDataDom(path, result); - } - - @Override - public InstanceIdentifier fromDataDom(final YangInstanceIdentifier entry) - throws DeserializationException { - return delegate.fromDataDom(entry); - } - - @Override - public Set getRpcQNamesFor(final Class service) { - return delegate.getRpcQNamesFor(service); - } - - @Override - public Optional> getRpcServiceClassFor(final String namespace, final String revision) { - return delegate.getRpcServiceClassFor(namespace,revision); - } - - @Override - public DataContainer dataObjectFromDataDom(final Class inputClass, final CompositeNode domInput) { - return delegate.dataObjectFromDataDom(inputClass, domInput); - } - - @Override - public void close() { - if(delegate != null) { - delegate = null; - - try { - bundleContext.ungetService(reference); - } catch (IllegalStateException e) { - // Indicates the BundleContext is no longer valid which can happen normally on shutdown. - LOG.debug( "Error unregistering service", e ); - } - - bundleContext= null; - reference = null; - } - } - - @Override - public BindingIndependentMappingService getDelegate() { - return delegate; - } - } } diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java index d4b1d84aa7..273155bcf7 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java @@ -124,7 +124,7 @@ public abstract class AbstractForwardedDataBroker implements Delegator> of(data)); + return (Optional) getCodec().deserializeFunction(path).apply(Optional.> of(data)); } private class TranslatingDataChangeInvoker implements DOMDataChangeListener { diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/AbstractRuntimeCodeGenerator.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/AbstractRuntimeCodeGenerator.java index 1fa54be200..eba5b8756b 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/AbstractRuntimeCodeGenerator.java +++ b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/AbstractRuntimeCodeGenerator.java @@ -8,17 +8,11 @@ package org.opendaylight.controller.sal.binding.codegen.impl; import com.google.common.base.Supplier; - -import java.util.Map; -import java.util.WeakHashMap; - +import com.google.common.collect.Iterables; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; - -import javax.annotation.concurrent.GuardedBy; - import org.eclipse.xtext.xbase.lib.Extension; import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter; import org.opendaylight.controller.sal.binding.codegen.RpcIsNotRoutedException; @@ -31,6 +25,10 @@ import org.opendaylight.yangtools.yang.binding.RpcService; import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext; import org.opendaylight.yangtools.yang.binding.util.ClassLoaderUtils; +import javax.annotation.concurrent.GuardedBy; +import java.util.Map; +import java.util.WeakHashMap; + abstract class AbstractRuntimeCodeGenerator implements org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator, NotificationInvokerFactory { @GuardedBy("this") private final Map, RuntimeGeneratedInvokerPrototype> invokerClasses = new WeakHashMap<>(); @@ -174,6 +172,10 @@ abstract class AbstractRuntimeCodeGenerator implements org.opendaylight.controll } }); + if (Iterables.isEmpty(metadata.getContexts())) { + throw new RpcIsNotRoutedException("Service doesn't have routing context associated."); + } + synchronized (utils) { final T instance = ClassLoaderUtils.withClassLoader(serviceType.getClassLoader(), routerSupplier(serviceType, metadata)); return new RpcRouterCodegenInstance(name, serviceType, instance, metadata.getContexts()); diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/AugmentationVerifier.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/AugmentationVerifier.java index 227354c41e..c8129e6eca 100644 --- a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/AugmentationVerifier.java +++ b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/AugmentationVerifier.java @@ -7,9 +7,7 @@ */ package org.opendaylight.controller.sal.binding.test; -import junit.framework.Assert; - - +import static org.junit.Assert.assertNotNull; import org.opendaylight.yangtools.yang.binding.Augmentable; import org.opendaylight.yangtools.yang.binding.Augmentation; @@ -28,8 +26,8 @@ public class AugmentationVerifier> { public static > void assertHasAugmentation(T object, Class> augmentation) { - Assert.assertNotNull(object); - Assert.assertNotNull("Augmentation " + augmentation.getSimpleName() + " is not present.", object.getAugmentation(augmentation)); + assertNotNull(object); + assertNotNull("Augmentation " + augmentation.getSimpleName() + " is not present.", object.getAugmentation(augmentation)); } public static > AugmentationVerifier from(T obj) { diff --git a/opendaylight/md-sal/sal-binding-dom-it/pom.xml b/opendaylight/md-sal/sal-binding-dom-it/pom.xml index fefd85b44b..01cd1f88ba 100644 --- a/opendaylight/md-sal/sal-binding-dom-it/pom.xml +++ b/opendaylight/md-sal/sal-binding-dom-it/pom.xml @@ -52,7 +52,6 @@ org.opendaylight.controller sal-test-model - 1.2.0-SNAPSHOT diff --git a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/CrossBrokerRpcTest.java b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/CrossBrokerRpcTest.java index 4cc3780c6f..ba75d578fb 100644 --- a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/CrossBrokerRpcTest.java +++ b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/CrossBrokerRpcTest.java @@ -7,10 +7,10 @@ */ package org.opendaylight.controller.sal.binding.test.connect.dom; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.assertNotSame; -import static junit.framework.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; import java.math.BigInteger; import java.util.Collections; diff --git a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/DOMRpcServiceTestBugfix560.java b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/DOMRpcServiceTestBugfix560.java index 6686a83a2e..7d616ca62c 100644 --- a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/DOMRpcServiceTestBugfix560.java +++ b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/DOMRpcServiceTestBugfix560.java @@ -7,9 +7,9 @@ */ package org.opendaylight.controller.sal.binding.test.connect.dom; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.assertTrue; -import static junit.framework.Assert.fail; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.InputStream; import java.util.Collections; diff --git a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/MessageCapturingFlowService.java b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/MessageCapturingFlowService.java index df287791ef..47e79650fe 100644 --- a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/MessageCapturingFlowService.java +++ b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/MessageCapturingFlowService.java @@ -7,7 +7,7 @@ */ package org.opendaylight.controller.sal.binding.test.connect.dom; -import static junit.framework.Assert.assertNotNull; +import static org.junit.Assert.assertNotNull; import java.util.concurrent.Future; diff --git a/opendaylight/md-sal/sal-binding-it/src/main/java/org/opendaylight/controller/test/sal/binding/it/TestHelper.java b/opendaylight/md-sal/sal-binding-it/src/main/java/org/opendaylight/controller/test/sal/binding/it/TestHelper.java index efd35ccfa6..f7313f4ce7 100644 --- a/opendaylight/md-sal/sal-binding-it/src/main/java/org/opendaylight/controller/test/sal/binding/it/TestHelper.java +++ b/opendaylight/md-sal/sal-binding-it/src/main/java/org/opendaylight/controller/test/sal/binding/it/TestHelper.java @@ -76,7 +76,6 @@ public class TestHelper { mavenBundle("org.apache.sshd", "sshd-core").versionAsInProject(), // mavenBundle("org.openexi", "nagasena").versionAsInProject(), // mavenBundle("org.openexi", "nagasena-rta").versionAsInProject(), // - mavenBundle(CONTROLLER + ".thirdparty", "ganymed").versionAsInProject(), // mavenBundle(CONTROLLER, "netconf-mapping-api").versionAsInProject(), // mavenBundle(CONTROLLER, "config-persister-impl").versionAsInProject(), // diff --git a/opendaylight/md-sal/sal-clustering-commons/pom.xml b/opendaylight/md-sal/sal-clustering-commons/pom.xml index 54a1fe7a95..f6d7dbab1a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/pom.xml +++ b/opendaylight/md-sal/sal-clustering-commons/pom.xml @@ -55,7 +55,6 @@ com.google.code.findbugs jsr305 - 2.0.1 com.google.guava @@ -111,7 +110,6 @@ xmlunit xmlunit - 1.5 junit @@ -131,7 +129,6 @@ org.slf4j slf4j-simple - ${slf4j.version} test @@ -185,7 +182,6 @@ xmlunit xmlunit - 1.5 @@ -199,13 +195,11 @@ org.slf4j slf4j-simple - ${slf4j.version} test com.google.code.findbugs jsr305 - 2.0.1 com.codahale.metrics diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DataPersistenceProvider.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DataPersistenceProvider.java new file mode 100644 index 0000000000..db4bf31438 --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DataPersistenceProvider.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster; + +import akka.japi.Procedure; +import akka.persistence.SnapshotSelectionCriteria; + +/** + * DataPersistenceProvider provides methods to persist data and is an abstraction of the akka-persistence persistence + * API. + */ +public interface DataPersistenceProvider { + /** + * @return false if recovery is not applicable. In that case the provider is not persistent and may not have + * anything to be recovered + */ + boolean isRecoveryApplicable(); + + /** + * Persist a journal entry. + * + * @param o + * @param procedure + * @param + */ + void persist(T o, Procedure procedure); + + /** + * Save a snapshot + * + * @param o + */ + void saveSnapshot(Object o); + + /** + * Delete snapshots based on the criteria + * + * @param criteria + */ + void deleteSnapshots(SnapshotSelectionCriteria criteria); + + /** + * Delete journal entries up to the sequence number + * + * @param sequenceNumber + */ + void deleteMessages(long sequenceNumber); + +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActorWithMetering.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActorWithMetering.java index 5497f93c43..04d9a43c2d 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActorWithMetering.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActorWithMetering.java @@ -12,13 +12,26 @@ package org.opendaylight.controller.cluster.common.actor; */ public abstract class AbstractUntypedActorWithMetering extends AbstractUntypedActor { + //this is used in the metric name. Some transient actors do not have defined names + private String actorNameOverride; + public AbstractUntypedActorWithMetering() { if (isMetricsCaptureEnabled()) getContext().become(new MeteringBehavior(this)); } + public AbstractUntypedActorWithMetering(String actorNameOverride){ + this.actorNameOverride = actorNameOverride; + if (isMetricsCaptureEnabled()) + getContext().become(new MeteringBehavior(this)); + } + private boolean isMetricsCaptureEnabled(){ CommonConfig config = new CommonConfig(getContext().system().settings().config()); return config.isMetricCaptureEnabled(); } + + public String getActorNameOverride() { + return actorNameOverride; + } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActor.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActor.java index 36b2866210..8a6217deab 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActor.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActor.java @@ -10,7 +10,10 @@ package org.opendaylight.controller.cluster.common.actor; import akka.event.Logging; import akka.event.LoggingAdapter; +import akka.japi.Procedure; +import akka.persistence.SnapshotSelectionCriteria; import akka.persistence.UntypedPersistentActor; +import org.opendaylight.controller.cluster.DataPersistenceProvider; public abstract class AbstractUntypedPersistentActor extends UntypedPersistentActor { @@ -67,4 +70,71 @@ public abstract class AbstractUntypedPersistentActor extends UntypedPersistentAc } unhandled(message); } + + protected class PersistentDataProvider implements DataPersistenceProvider { + + public PersistentDataProvider(){ + + } + + @Override + public boolean isRecoveryApplicable() { + return true; + } + + @Override + public void persist(T o, Procedure procedure) { + AbstractUntypedPersistentActor.this.persist(o, procedure); + } + + @Override + public void saveSnapshot(Object o) { + AbstractUntypedPersistentActor.this.saveSnapshot(o); + } + + @Override + public void deleteSnapshots(SnapshotSelectionCriteria criteria) { + AbstractUntypedPersistentActor.this.deleteSnapshots(criteria); + } + + @Override + public void deleteMessages(long sequenceNumber) { + AbstractUntypedPersistentActor.this.deleteMessages(sequenceNumber); + } + } + + protected class NonPersistentDataProvider implements DataPersistenceProvider { + + public NonPersistentDataProvider(){ + + } + + @Override + public boolean isRecoveryApplicable() { + return false; + } + + @Override + public void persist(T o, Procedure procedure) { + try { + procedure.apply(o); + } catch (Exception e) { + LOG.error(e, "An unexpected error occurred"); + } + } + + @Override + public void saveSnapshot(Object o) { + } + + @Override + public void deleteSnapshots(SnapshotSelectionCriteria criteria) { + + } + + @Override + public void deleteMessages(long sequenceNumber) { + + } + } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/CommonConfig.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/CommonConfig.java index 0d139f9670..48afe40607 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/CommonConfig.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/CommonConfig.java @@ -109,7 +109,7 @@ public class CommonConfig extends AbstractConfig { public T mailboxCapacity(int capacity) { Preconditions.checkArgument(capacity > 0, "mailbox capacity must be >0"); - Map boundedMailbox = (Map) configHolder.get(TAG_MAILBOX); + Map boundedMailbox = (Map) configHolder.get(TAG_MAILBOX); boundedMailbox.put(TAG_MAILBOX_CAPACITY, capacity); return (T)this; } @@ -118,7 +118,7 @@ public class CommonConfig extends AbstractConfig { Duration pushTimeout = Duration.create(timeout); Preconditions.checkArgument(pushTimeout.isFinite(), "invalid value for mailbox push timeout"); - Map boundedMailbox = (Map) configHolder.get(TAG_MAILBOX); + Map boundedMailbox = (Map) configHolder.get(TAG_MAILBOX); boundedMailbox.put(TAG_MAILBOX_PUSH_TIMEOUT, timeout); return (T)this; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java index 458f379f84..9b4560c726 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java @@ -55,24 +55,25 @@ public class MeteredBoundedMailbox implements MailboxType, ProducesMessageQueue< return; //there's no actor to monitor } String actorName = owner.get().path().toStringWithoutAddress(); - String metricName = registry.name(actorName, QUEUE_SIZE); + String metricName = MetricRegistry.name(actorName, QUEUE_SIZE); if (registry.getMetrics().containsKey(metricName)) return; //already registered - Gauge queueSize = getQueueSizeGuage(monitoredQueue); + Gauge queueSize = getQueueSizeGuage(monitoredQueue); registerQueueSizeMetric(metricName, queueSize); } public static class MeteredMessageQueue extends BoundedDequeBasedMailbox.MessageQueue { + private static final long serialVersionUID = 1L; public MeteredMessageQueue(int capacity, FiniteDuration pushTimeOut) { super(capacity, pushTimeOut); } } - private Gauge getQueueSizeGuage(final MeteredMessageQueue monitoredQueue ){ + private Gauge getQueueSizeGuage(final MeteredMessageQueue monitoredQueue ){ return new Gauge() { @Override public Integer getValue() { @@ -81,7 +82,7 @@ public class MeteredBoundedMailbox implements MailboxType, ProducesMessageQueue< }; } - private void registerQueueSizeMetric(String metricName, Gauge metric){ + private void registerQueueSizeMetric(String metricName, Gauge metric){ try { registry.register(metricName,metric); } catch (IllegalArgumentException e) { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java index d67d413d09..9ff185a61e 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java @@ -32,19 +32,35 @@ public class MeteringBehavior implements Procedure { private final MetricRegistry METRICREGISTRY = MetricsReporter.getInstance().getMetricsRegistry(); private final String MSG_PROCESSING_RATE = "msg-rate"; - private String actorName; + private String actorQualifiedName; private Timer msgProcessingTimer; /** * * @param actor whose behaviour needs to be metered */ - public MeteringBehavior(UntypedActor actor){ + public MeteringBehavior(AbstractUntypedActorWithMetering actor){ Preconditions.checkArgument(actor != null, "actor must not be null"); + this.meteredActor = actor; + String actorName = actor.getActorNameOverride() != null ? actor.getActorNameOverride() + : actor.getSelf().path().name(); + init(actorName); + } + + public MeteringBehavior(UntypedActor actor){ + Preconditions.checkArgument(actor != null, "actor must not be null"); this.meteredActor = actor; - actorName = meteredActor.getSelf().path().toStringWithoutAddress(); - final String msgProcessingTime = MetricRegistry.name(actorName, MSG_PROCESSING_RATE); + + String actorName = actor.getSelf().path().name(); + init(actorName); + } + + private void init(String actorName){ + actorQualifiedName = new StringBuilder(meteredActor.getSelf().path().parent().toStringWithoutAddress()). + append("/").append(actorName).toString(); + + final String msgProcessingTime = MetricRegistry.name(actorQualifiedName, MSG_PROCESSING_RATE); msgProcessingTimer = METRICREGISTRY.timer(msgProcessingTime); } @@ -69,7 +85,7 @@ public class MeteringBehavior implements Procedure { final String messageType = message.getClass().getSimpleName(); final String msgProcessingTimeByMsgType = - MetricRegistry.name(actorName, MSG_PROCESSING_RATE, messageType); + MetricRegistry.name(actorQualifiedName, MSG_PROCESSING_RATE, messageType); final Timer msgProcessingTimerByMsgType = METRICREGISTRY.timer(msgProcessingTimeByMsgType); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/Monitor.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/Monitor.java index b2a43c03d9..f81b34aad8 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/Monitor.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/Monitor.java @@ -10,7 +10,10 @@ package org.opendaylight.controller.cluster.common.actor; import akka.actor.ActorRef; -public class Monitor { +import java.io.Serializable; + +public class Monitor implements Serializable { + private static final long serialVersionUID = 1L; private final ActorRef actorRef; public Monitor(ActorRef actorRef){ diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/DataPersistenceProviderMonitor.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/DataPersistenceProviderMonitor.java new file mode 100644 index 0000000000..33d4056395 --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/DataPersistenceProviderMonitor.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.datastore; + +import akka.japi.Procedure; +import akka.persistence.SnapshotSelectionCriteria; +import org.opendaylight.controller.cluster.DataPersistenceProvider; + +import java.util.concurrent.CountDownLatch; + +/** + * This class is intended for testing purposes. It just triggers CountDownLatch's in each method. + * This class really should be under src/test/java but it was problematic trying to uses it in other projects. + */ +public class DataPersistenceProviderMonitor implements DataPersistenceProvider { + + private CountDownLatch persistLatch = new CountDownLatch(1); + private CountDownLatch saveSnapshotLatch = new CountDownLatch(1); + private CountDownLatch deleteSnapshotsLatch = new CountDownLatch(1);; + private CountDownLatch deleteMessagesLatch = new CountDownLatch(1);; + + @Override + public boolean isRecoveryApplicable() { + return false; + } + + @Override + public void persist(T o, Procedure procedure) { + persistLatch.countDown(); + } + + @Override + public void saveSnapshot(Object o) { + saveSnapshotLatch.countDown(); + } + + @Override + public void deleteSnapshots(SnapshotSelectionCriteria criteria) { + deleteSnapshotsLatch.countDown(); + } + + @Override + public void deleteMessages(long sequenceNumber) { + deleteMessagesLatch.countDown(); + } + + public void setPersistLatch(CountDownLatch persistLatch) { + this.persistLatch = persistLatch; + } + + public void setSaveSnapshotLatch(CountDownLatch saveSnapshotLatch) { + this.saveSnapshotLatch = saveSnapshotLatch; + } + + public void setDeleteSnapshotsLatch(CountDownLatch deleteSnapshotsLatch) { + this.deleteSnapshotsLatch = deleteSnapshotsLatch; + } + + public void setDeleteMessagesLatch(CountDownLatch deleteMessagesLatch) { + this.deleteMessagesLatch = deleteMessagesLatch; + } +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java index 32f3be82fc..fd53b0f972 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java @@ -16,7 +16,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; public class NormalizedNodeGetter implements NormalizedNodeVisitor { private final String path; - NormalizedNode output; + NormalizedNode output; public NormalizedNodeGetter(String path){ Preconditions.checkNotNull(path); @@ -24,7 +24,7 @@ public class NormalizedNodeGetter implements } @Override - public void visitNode(int level, String parentPath, NormalizedNode normalizedNode) { + public void visitNode(int level, String parentPath, NormalizedNode normalizedNode) { String nodePath = parentPath + "/"+ PathUtils.toString(normalizedNode.getIdentifier()); if(nodePath.toString().equals(path)){ @@ -32,7 +32,7 @@ public class NormalizedNodeGetter implements } } - public NormalizedNode getOutput(){ + public NormalizedNode getOutput(){ return output; } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java index 0083b00403..f8019c9186 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java @@ -67,7 +67,7 @@ public class NormalizedNodeNavigator { String newParentPath = parentPath + "/" + node.getIdentifier().toString(); final Iterable> value = node.getValue(); - for(NormalizedNode normalizedNode : value){ + for(NormalizedNode normalizedNode : value){ if(normalizedNode instanceof MixinNode && normalizedNode instanceof NormalizedNodeContainer){ navigateNormalizedNodeContainerMixin(level + 1, newParentPath, (NormalizedNodeContainer) normalizedNode); } else { @@ -81,7 +81,7 @@ public class NormalizedNodeNavigator { private void navigateNormalizedNode(int level, String parentPath, NormalizedNode normalizedNode){ if(normalizedNode instanceof DataContainerNode){ - final DataContainerNode dataContainerNode = (DataContainerNode) normalizedNode; + final DataContainerNode dataContainerNode = (DataContainerNode) normalizedNode; navigateDataContainerNode(level + 1, parentPath, dataContainerNode); } else { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java index d370eb2deb..5f10800e34 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java @@ -25,7 +25,7 @@ public class NormalizedNodePrinter implements NormalizedNodeVisitor { } @Override - public void visitNode(int level, String parentPath, NormalizedNode normalizedNode) { + public void visitNode(int level, String parentPath, NormalizedNode normalizedNode) { System.out.println(spaces((level) * 4) + normalizedNode.getClass().toString() + ":" + normalizedNode.getIdentifier()); if(normalizedNode instanceof LeafNode || normalizedNode instanceof LeafSetEntryNode){ System.out.println(spaces((level) * 4) + " parentPath = " + parentPath); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java index 9e85ccb9ab..9e847d94ce 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java @@ -13,5 +13,5 @@ package org.opendaylight.controller.cluster.datastore.node.utils; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; public interface NormalizedNodeVisitor { - public void visitNode(int level, String parentPath, NormalizedNode normalizedNode); + public void visitNode(int level, String parentPath, NormalizedNode normalizedNode); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializer.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializer.java index 15d51e1d80..c7bf7d1f7a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializer.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializer.java @@ -81,12 +81,12 @@ public class NormalizedNodeSerializer { * @param node * @return */ - public static NormalizedNodeMessages.Node serialize(NormalizedNode node){ + public static NormalizedNodeMessages.Node serialize(NormalizedNode node){ Preconditions.checkNotNull(node, "node should not be null"); return new Serializer(node).serialize(); } - public static Serializer newSerializer(NormalizedNode node) { + public static Serializer newSerializer(NormalizedNode node) { Preconditions.checkNotNull(node, "node should not be null"); return new Serializer(node); } @@ -97,7 +97,7 @@ public class NormalizedNodeSerializer { * @param node * @return */ - public static NormalizedNode deSerialize(NormalizedNodeMessages.Node node) { + public static NormalizedNode deSerialize(NormalizedNodeMessages.Node node) { Preconditions.checkNotNull(node, "node should not be null"); return new DeSerializer(null, node).deSerialize(); } @@ -131,11 +131,11 @@ public class NormalizedNodeSerializer { public static class Serializer extends QNameSerializationContextImpl implements NormalizedNodeSerializationContext { - private final NormalizedNode node; + private final NormalizedNode node; private NormalizedNodeMessages.InstanceIdentifier serializedPath; - private Serializer(NormalizedNode node) { + private Serializer(NormalizedNode node) { this.node = node; } @@ -154,7 +154,7 @@ public class NormalizedNodeSerializer { } private NormalizedNodeMessages.Node.Builder serialize( - NormalizedNode node) { + NormalizedNode node) { NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); @@ -179,17 +179,17 @@ public class NormalizedNodeSerializer { ValueSerializer.serialize(builder, this, value); } else if (value instanceof Iterable) { - Iterable iterable = (Iterable) value; + Iterable iterable = (Iterable) value; for (Object o : iterable) { if (o instanceof NormalizedNode) { - builder.addChild(serialize((NormalizedNode) o)); + builder.addChild(serialize((NormalizedNode) o)); } } } else if (value instanceof NormalizedNode) { - builder.addChild(serialize((NormalizedNode) value)); + builder.addChild(serialize((NormalizedNode) value)); } else { @@ -208,7 +208,7 @@ public class NormalizedNodeSerializer { static { deSerializationFunctions.put(CONTAINER_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { DataContainerNodeAttrBuilder @@ -226,7 +226,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(LEAF_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { NormalizedNodeAttrBuilder> @@ -243,7 +243,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(MAP_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { CollectionNodeBuilder @@ -255,7 +255,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(MAP_ENTRY_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { DataContainerNodeAttrBuilder @@ -270,7 +270,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(AUGMENTATION_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { DataContainerNodeBuilder @@ -286,7 +286,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(LEAF_SET_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { ListNodeBuilder> @@ -298,7 +298,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(LEAF_SET_ENTRY_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { NormalizedNodeAttrBuilder> @@ -313,7 +313,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(CHOICE_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { DataContainerNodeBuilder @@ -330,7 +330,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(ORDERED_LEAF_SET_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { ListNodeBuilder> @@ -345,7 +345,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(ORDERED_MAP_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { CollectionNodeBuilder @@ -358,7 +358,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(UNKEYED_LIST_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { CollectionNodeBuilder @@ -371,7 +371,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(UNKEYED_LIST_ENTRY_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { DataContainerNodeAttrBuilder @@ -389,7 +389,7 @@ public class NormalizedNodeSerializer { deSerializationFunctions.put(ANY_XML_NODE_TYPE, new DeSerializationFunction() { - @Override public NormalizedNode apply( + @Override public NormalizedNode apply( DeSerializer deSerializer, NormalizedNodeMessages.Node node) { NormalizedNodeAttrBuilder, AnyXmlNode> @@ -421,8 +421,8 @@ public class NormalizedNodeSerializer { return deserializedPath; } - public NormalizedNode deSerialize() { - NormalizedNode deserializedNode = deSerialize(node); + public NormalizedNode deSerialize() { + NormalizedNode deserializedNode = deSerialize(node); if(path != null) { deserializedPath = InstanceIdentifierUtils.fromSerializable(path, this); } @@ -430,7 +430,7 @@ public class NormalizedNodeSerializer { return deserializedNode; } - private NormalizedNode deSerialize(NormalizedNodeMessages.Node node){ + private NormalizedNode deSerialize(NormalizedNodeMessages.Node node){ Preconditions.checkNotNull(node, "node should not be null"); DeSerializationFunction deSerializationFunction = deSerializationFunctions.get( @@ -440,7 +440,7 @@ public class NormalizedNodeSerializer { } - private NormalizedNode buildCollectionNode( + private NormalizedNode buildCollectionNode( CollectionNodeBuilder builder, NormalizedNodeMessages.Node node) { @@ -454,7 +454,7 @@ public class NormalizedNodeSerializer { } - private NormalizedNode buildListNode( + private NormalizedNode buildListNode( ListNodeBuilder> builder, NormalizedNodeMessages.Node node) { builder.withNodeIdentifier(toNodeIdentifier(node.getPathArgument())); @@ -466,7 +466,7 @@ public class NormalizedNodeSerializer { return builder.build(); } - private NormalizedNode buildDataContainer(DataContainerNodeBuilder builder, NormalizedNodeMessages.Node node){ + private NormalizedNode buildDataContainer(DataContainerNodeBuilder builder, NormalizedNodeMessages.Node node){ for(NormalizedNodeMessages.Node child : node.getChildList()){ builder.withChild((DataContainerChild) deSerialize(child)); @@ -477,7 +477,7 @@ public class NormalizedNodeSerializer { return builder.build(); } - private NormalizedNode buildNormalizedNode(NormalizedNodeAttrBuilder builder, NormalizedNodeMessages.Node node){ + private NormalizedNode buildNormalizedNode(NormalizedNodeAttrBuilder builder, NormalizedNodeMessages.Node node){ builder.withValue(ValueSerializer.deSerialize(this, node)); @@ -515,7 +515,7 @@ public class NormalizedNodeSerializer { } private static interface DeSerializationFunction { - NormalizedNode apply(DeSerializer deserializer, NormalizedNodeMessages.Node node); + NormalizedNode apply(DeSerializer deserializer, NormalizedNodeMessages.Node node); } } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeType.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeType.java index 2d6d738b76..b7460e8acf 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeType.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeType.java @@ -39,7 +39,7 @@ public enum NormalizedNodeType { UNKEYED_LIST_ENTRY_NODE_TYPE, ANY_XML_NODE_TYPE; - public static NormalizedNodeType getSerializableNodeType(NormalizedNode node){ + public static NormalizedNodeType getSerializableNodeType(NormalizedNode node){ Preconditions.checkNotNull(node, "node should not be null"); if(node instanceof LeafNode){ diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializer.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializer.java index 6a843f57c7..f562d8b35d 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializer.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializer.java @@ -8,15 +8,15 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; -import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory; -import org.opendaylight.controller.cluster.datastore.util.InstanceIdentifierUtils; -import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; - +import com.google.protobuf.ByteString; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashSet; import java.util.Set; +import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory; +import org.opendaylight.controller.cluster.datastore.util.InstanceIdentifierUtils; +import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class ValueSerializer { public static void serialize(NormalizedNodeMessages.Node.Builder builder, @@ -27,17 +27,19 @@ public class ValueSerializer { builder.setInstanceIdentifierValue( InstanceIdentifierUtils.toSerializable((YangInstanceIdentifier) value, context)); } else if(value instanceof Set) { - Set set = (Set) value; - if(!set.isEmpty()){ - for(Object o : set){ - if(o instanceof String){ + Set set = (Set) value; + if (!set.isEmpty()) { + for (Object o : set) { + if (o instanceof String) { builder.addBitsValue(o.toString()); } else { throw new IllegalArgumentException("Expected value type to be Bits but was : " + - value.toString()); + value.toString()); } } } + } else if(value instanceof byte[]){ + builder.setBytesValue(ByteString.copyFrom((byte[]) value)); } else { builder.setValue(value.toString()); } @@ -47,7 +49,27 @@ public class ValueSerializer { QNameSerializationContext context, Object value){ builder.setType(ValueType.getSerializableType(value).ordinal()); - builder.setValue(value.toString()); + + if(value instanceof YangInstanceIdentifier) { + builder.setInstanceIdentifierValue( + InstanceIdentifierUtils.toSerializable((YangInstanceIdentifier) value, context)); + } else if(value instanceof Set) { + Set set = (Set) value; + if (!set.isEmpty()) { + for (Object o : set) { + if (o instanceof String) { + builder.addBitsValue(o.toString()); + } else { + throw new IllegalArgumentException("Expected value type to be Bits but was : " + + value.toString()); + } + } + } + } else if(value instanceof byte[]){ + builder.setBytesValue(ByteString.copyFrom((byte[]) value)); + } else { + builder.setValue(value.toString()); + } } public static Object deSerialize(QNameDeSerializationContext context, @@ -56,13 +78,24 @@ public class ValueSerializer { return InstanceIdentifierUtils.fromSerializable( node.getInstanceIdentifierValue(), context); } else if(node.getIntValueType() == ValueType.BITS_TYPE.ordinal()){ - return new HashSet(node.getBitsValueList()); + return new HashSet<>(node.getBitsValueList()); + } else if(node.getIntValueType() == ValueType.BINARY_TYPE.ordinal()){ + return node.getBytesValue().toByteArray(); } return deSerializeBasicTypes(node.getIntValueType(), node.getValue()); } public static Object deSerialize(QNameDeSerializationContext context, NormalizedNodeMessages.PathArgumentAttribute attribute) { + + if(attribute.getType() == ValueType.YANG_IDENTIFIER_TYPE.ordinal()){ + return InstanceIdentifierUtils.fromSerializable( + attribute.getInstanceIdentifierValue(), context); + } else if(attribute.getType() == ValueType.BITS_TYPE.ordinal()){ + return new HashSet<>(attribute.getBitsValueList()); + } else if(attribute.getType() == ValueType.BINARY_TYPE.ordinal()){ + return attribute.getBytesValue().toByteArray(); + } return deSerializeBasicTypes(attribute.getType(), attribute.getValue()); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueType.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueType.java index 49db8967a6..2007544b7e 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueType.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueType.java @@ -29,9 +29,10 @@ public enum ValueType { YANG_IDENTIFIER_TYPE, STRING_TYPE, BIG_INTEGER_TYPE, - BIG_DECIMAL_TYPE; + BIG_DECIMAL_TYPE, + BINARY_TYPE; - private static Map types = new HashMap<>(); + private static Map, ValueType> types = new HashMap<>(); static { types.put(String.class, STRING_TYPE); @@ -45,6 +46,7 @@ public enum ValueType { types.put(Short.class,SHORT_TYPE); types.put(BigInteger.class, BIG_INTEGER_TYPE); types.put(BigDecimal.class, BIG_DECIMAL_TYPE); + types.put(byte[].class, BINARY_TYPE); } public static final ValueType getSerializableType(Object node){ diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NodeTypes.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NodeTypes.java new file mode 100644 index 0000000000..3ff6efbb05 --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NodeTypes.java @@ -0,0 +1,29 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.cluster.datastore.node.utils.stream; + +public class NodeTypes { + + public static final byte LEAF_NODE = 1; + public static final byte LEAF_SET = 2; + public static final byte LEAF_SET_ENTRY_NODE = 3; + public static final byte CONTAINER_NODE = 4; + public static final byte UNKEYED_LIST = 5; + public static final byte UNKEYED_LIST_ITEM = 6; + public static final byte MAP_NODE = 7; + public static final byte MAP_ENTRY_NODE = 8; + public static final byte ORDERED_MAP_NODE = 9; + public static final byte CHOICE_NODE = 10; + public static final byte AUGMENTATION_NODE = 11; + public static final byte ANY_XML_NODE = 12; + public static final byte END_NODE = 13; + +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeInputStreamReader.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeInputStreamReader.java new file mode 100644 index 0000000000..797258b443 --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeInputStreamReader.java @@ -0,0 +1,400 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.cluster.datastore.node.utils.stream; + +import com.google.common.base.Preconditions; +import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.data.api.Node; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode; +import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode; +import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; +import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; +import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.MapNode; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode; +import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode; +import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode; +import org.opendaylight.yangtools.yang.data.impl.schema.Builders; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder; +import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes. + * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE. + * If a node can have children, then that node's end is calculated based on appearance of END_NODE. + * + */ + +public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamReader { + + private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class); + + private static final String REVISION_ARG = "?revision="; + + private final DataInputStream reader; + + private final Map codedStringMap = new HashMap<>(); + + private QName lastLeafSetQName; + + public NormalizedNodeInputStreamReader(InputStream stream) throws IOException { + Preconditions.checkNotNull(stream); + reader = new DataInputStream(stream); + } + + @Override + public NormalizedNode readNormalizedNode() throws IOException { + NormalizedNode node = null; + + // each node should start with a byte + byte nodeType = reader.readByte(); + + if(nodeType == NodeTypes.END_NODE) { + LOG.debug("End node reached. return"); + return null; + } + else if(nodeType == NodeTypes.AUGMENTATION_NODE) { + LOG.debug("Reading augmentation node. will create augmentation identifier"); + + YangInstanceIdentifier.AugmentationIdentifier identifier = + new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet()); + DataContainerNodeBuilder augmentationBuilder = + Builders.augmentationBuilder().withNodeIdentifier(identifier); + augmentationBuilder = addDataContainerChildren(augmentationBuilder); + node = augmentationBuilder.build(); + + } else { + if(nodeType == NodeTypes.LEAF_SET_ENTRY_NODE) { + LOG.debug("Reading leaf set entry node. Will create NodeWithValue instance identifier"); + + // Read the object value + Object value = readObject(); + + YangInstanceIdentifier.NodeWithValue nodeWithValue = new YangInstanceIdentifier.NodeWithValue( + lastLeafSetQName, value); + node = Builders.leafSetEntryBuilder().withNodeIdentifier(nodeWithValue). + withValue(value).build(); + + } else if(nodeType == NodeTypes.MAP_ENTRY_NODE) { + LOG.debug("Reading map entry node. Will create node identifier with predicates."); + + QName qName = readQName(); + YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifier = + new YangInstanceIdentifier.NodeIdentifierWithPredicates(qName, readKeyValueMap()); + DataContainerNodeAttrBuilder mapEntryBuilder + = Builders.mapEntryBuilder().withNodeIdentifier(nodeIdentifier); + + mapEntryBuilder = (DataContainerNodeAttrBuilder)addDataContainerChildren(mapEntryBuilder); + node = mapEntryBuilder.build(); + + } else { + LOG.debug("Creating standard node identifier. "); + + QName qName = readQName(); + YangInstanceIdentifier.NodeIdentifier identifier = new YangInstanceIdentifier.NodeIdentifier(qName); + node = readNodeIdentifierDependentNode(nodeType, identifier); + + } + } + return node; + } + + private NormalizedNode readNodeIdentifierDependentNode(byte nodeType, YangInstanceIdentifier.NodeIdentifier identifier) + throws IOException { + + switch(nodeType) { + case NodeTypes.LEAF_NODE : + LOG.debug("Read leaf node"); + // Read the object value + NormalizedNodeAttrBuilder leafBuilder = Builders.leafBuilder(); + return leafBuilder.withNodeIdentifier(identifier).withValue(readObject()).build(); + + case NodeTypes.ANY_XML_NODE : + LOG.debug("Read xml node"); + Node value = (Node) readObject(); + return Builders.anyXmlBuilder().withValue(value).build(); + + case NodeTypes.MAP_NODE : + LOG.debug("Read map node"); + CollectionNodeBuilder mapBuilder = Builders.mapBuilder().withNodeIdentifier(identifier); + mapBuilder = addMapNodeChildren(mapBuilder); + return mapBuilder.build(); + + case NodeTypes.CHOICE_NODE : + LOG.debug("Read choice node"); + DataContainerNodeBuilder choiceBuilder = + Builders.choiceBuilder().withNodeIdentifier(identifier); + choiceBuilder = addDataContainerChildren(choiceBuilder); + return choiceBuilder.build(); + + case NodeTypes.ORDERED_MAP_NODE : + LOG.debug("Reading ordered map node"); + CollectionNodeBuilder orderedMapBuilder = + Builders.orderedMapBuilder().withNodeIdentifier(identifier); + orderedMapBuilder = addMapNodeChildren(orderedMapBuilder); + return orderedMapBuilder.build(); + + case NodeTypes.UNKEYED_LIST : + LOG.debug("Read unkeyed list node"); + CollectionNodeBuilder unkeyedListBuilder = + Builders.unkeyedListBuilder().withNodeIdentifier(identifier); + unkeyedListBuilder = addUnkeyedListChildren(unkeyedListBuilder); + return unkeyedListBuilder.build(); + + case NodeTypes.UNKEYED_LIST_ITEM : + LOG.debug("Read unkeyed list item node"); + DataContainerNodeAttrBuilder unkeyedListEntryBuilder + = Builders.unkeyedListEntryBuilder().withNodeIdentifier(identifier); + + unkeyedListEntryBuilder = (DataContainerNodeAttrBuilder) + addDataContainerChildren(unkeyedListEntryBuilder); + return unkeyedListEntryBuilder.build(); + + case NodeTypes.CONTAINER_NODE : + LOG.debug("Read container node"); + DataContainerNodeAttrBuilder containerBuilder = + Builders.containerBuilder().withNodeIdentifier(identifier); + + containerBuilder = (DataContainerNodeAttrBuilder) + addDataContainerChildren(containerBuilder); + return containerBuilder.build(); + + case NodeTypes.LEAF_SET : + LOG.debug("Read leaf set node"); + ListNodeBuilder> leafSetBuilder = + Builders.leafSetBuilder().withNodeIdentifier(identifier); + leafSetBuilder = addLeafSetChildren(identifier.getNodeType(), leafSetBuilder); + return leafSetBuilder.build(); + + default : + return null; + } + } + + private QName readQName() throws IOException { + // Read in the same sequence of writing + String localName = readCodedString(); + String namespace = readCodedString(); + String revision = readCodedString(); + String qName; + // Not using stringbuilder as compiler optimizes string concatenation of + + if(revision != null){ + qName = "(" + namespace+ REVISION_ARG + revision + ")" +localName; + } else { + qName = "(" + namespace + ")" +localName; + } + + return QNameFactory.create(qName); + } + + + private String readCodedString() throws IOException { + boolean readFromMap = reader.readBoolean(); + if(readFromMap) { + return codedStringMap.get(reader.readInt()); + } else { + String value = reader.readUTF(); + if(value != null) { + codedStringMap.put(Integer.valueOf(codedStringMap.size()), value); + } + return value; + } + } + + private Set readQNameSet() throws IOException{ + // Read the children count + int count = reader.readInt(); + Set children = new HashSet<>(count); + for(int i = 0; i readKeyValueMap() throws IOException { + int count = reader.readInt(); + Map keyValueMap = new HashMap<>(count); + + for(int i = 0; i pathArguments = new ArrayList<>(size); + + for(int i=0; i readObjSet() throws IOException { + int count = reader.readInt(); + Set children = new HashSet<>(count); + for(int i = 0; i> addLeafSetChildren(QName nodeType, + ListNodeBuilder> builder) + throws IOException { + + LOG.debug("Reading children of leaf set"); + + lastLeafSetQName = nodeType; + + LeafSetEntryNode child = (LeafSetEntryNode)readNormalizedNode(); + + while(child != null) { + builder.withChild(child); + child = (LeafSetEntryNode)readNormalizedNode(); + } + return builder; + } + + private CollectionNodeBuilder addUnkeyedListChildren( + CollectionNodeBuilder builder) + throws IOException{ + + LOG.debug("Reading children of unkeyed list"); + UnkeyedListEntryNode child = (UnkeyedListEntryNode)readNormalizedNode(); + + while(child != null) { + builder.withChild(child); + child = (UnkeyedListEntryNode)readNormalizedNode(); + } + return builder; + } + + private DataContainerNodeBuilder addDataContainerChildren(DataContainerNodeBuilder builder) + throws IOException { + LOG.debug("Reading data container (leaf nodes) nodes"); + + DataContainerChild child = + (DataContainerChild) readNormalizedNode(); + + while(child != null) { + builder.withChild(child); + child = + (DataContainerChild) readNormalizedNode(); + } + return builder; + } + + + private CollectionNodeBuilder addMapNodeChildren(CollectionNodeBuilder builder) + throws IOException { + LOG.debug("Reading map node children"); + MapEntryNode child = (MapEntryNode)readNormalizedNode(); + + while(child != null){ + builder.withChild(child); + child = (MapEntryNode)readNormalizedNode(); + } + + return builder; + } + + + @Override + public void close() throws IOException { + reader.close(); + } + +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeOutputStreamWriter.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeOutputStreamWriter.java new file mode 100644 index 0000000000..08567fd79e --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeOutputStreamWriter.java @@ -0,0 +1,342 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.cluster.datastore.node.utils.stream; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * NormalizedNodeOutputStreamWriter will be used by distributed datastore to send normalized node in + * a stream. + * A stream writer wrapper around this class will write node objects to stream in recursive manner. + * for example - If you have a ContainerNode which has a two LeafNode as children, then + * you will first call {@link #startContainerNode(YangInstanceIdentifier.NodeIdentifier, int)}, then will call + * {@link #leafNode(YangInstanceIdentifier.NodeIdentifier, Object)} twice and then, {@link #endNode()} to end + * container node. + * + * Based on the each node, the node type is also written to the stream, that helps in reconstructing the object, + * while reading. + * + * + */ + +public class NormalizedNodeOutputStreamWriter implements NormalizedNodeStreamWriter{ + + private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeOutputStreamWriter.class); + + private final DataOutputStream writer; + + private final Map stringCodeMap = new HashMap<>(); + + public NormalizedNodeOutputStreamWriter(OutputStream stream) throws IOException { + Preconditions.checkNotNull(stream); + writer = new DataOutputStream(stream); + } + + @Override + public void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + LOG.debug("Writing a new leaf node"); + startNode(name.getNodeType(), NodeTypes.LEAF_NODE); + + writeObject(value); + } + + @Override + public void startLeafSet(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + LOG.debug("Starting a new leaf set"); + + startNode(name.getNodeType(), NodeTypes.LEAF_SET); + } + + @Override + public void leafSetEntryNode(Object value) throws IOException, IllegalArgumentException { + LOG.debug("Writing a new leaf set entry node"); + + writer.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE); + writeObject(value); + } + + @Override + public void startContainerNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + + LOG.debug("Starting a new container node"); + + startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE); + } + + @Override + public void startUnkeyedList(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + LOG.debug("Starting a new unkeyed list"); + + startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST); + } + + @Override + public void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalStateException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + LOG.debug("Starting a new unkeyed list item"); + + startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM); + } + + @Override + public void startMapNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + LOG.debug("Starting a new map node"); + + startNode(name.getNodeType(), NodeTypes.MAP_NODE); + } + + @Override + public void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, int childSizeHint) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(identifier, "Node identifier should not be null"); + LOG.debug("Starting a new map entry node"); + startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE); + + writeKeyValueMap(identifier.getKeyValues()); + + } + + @Override + public void startOrderedMapNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + LOG.debug("Starting a new ordered map node"); + + startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE); + } + + @Override + public void startChoiceNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + LOG.debug("Starting a new choice node"); + + startNode(name.getNodeType(), NodeTypes.CHOICE_NODE); + } + + @Override + public void startAugmentationNode(YangInstanceIdentifier.AugmentationIdentifier identifier) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(identifier, "Node identifier should not be null"); + LOG.debug("Starting a new augmentation node"); + + writer.writeByte(NodeTypes.AUGMENTATION_NODE); + writeQNameSet(identifier.getPossibleChildNames()); + } + + @Override + public void anyxmlNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException { + Preconditions.checkNotNull(name, "Node identifier should not be null"); + LOG.debug("Writing a new xml node"); + + startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE); + + writeObject(value); + } + + @Override + public void endNode() throws IOException, IllegalStateException { + LOG.debug("Ending the node"); + + writer.writeByte(NodeTypes.END_NODE); + } + + @Override + public void close() throws IOException { + writer.close(); + } + + @Override + public void flush() throws IOException { + writer.flush(); + } + + private void startNode(final QName qName, byte nodeType) throws IOException { + + Preconditions.checkNotNull(qName, "QName of node identifier should not be null."); + // First write the type of node + writer.writeByte(nodeType); + // Write Start Tag + writeQName(qName); + } + + private void writeQName(QName qName) throws IOException { + + writeCodedString(qName.getLocalName()); + writeCodedString(qName.getNamespace().toString()); + writeCodedString(qName.getFormattedRevision()); + } + + private void writeCodedString(String key) throws IOException { + Integer value = stringCodeMap.get(key); + + if(value != null) { + writer.writeBoolean(true); + writer.writeInt(value); + } else { + if(key != null) { + stringCodeMap.put(key, Integer.valueOf(stringCodeMap.size())); + } + writer.writeBoolean(false); + writer.writeUTF(key); + } + } + + private void writeObjSet(Set set) throws IOException { + if(!set.isEmpty()){ + writer.writeInt(set.size()); + for(Object o : set){ + if(o instanceof String){ + writeCodedString(o.toString()); + } else { + throw new IllegalArgumentException("Expected value type to be String but was : " + + o.toString()); + } + } + } else { + writer.writeInt(0); + } + } + + private void writeYangInstanceIdentifier(YangInstanceIdentifier identifier) throws IOException { + Iterable pathArguments = identifier.getPathArguments(); + int size = Iterables.size(pathArguments); + writer.writeInt(size); + + for(YangInstanceIdentifier.PathArgument pathArgument : pathArguments) { + writePathArgument(pathArgument); + } + } + + private void writePathArgument(YangInstanceIdentifier.PathArgument pathArgument) throws IOException { + + byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument); + + writer.writeByte(type); + + switch(type) { + case PathArgumentTypes.NODE_IDENTIFIER : + + YangInstanceIdentifier.NodeIdentifier nodeIdentifier = + (YangInstanceIdentifier.NodeIdentifier) pathArgument; + + writeQName(nodeIdentifier.getNodeType()); + break; + + case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES: + + YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates = + (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument; + writeQName(nodeIdentifierWithPredicates.getNodeType()); + + writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues()); + break; + + case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE : + + YangInstanceIdentifier.NodeWithValue nodeWithValue = + (YangInstanceIdentifier.NodeWithValue) pathArgument; + + writeQName(nodeWithValue.getNodeType()); + writeObject(nodeWithValue.getValue()); + break; + + case PathArgumentTypes.AUGMENTATION_IDENTIFIER : + + YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier = + (YangInstanceIdentifier.AugmentationIdentifier) pathArgument; + + // No Qname in augmentation identifier + writeQNameSet(augmentationIdentifier.getPossibleChildNames()); + break; + default : + throw new IllegalStateException("Unknown node identifier type is found : " + pathArgument.getClass().toString() ); + } + } + + private void writeKeyValueMap(Map keyValueMap) throws IOException { + if(keyValueMap != null && !keyValueMap.isEmpty()) { + writer.writeInt(keyValueMap.size()); + Set qNameSet = keyValueMap.keySet(); + + for(QName qName : qNameSet) { + writeQName(qName); + writeObject(keyValueMap.get(qName)); + } + } else { + writer.writeInt(0); + } + } + + private void writeQNameSet(Set children) throws IOException { + // Write each child's qname separately, if list is empty send count as 0 + if(children != null && !children.isEmpty()) { + writer.writeInt(children.size()); + for(QName qName : children) { + writeQName(qName); + } + } else { + LOG.debug("augmentation node does not have any child"); + writer.writeInt(0); + } + } + + private void writeObject(Object value) throws IOException { + + byte type = ValueTypes.getSerializableType(value); + // Write object type first + writer.writeByte(type); + + switch(type) { + case ValueTypes.BOOL_TYPE: + writer.writeBoolean((Boolean) value); + break; + case ValueTypes.QNAME_TYPE: + writeQName((QName) value); + break; + case ValueTypes.INT_TYPE: + writer.writeInt((Integer) value); + break; + case ValueTypes.BYTE_TYPE: + writer.writeByte((Byte) value); + break; + case ValueTypes.LONG_TYPE: + writer.writeLong((Long) value); + break; + case ValueTypes.SHORT_TYPE: + writer.writeShort((Short) value); + break; + case ValueTypes.BITS_TYPE: + writeObjSet((Set) value); + break; + case ValueTypes.YANG_IDENTIFIER_TYPE: + writeYangInstanceIdentifier((YangInstanceIdentifier) value); + break; + default: + writer.writeUTF(value.toString()); + break; + } + } +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReader.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReader.java new file mode 100644 index 0000000000..c619afd7ee --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReader.java @@ -0,0 +1,23 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + + +package org.opendaylight.controller.cluster.datastore.node.utils.stream; + + +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; + +import java.io.IOException; + + +public interface NormalizedNodeStreamReader extends AutoCloseable { + + NormalizedNode readNormalizedNode() throws IOException; +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/PathArgumentTypes.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/PathArgumentTypes.java new file mode 100644 index 0000000000..b01beb8c77 --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/PathArgumentTypes.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.datastore.node.utils.stream; + +import com.google.common.collect.ImmutableMap; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; + +import java.util.Map; + +public class PathArgumentTypes { + public static final byte AUGMENTATION_IDENTIFIER = 1; + public static final byte NODE_IDENTIFIER = 2; + public static final byte NODE_IDENTIFIER_WITH_VALUE = 3; + public static final byte NODE_IDENTIFIER_WITH_PREDICATES = 4; + + private static Map, Byte> CLASS_TO_ENUM_MAP = + ImmutableMap., Byte>builder(). + put(YangInstanceIdentifier.AugmentationIdentifier.class, AUGMENTATION_IDENTIFIER). + put(YangInstanceIdentifier.NodeIdentifier.class, NODE_IDENTIFIER). + put(YangInstanceIdentifier.NodeIdentifierWithPredicates.class, NODE_IDENTIFIER_WITH_PREDICATES). + put(YangInstanceIdentifier.NodeWithValue.class, NODE_IDENTIFIER_WITH_VALUE).build(); + + public static byte getSerializablePathArgumentType(YangInstanceIdentifier.PathArgument pathArgument){ + + Byte type = CLASS_TO_ENUM_MAP.get(pathArgument.getClass()); + if(type == null) { + throw new IllegalArgumentException("Unknown type of PathArgument = " + pathArgument); + } + + return type; + } + +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/ValueTypes.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/ValueTypes.java new file mode 100644 index 0000000000..80fa527b46 --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/ValueTypes.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.datastore.node.utils.stream; + +import com.google.common.base.Preconditions; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class ValueTypes { + public static final byte SHORT_TYPE = 1; + public static final byte BYTE_TYPE = 2; + public static final byte INT_TYPE = 3; + public static final byte LONG_TYPE = 4; + public static final byte BOOL_TYPE = 5; + public static final byte QNAME_TYPE = 6; + public static final byte BITS_TYPE = 7; + public static final byte YANG_IDENTIFIER_TYPE = 8; + public static final byte STRING_TYPE = 9; + public static final byte BIG_INTEGER_TYPE = 10; + public static final byte BIG_DECIMAL_TYPE = 11; + + private static Map, Byte> types = new HashMap<>(); + + static { + types.put(String.class, Byte.valueOf(STRING_TYPE)); + types.put(Byte.class, Byte.valueOf(BYTE_TYPE)); + types.put(Integer.class, Byte.valueOf(INT_TYPE)); + types.put(Long.class, Byte.valueOf(LONG_TYPE)); + types.put(Boolean.class, Byte.valueOf(BOOL_TYPE)); + types.put(QName.class, Byte.valueOf(QNAME_TYPE)); + types.put(Set.class, Byte.valueOf(BITS_TYPE)); + types.put(YangInstanceIdentifier.class, Byte.valueOf(YANG_IDENTIFIER_TYPE)); + types.put(Short.class, Byte.valueOf(SHORT_TYPE)); + types.put(BigInteger.class, Byte.valueOf(BIG_INTEGER_TYPE)); + types.put(BigDecimal.class, Byte.valueOf(BIG_DECIMAL_TYPE)); + } + + public static final byte getSerializableType(Object node){ + Preconditions.checkNotNull(node, "node should not be null"); + + Byte type = types.get(node.getClass()); + if(type != null) { + return type; + } else if(node instanceof Set){ + return BITS_TYPE; + } + + throw new IllegalArgumentException("Unknown value type " + node.getClass().getSimpleName()); + } +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/raft/protobuff/client/messages/CompositeModificationPayload.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/raft/protobuff/client/messages/CompositeModificationPayload.java index 8822ac83a6..aadc3625cc 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/raft/protobuff/client/messages/CompositeModificationPayload.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/raft/protobuff/client/messages/CompositeModificationPayload.java @@ -21,6 +21,7 @@ import java.util.Map; public class CompositeModificationPayload extends Payload implements Serializable { + private static final long serialVersionUID = 1L; private final PersistentMessages.CompositeModification modification; diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java index e43b44582d..2a79a5b827 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java @@ -11,17 +11,17 @@ public final class ThreePhaseCommitCohortMessages { public interface CanCommitTransactionOrBuilder extends com.google.protobuf.MessageOrBuilder { - // required string transactionId = 1; + // optional string transactionId = 1; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ boolean hasTransactionId(); /** - * required string transactionId = 1; + * optional string transactionId = 1; */ java.lang.String getTransactionId(); /** - * required string transactionId = 1; + * optional string transactionId = 1; */ com.google.protobuf.ByteString getTransactionIdBytes(); @@ -122,17 +122,17 @@ public final class ThreePhaseCommitCohortMessages { } private int bitField0_; - // required string transactionId = 1; + // optional string transactionId = 1; public static final int TRANSACTIONID_FIELD_NUMBER = 1; private java.lang.Object transactionId_; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public boolean hasTransactionId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public java.lang.String getTransactionId() { java.lang.Object ref = transactionId_; @@ -149,7 +149,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public com.google.protobuf.ByteString getTransactionIdBytes() { @@ -173,10 +173,6 @@ public final class ThreePhaseCommitCohortMessages { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; - if (!hasTransactionId()) { - memoizedIsInitialized = 0; - return false; - } memoizedIsInitialized = 1; return true; } @@ -376,10 +372,6 @@ public final class ThreePhaseCommitCohortMessages { } public final boolean isInitialized() { - if (!hasTransactionId()) { - - return false; - } return true; } @@ -402,16 +394,16 @@ public final class ThreePhaseCommitCohortMessages { } private int bitField0_; - // required string transactionId = 1; + // optional string transactionId = 1; private java.lang.Object transactionId_ = ""; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public boolean hasTransactionId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public java.lang.String getTransactionId() { java.lang.Object ref = transactionId_; @@ -425,7 +417,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public com.google.protobuf.ByteString getTransactionIdBytes() { @@ -441,7 +433,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder setTransactionId( java.lang.String value) { @@ -454,7 +446,7 @@ public final class ThreePhaseCommitCohortMessages { return this; } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder clearTransactionId() { bitField0_ = (bitField0_ & ~0x00000001); @@ -463,7 +455,7 @@ public final class ThreePhaseCommitCohortMessages { return this; } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder setTransactionIdBytes( com.google.protobuf.ByteString value) { @@ -894,17 +886,17 @@ public final class ThreePhaseCommitCohortMessages { public interface AbortTransactionOrBuilder extends com.google.protobuf.MessageOrBuilder { - // required string transactionId = 1; + // optional string transactionId = 1; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ boolean hasTransactionId(); /** - * required string transactionId = 1; + * optional string transactionId = 1; */ java.lang.String getTransactionId(); /** - * required string transactionId = 1; + * optional string transactionId = 1; */ com.google.protobuf.ByteString getTransactionIdBytes(); @@ -1005,17 +997,17 @@ public final class ThreePhaseCommitCohortMessages { } private int bitField0_; - // required string transactionId = 1; + // optional string transactionId = 1; public static final int TRANSACTIONID_FIELD_NUMBER = 1; private java.lang.Object transactionId_; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public boolean hasTransactionId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public java.lang.String getTransactionId() { java.lang.Object ref = transactionId_; @@ -1032,7 +1024,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public com.google.protobuf.ByteString getTransactionIdBytes() { @@ -1056,10 +1048,6 @@ public final class ThreePhaseCommitCohortMessages { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; - if (!hasTransactionId()) { - memoizedIsInitialized = 0; - return false; - } memoizedIsInitialized = 1; return true; } @@ -1259,10 +1247,6 @@ public final class ThreePhaseCommitCohortMessages { } public final boolean isInitialized() { - if (!hasTransactionId()) { - - return false; - } return true; } @@ -1285,16 +1269,16 @@ public final class ThreePhaseCommitCohortMessages { } private int bitField0_; - // required string transactionId = 1; + // optional string transactionId = 1; private java.lang.Object transactionId_ = ""; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public boolean hasTransactionId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public java.lang.String getTransactionId() { java.lang.Object ref = transactionId_; @@ -1308,7 +1292,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public com.google.protobuf.ByteString getTransactionIdBytes() { @@ -1324,7 +1308,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder setTransactionId( java.lang.String value) { @@ -1337,7 +1321,7 @@ public final class ThreePhaseCommitCohortMessages { return this; } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder clearTransactionId() { bitField0_ = (bitField0_ & ~0x00000001); @@ -1346,7 +1330,7 @@ public final class ThreePhaseCommitCohortMessages { return this; } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder setTransactionIdBytes( com.google.protobuf.ByteString value) { @@ -1682,17 +1666,17 @@ public final class ThreePhaseCommitCohortMessages { public interface CommitTransactionOrBuilder extends com.google.protobuf.MessageOrBuilder { - // required string transactionId = 1; + // optional string transactionId = 1; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ boolean hasTransactionId(); /** - * required string transactionId = 1; + * optional string transactionId = 1; */ java.lang.String getTransactionId(); /** - * required string transactionId = 1; + * optional string transactionId = 1; */ com.google.protobuf.ByteString getTransactionIdBytes(); @@ -1793,17 +1777,17 @@ public final class ThreePhaseCommitCohortMessages { } private int bitField0_; - // required string transactionId = 1; + // optional string transactionId = 1; public static final int TRANSACTIONID_FIELD_NUMBER = 1; private java.lang.Object transactionId_; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public boolean hasTransactionId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public java.lang.String getTransactionId() { java.lang.Object ref = transactionId_; @@ -1820,7 +1804,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public com.google.protobuf.ByteString getTransactionIdBytes() { @@ -1844,10 +1828,6 @@ public final class ThreePhaseCommitCohortMessages { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; - if (!hasTransactionId()) { - memoizedIsInitialized = 0; - return false; - } memoizedIsInitialized = 1; return true; } @@ -2047,10 +2027,6 @@ public final class ThreePhaseCommitCohortMessages { } public final boolean isInitialized() { - if (!hasTransactionId()) { - - return false; - } return true; } @@ -2073,16 +2049,16 @@ public final class ThreePhaseCommitCohortMessages { } private int bitField0_; - // required string transactionId = 1; + // optional string transactionId = 1; private java.lang.Object transactionId_ = ""; /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public boolean hasTransactionId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public java.lang.String getTransactionId() { java.lang.Object ref = transactionId_; @@ -2096,7 +2072,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public com.google.protobuf.ByteString getTransactionIdBytes() { @@ -2112,7 +2088,7 @@ public final class ThreePhaseCommitCohortMessages { } } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder setTransactionId( java.lang.String value) { @@ -2125,7 +2101,7 @@ public final class ThreePhaseCommitCohortMessages { return this; } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder clearTransactionId() { bitField0_ = (bitField0_ & ~0x00000001); @@ -2134,7 +2110,7 @@ public final class ThreePhaseCommitCohortMessages { return this; } /** - * required string transactionId = 1; + * optional string transactionId = 1; */ public Builder setTransactionIdBytes( com.google.protobuf.ByteString value) { @@ -3136,11 +3112,11 @@ public final class ThreePhaseCommitCohortMessages { java.lang.String[] descriptorData = { "\n\014Cohort.proto\022!org.opendaylight.control" + "ler.mdsal\"-\n\024CanCommitTransaction\022\025\n\rtra" + - "nsactionId\030\001 \002(\t\".\n\031CanCommitTransaction" + + "nsactionId\030\001 \001(\t\".\n\031CanCommitTransaction" + "Reply\022\021\n\tcanCommit\030\001 \002(\010\")\n\020AbortTransac" + - "tion\022\025\n\rtransactionId\030\001 \002(\t\"\027\n\025AbortTran" + + "tion\022\025\n\rtransactionId\030\001 \001(\t\"\027\n\025AbortTran" + "sactionReply\"*\n\021CommitTransaction\022\025\n\rtra" + - "nsactionId\030\001 \002(\t\"\030\n\026CommitTransactionRep" + + "nsactionId\030\001 \001(\t\"\030\n\026CommitTransactionRep" + "ly\"\026\n\024PreCommitTransaction\"\033\n\031PreCommitT" + "ransactionReplyBZ\n8org.opendaylight.cont" + "roller.protobuff.messages.cohort3pcB\036Thr", diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java index e7f2c361ae..0f14c6b762 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java @@ -840,6 +840,78 @@ public final class NormalizedNodeMessages { * optional int32 type = 3; */ int getType(); + + // optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +     * Specific values
      +     * 
      + */ + boolean hasInstanceIdentifierValue(); + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +     * Specific values
      +     * 
      + */ + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier getInstanceIdentifierValue(); + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +     * Specific values
      +     * 
      + */ + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder getInstanceIdentifierValueOrBuilder(); + + // repeated string bitsValue = 5; + /** + * repeated string bitsValue = 5; + * + *
      +     * intValueType = Bits
      +     * 
      + */ + java.util.List + getBitsValueList(); + /** + * repeated string bitsValue = 5; + * + *
      +     * intValueType = Bits
      +     * 
      + */ + int getBitsValueCount(); + /** + * repeated string bitsValue = 5; + * + *
      +     * intValueType = Bits
      +     * 
      + */ + java.lang.String getBitsValue(int index); + /** + * repeated string bitsValue = 5; + * + *
      +     * intValueType = Bits
      +     * 
      + */ + com.google.protobuf.ByteString + getBitsValueBytes(int index); + + // optional bytes bytesValue = 6; + /** + * optional bytes bytesValue = 6; + */ + boolean hasBytesValue(); + /** + * optional bytes bytesValue = 6; + */ + com.google.protobuf.ByteString getBytesValue(); } /** * Protobuf type {@code org.opendaylight.controller.mdsal.PathArgumentAttribute} @@ -915,6 +987,32 @@ public final class NormalizedNodeMessages { type_ = input.readInt32(); break; } + case 34: { + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder subBuilder = null; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + subBuilder = instanceIdentifierValue_.toBuilder(); + } + instanceIdentifierValue_ = input.readMessage(org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(instanceIdentifierValue_); + instanceIdentifierValue_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000008; + break; + } + case 42: { + if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) { + bitsValue_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000010; + } + bitsValue_.add(input.readBytes()); + break; + } + case 50: { + bitField0_ |= 0x00000010; + bytesValue_ = input.readBytes(); + break; + } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { @@ -923,6 +1021,9 @@ public final class NormalizedNodeMessages { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { + if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) { + bitsValue_ = new com.google.protobuf.UnmodifiableLazyStringList(bitsValue_); + } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } @@ -1036,16 +1137,121 @@ public final class NormalizedNodeMessages { return type_; } + // optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + public static final int INSTANCEIDENTIFIERVALUE_FIELD_NUMBER = 4; + private org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier instanceIdentifierValue_; + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +     * Specific values
      +     * 
      + */ + public boolean hasInstanceIdentifierValue() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +     * Specific values
      +     * 
      + */ + public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier getInstanceIdentifierValue() { + return instanceIdentifierValue_; + } + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +     * Specific values
      +     * 
      + */ + public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder getInstanceIdentifierValueOrBuilder() { + return instanceIdentifierValue_; + } + + // repeated string bitsValue = 5; + public static final int BITSVALUE_FIELD_NUMBER = 5; + private com.google.protobuf.LazyStringList bitsValue_; + /** + * repeated string bitsValue = 5; + * + *
      +     * intValueType = Bits
      +     * 
      + */ + public java.util.List + getBitsValueList() { + return bitsValue_; + } + /** + * repeated string bitsValue = 5; + * + *
      +     * intValueType = Bits
      +     * 
      + */ + public int getBitsValueCount() { + return bitsValue_.size(); + } + /** + * repeated string bitsValue = 5; + * + *
      +     * intValueType = Bits
      +     * 
      + */ + public java.lang.String getBitsValue(int index) { + return bitsValue_.get(index); + } + /** + * repeated string bitsValue = 5; + * + *
      +     * intValueType = Bits
      +     * 
      + */ + public com.google.protobuf.ByteString + getBitsValueBytes(int index) { + return bitsValue_.getByteString(index); + } + + // optional bytes bytesValue = 6; + public static final int BYTESVALUE_FIELD_NUMBER = 6; + private com.google.protobuf.ByteString bytesValue_; + /** + * optional bytes bytesValue = 6; + */ + public boolean hasBytesValue() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * optional bytes bytesValue = 6; + */ + public com.google.protobuf.ByteString getBytesValue() { + return bytesValue_; + } + private void initFields() { name_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.getDefaultInstance(); value_ = ""; type_ = 0; + instanceIdentifierValue_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.getDefaultInstance(); + bitsValue_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bytesValue_ = com.google.protobuf.ByteString.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; + if (hasInstanceIdentifierValue()) { + if (!getInstanceIdentifierValue().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } memoizedIsInitialized = 1; return true; } @@ -1062,6 +1268,15 @@ public final class NormalizedNodeMessages { if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeInt32(3, type_); } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeMessage(4, instanceIdentifierValue_); + } + for (int i = 0; i < bitsValue_.size(); i++) { + output.writeBytes(5, bitsValue_.getByteString(i)); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeBytes(6, bytesValue_); + } getUnknownFields().writeTo(output); } @@ -1083,6 +1298,23 @@ public final class NormalizedNodeMessages { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, type_); } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, instanceIdentifierValue_); + } + { + int dataSize = 0; + for (int i = 0; i < bitsValue_.size(); i++) { + dataSize += com.google.protobuf.CodedOutputStream + .computeBytesSizeNoTag(bitsValue_.getByteString(i)); + } + size += dataSize; + size += 1 * getBitsValueList().size(); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(6, bytesValue_); + } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; @@ -1192,6 +1424,7 @@ public final class NormalizedNodeMessages { private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getNameFieldBuilder(); + getInstanceIdentifierValueFieldBuilder(); } } private static Builder create() { @@ -1210,6 +1443,16 @@ public final class NormalizedNodeMessages { bitField0_ = (bitField0_ & ~0x00000002); type_ = 0; bitField0_ = (bitField0_ & ~0x00000004); + if (instanceIdentifierValueBuilder_ == null) { + instanceIdentifierValue_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.getDefaultInstance(); + } else { + instanceIdentifierValueBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000008); + bitsValue_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000010); + bytesValue_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000020); return this; } @@ -1254,6 +1497,24 @@ public final class NormalizedNodeMessages { to_bitField0_ |= 0x00000004; } result.type_ = type_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + if (instanceIdentifierValueBuilder_ == null) { + result.instanceIdentifierValue_ = instanceIdentifierValue_; + } else { + result.instanceIdentifierValue_ = instanceIdentifierValueBuilder_.build(); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + bitsValue_ = new com.google.protobuf.UnmodifiableLazyStringList( + bitsValue_); + bitField0_ = (bitField0_ & ~0x00000010); + } + result.bitsValue_ = bitsValue_; + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000010; + } + result.bytesValue_ = bytesValue_; result.bitField0_ = to_bitField0_; onBuilt(); return result; @@ -1281,11 +1542,33 @@ public final class NormalizedNodeMessages { if (other.hasType()) { setType(other.getType()); } + if (other.hasInstanceIdentifierValue()) { + mergeInstanceIdentifierValue(other.getInstanceIdentifierValue()); + } + if (!other.bitsValue_.isEmpty()) { + if (bitsValue_.isEmpty()) { + bitsValue_ = other.bitsValue_; + bitField0_ = (bitField0_ & ~0x00000010); + } else { + ensureBitsValueIsMutable(); + bitsValue_.addAll(other.bitsValue_); + } + onChanged(); + } + if (other.hasBytesValue()) { + setBytesValue(other.getBytesValue()); + } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { + if (hasInstanceIdentifierValue()) { + if (!getInstanceIdentifierValue().isInitialized()) { + + return false; + } + } return true; } @@ -1374,160 +1657,478 @@ public final class NormalizedNodeMessages { } else { nameBuilder_.mergeFrom(value); } - bitField0_ |= 0x00000001; + bitField0_ |= 0x00000001; + return this; + } + /** + * optional .org.opendaylight.controller.mdsal.QName name = 1; + */ + public Builder clearName() { + if (nameBuilder_ == null) { + name_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.getDefaultInstance(); + onChanged(); + } else { + nameBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + /** + * optional .org.opendaylight.controller.mdsal.QName name = 1; + */ + public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder getNameBuilder() { + bitField0_ |= 0x00000001; + onChanged(); + return getNameFieldBuilder().getBuilder(); + } + /** + * optional .org.opendaylight.controller.mdsal.QName name = 1; + */ + public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder getNameOrBuilder() { + if (nameBuilder_ != null) { + return nameBuilder_.getMessageOrBuilder(); + } else { + return name_; + } + } + /** + * optional .org.opendaylight.controller.mdsal.QName name = 1; + */ + private com.google.protobuf.SingleFieldBuilder< + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder> + getNameFieldBuilder() { + if (nameBuilder_ == null) { + nameBuilder_ = new com.google.protobuf.SingleFieldBuilder< + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder>( + name_, + getParentForChildren(), + isClean()); + name_ = null; + } + return nameBuilder_; + } + + // optional string value = 2; + private java.lang.Object value_ = ""; + /** + * optional string value = 2; + */ + public boolean hasValue() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional string value = 2; + */ + public java.lang.String getValue() { + java.lang.Object ref = value_; + if (!(ref instanceof java.lang.String)) { + java.lang.String s = ((com.google.protobuf.ByteString) ref) + .toStringUtf8(); + value_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + * optional string value = 2; + */ + public com.google.protobuf.ByteString + getValueBytes() { + java.lang.Object ref = value_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + value_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * optional string value = 2; + */ + public Builder setValue( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + value_ = value; + onChanged(); + return this; + } + /** + * optional string value = 2; + */ + public Builder clearValue() { + bitField0_ = (bitField0_ & ~0x00000002); + value_ = getDefaultInstance().getValue(); + onChanged(); + return this; + } + /** + * optional string value = 2; + */ + public Builder setValueBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + value_ = value; + onChanged(); + return this; + } + + // optional int32 type = 3; + private int type_ ; + /** + * optional int32 type = 3; + */ + public boolean hasType() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * optional int32 type = 3; + */ + public int getType() { + return type_; + } + /** + * optional int32 type = 3; + */ + public Builder setType(int value) { + bitField0_ |= 0x00000004; + type_ = value; + onChanged(); + return this; + } + /** + * optional int32 type = 3; + */ + public Builder clearType() { + bitField0_ = (bitField0_ & ~0x00000004); + type_ = 0; + onChanged(); + return this; + } + + // optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + private org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier instanceIdentifierValue_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> instanceIdentifierValueBuilder_; + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      + */ + public boolean hasInstanceIdentifierValue() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      + */ + public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier getInstanceIdentifierValue() { + if (instanceIdentifierValueBuilder_ == null) { + return instanceIdentifierValue_; + } else { + return instanceIdentifierValueBuilder_.getMessage(); + } + } + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      + */ + public Builder setInstanceIdentifierValue(org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier value) { + if (instanceIdentifierValueBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + instanceIdentifierValue_ = value; + onChanged(); + } else { + instanceIdentifierValueBuilder_.setMessage(value); + } + bitField0_ |= 0x00000008; + return this; + } + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      + */ + public Builder setInstanceIdentifierValue( + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder builderForValue) { + if (instanceIdentifierValueBuilder_ == null) { + instanceIdentifierValue_ = builderForValue.build(); + onChanged(); + } else { + instanceIdentifierValueBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000008; + return this; + } + /** + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      + */ + public Builder mergeInstanceIdentifierValue(org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier value) { + if (instanceIdentifierValueBuilder_ == null) { + if (((bitField0_ & 0x00000008) == 0x00000008) && + instanceIdentifierValue_ != org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.getDefaultInstance()) { + instanceIdentifierValue_ = + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.newBuilder(instanceIdentifierValue_).mergeFrom(value).buildPartial(); + } else { + instanceIdentifierValue_ = value; + } + onChanged(); + } else { + instanceIdentifierValueBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000008; return this; } /** - * optional .org.opendaylight.controller.mdsal.QName name = 1; + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      */ - public Builder clearName() { - if (nameBuilder_ == null) { - name_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.getDefaultInstance(); + public Builder clearInstanceIdentifierValue() { + if (instanceIdentifierValueBuilder_ == null) { + instanceIdentifierValue_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.getDefaultInstance(); onChanged(); } else { - nameBuilder_.clear(); + instanceIdentifierValueBuilder_.clear(); } - bitField0_ = (bitField0_ & ~0x00000001); + bitField0_ = (bitField0_ & ~0x00000008); return this; } /** - * optional .org.opendaylight.controller.mdsal.QName name = 1; + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      */ - public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder getNameBuilder() { - bitField0_ |= 0x00000001; + public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder getInstanceIdentifierValueBuilder() { + bitField0_ |= 0x00000008; onChanged(); - return getNameFieldBuilder().getBuilder(); + return getInstanceIdentifierValueFieldBuilder().getBuilder(); } /** - * optional .org.opendaylight.controller.mdsal.QName name = 1; + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      */ - public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder getNameOrBuilder() { - if (nameBuilder_ != null) { - return nameBuilder_.getMessageOrBuilder(); + public org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder getInstanceIdentifierValueOrBuilder() { + if (instanceIdentifierValueBuilder_ != null) { + return instanceIdentifierValueBuilder_.getMessageOrBuilder(); } else { - return name_; + return instanceIdentifierValue_; } } /** - * optional .org.opendaylight.controller.mdsal.QName name = 1; + * optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 4; + * + *
      +       * Specific values
      +       * 
      */ private com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder> - getNameFieldBuilder() { - if (nameBuilder_ == null) { - nameBuilder_ = new com.google.protobuf.SingleFieldBuilder< - org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder>( - name_, + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> + getInstanceIdentifierValueFieldBuilder() { + if (instanceIdentifierValueBuilder_ == null) { + instanceIdentifierValueBuilder_ = new com.google.protobuf.SingleFieldBuilder< + org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>( + instanceIdentifierValue_, getParentForChildren(), isClean()); - name_ = null; + instanceIdentifierValue_ = null; } - return nameBuilder_; + return instanceIdentifierValueBuilder_; } - // optional string value = 2; - private java.lang.Object value_ = ""; + // repeated string bitsValue = 5; + private com.google.protobuf.LazyStringList bitsValue_ = com.google.protobuf.LazyStringArrayList.EMPTY; + private void ensureBitsValueIsMutable() { + if (!((bitField0_ & 0x00000010) == 0x00000010)) { + bitsValue_ = new com.google.protobuf.LazyStringArrayList(bitsValue_); + bitField0_ |= 0x00000010; + } + } /** - * optional string value = 2; + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      */ - public boolean hasValue() { - return ((bitField0_ & 0x00000002) == 0x00000002); + public java.util.List + getBitsValueList() { + return java.util.Collections.unmodifiableList(bitsValue_); } /** - * optional string value = 2; + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      */ - public java.lang.String getValue() { - java.lang.Object ref = value_; - if (!(ref instanceof java.lang.String)) { - java.lang.String s = ((com.google.protobuf.ByteString) ref) - .toStringUtf8(); - value_ = s; - return s; - } else { - return (java.lang.String) ref; - } + public int getBitsValueCount() { + return bitsValue_.size(); } /** - * optional string value = 2; + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      + */ + public java.lang.String getBitsValue(int index) { + return bitsValue_.get(index); + } + /** + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      */ public com.google.protobuf.ByteString - getValueBytes() { - java.lang.Object ref = value_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - value_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + getBitsValueBytes(int index) { + return bitsValue_.getByteString(index); } /** - * optional string value = 2; + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      */ - public Builder setValue( + public Builder setBitsValue( + int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureBitsValueIsMutable(); + bitsValue_.set(index, value); + onChanged(); + return this; + } + /** + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      + */ + public Builder addBitsValue( java.lang.String value) { if (value == null) { throw new NullPointerException(); } - bitField0_ |= 0x00000002; - value_ = value; + ensureBitsValueIsMutable(); + bitsValue_.add(value); onChanged(); return this; } /** - * optional string value = 2; + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      */ - public Builder clearValue() { - bitField0_ = (bitField0_ & ~0x00000002); - value_ = getDefaultInstance().getValue(); + public Builder addAllBitsValue( + java.lang.Iterable values) { + ensureBitsValueIsMutable(); + super.addAll(values, bitsValue_); onChanged(); return this; } /** - * optional string value = 2; + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      */ - public Builder setValueBytes( + public Builder clearBitsValue() { + bitsValue_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000010); + onChanged(); + return this; + } + /** + * repeated string bitsValue = 5; + * + *
      +       * intValueType = Bits
      +       * 
      + */ + public Builder addBitsValueBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } - bitField0_ |= 0x00000002; - value_ = value; + ensureBitsValueIsMutable(); + bitsValue_.add(value); onChanged(); return this; } - // optional int32 type = 3; - private int type_ ; + // optional bytes bytesValue = 6; + private com.google.protobuf.ByteString bytesValue_ = com.google.protobuf.ByteString.EMPTY; /** - * optional int32 type = 3; + * optional bytes bytesValue = 6; */ - public boolean hasType() { - return ((bitField0_ & 0x00000004) == 0x00000004); + public boolean hasBytesValue() { + return ((bitField0_ & 0x00000020) == 0x00000020); } /** - * optional int32 type = 3; + * optional bytes bytesValue = 6; */ - public int getType() { - return type_; + public com.google.protobuf.ByteString getBytesValue() { + return bytesValue_; } /** - * optional int32 type = 3; + * optional bytes bytesValue = 6; */ - public Builder setType(int value) { - bitField0_ |= 0x00000004; - type_ = value; + public Builder setBytesValue(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000020; + bytesValue_ = value; onChanged(); return this; } /** - * optional int32 type = 3; + * optional bytes bytesValue = 6; */ - public Builder clearType() { - bitField0_ = (bitField0_ & ~0x00000004); - type_ = 0; + public Builder clearBytesValue() { + bitField0_ = (bitField0_ & ~0x00000020); + bytesValue_ = getDefaultInstance().getBytesValue(); onChanged(); return this; } @@ -2850,6 +3451,12 @@ public final class NormalizedNodeMessages { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; + for (int i = 0; i < getAttributeCount(); i++) { + if (!getAttribute(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } for (int i = 0; i < getAttributesCount(); i++) { if (!getAttributes(i).isInitialized()) { memoizedIsInitialized = 0; @@ -3212,6 +3819,12 @@ public final class NormalizedNodeMessages { } public final boolean isInitialized() { + for (int i = 0; i < getAttributeCount(); i++) { + if (!getAttribute(i).isInitialized()) { + + return false; + } + } for (int i = 0; i < getAttributesCount(); i++) { if (!getAttributes(i).isInitialized()) { @@ -5410,6 +6023,16 @@ public final class NormalizedNodeMessages { */ com.google.protobuf.ByteString getCodeBytes(int index); + + // optional bytes bytesValue = 13; + /** + * optional bytes bytesValue = 13; + */ + boolean hasBytesValue(); + /** + * optional bytes bytesValue = 13; + */ + com.google.protobuf.ByteString getBytesValue(); } /** * Protobuf type {@code org.opendaylight.controller.mdsal.Node} @@ -5550,6 +6173,11 @@ public final class NormalizedNodeMessages { code_.add(input.readBytes()); break; } + case 106: { + bitField0_ |= 0x00000100; + bytesValue_ = input.readBytes(); + break; + } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { @@ -6070,6 +6698,22 @@ public final class NormalizedNodeMessages { return code_.getByteString(index); } + // optional bytes bytesValue = 13; + public static final int BYTESVALUE_FIELD_NUMBER = 13; + private com.google.protobuf.ByteString bytesValue_; + /** + * optional bytes bytesValue = 13; + */ + public boolean hasBytesValue() { + return ((bitField0_ & 0x00000100) == 0x00000100); + } + /** + * optional bytes bytesValue = 13; + */ + public com.google.protobuf.ByteString getBytesValue() { + return bytesValue_; + } + private void initFields() { path_ = ""; type_ = ""; @@ -6083,6 +6727,7 @@ public final class NormalizedNodeMessages { instanceIdentifierValue_ = org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.getDefaultInstance(); bitsValue_ = com.google.protobuf.LazyStringArrayList.EMPTY; code_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bytesValue_ = com.google.protobuf.ByteString.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { @@ -6156,6 +6801,9 @@ public final class NormalizedNodeMessages { for (int i = 0; i < code_.size(); i++) { output.writeBytes(12, code_.getByteString(i)); } + if (((bitField0_ & 0x00000100) == 0x00000100)) { + output.writeBytes(13, bytesValue_); + } getUnknownFields().writeTo(output); } @@ -6223,6 +6871,10 @@ public final class NormalizedNodeMessages { size += dataSize; size += 1 * getCodeList().size(); } + if (((bitField0_ & 0x00000100) == 0x00000100)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(13, bytesValue_); + } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; @@ -6383,6 +7035,8 @@ public final class NormalizedNodeMessages { bitField0_ = (bitField0_ & ~0x00000400); code_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000800); + bytesValue_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00001000); return this; } @@ -6481,6 +7135,10 @@ public final class NormalizedNodeMessages { bitField0_ = (bitField0_ & ~0x00000800); } result.code_ = code_; + if (((from_bitField0_ & 0x00001000) == 0x00001000)) { + to_bitField0_ |= 0x00000100; + } + result.bytesValue_ = bytesValue_; result.bitField0_ = to_bitField0_; onBuilt(); return result; @@ -6601,6 +7259,9 @@ public final class NormalizedNodeMessages { } onChanged(); } + if (other.hasBytesValue()) { + setBytesValue(other.getBytesValue()); + } this.mergeUnknownFields(other.getUnknownFields()); return this; } @@ -8110,6 +8771,42 @@ public final class NormalizedNodeMessages { return this; } + // optional bytes bytesValue = 13; + private com.google.protobuf.ByteString bytesValue_ = com.google.protobuf.ByteString.EMPTY; + /** + * optional bytes bytesValue = 13; + */ + public boolean hasBytesValue() { + return ((bitField0_ & 0x00001000) == 0x00001000); + } + /** + * optional bytes bytesValue = 13; + */ + public com.google.protobuf.ByteString getBytesValue() { + return bytesValue_; + } + /** + * optional bytes bytesValue = 13; + */ + public Builder setBytesValue(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00001000; + bytesValue_ = value; + onChanged(); + return this; + } + /** + * optional bytes bytesValue = 13; + */ + public Builder clearBytesValue() { + bitField0_ = (bitField0_ & ~0x00001000); + bytesValue_ = getDefaultInstance().getBytesValue(); + onChanged(); + return this; + } + // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.Node) } @@ -10273,42 +10970,46 @@ public final class NormalizedNodeMessages { java.lang.String[] descriptorData = { "\n\014Common.proto\022!org.opendaylight.control" + "ler.mdsal\"6\n\tAttribute\022\014\n\004name\030\001 \002(\t\022\r\n\005" + - "value\030\002 \001(\t\022\014\n\004type\030\003 \001(\t\"l\n\025PathArgumen" + - "tAttribute\0226\n\004name\030\001 \001(\0132(.org.opendayli" + - "ght.controller.mdsal.QName\022\r\n\005value\030\002 \001(" + - "\t\022\014\n\004type\030\003 \001(\005\"N\n\005QName\022\r\n\005value\030\001 \001(\t\022" + - "\021\n\tnamespace\030\002 \001(\005\022\020\n\010revision\030\003 \001(\005\022\021\n\t" + - "localName\030\004 \001(\005\"\207\002\n\014PathArgument\022\r\n\005valu" + - "e\030\001 \001(\t\022\014\n\004type\030\002 \001(\t\022:\n\010nodeType\030\003 \001(\0132" + - "(.org.opendaylight.controller.mdsal.QNam", - "e\022K\n\tattribute\030\004 \003(\01328.org.opendaylight." + - "controller.mdsal.PathArgumentAttribute\022@" + + "value\030\002 \001(\t\022\014\n\004type\030\003 \001(\t\"\353\001\n\025PathArgume" + + "ntAttribute\0226\n\004name\030\001 \001(\0132(.org.opendayl" + + "ight.controller.mdsal.QName\022\r\n\005value\030\002 \001" + + "(\t\022\014\n\004type\030\003 \001(\005\022V\n\027instanceIdentifierVa" + + "lue\030\004 \001(\01325.org.opendaylight.controller." + + "mdsal.InstanceIdentifier\022\021\n\tbitsValue\030\005 " + + "\003(\t\022\022\n\nbytesValue\030\006 \001(\014\"N\n\005QName\022\r\n\005valu" + + "e\030\001 \001(\t\022\021\n\tnamespace\030\002 \001(\005\022\020\n\010revision\030\003", + " \001(\005\022\021\n\tlocalName\030\004 \001(\005\"\207\002\n\014PathArgument" + + "\022\r\n\005value\030\001 \001(\t\022\014\n\004type\030\002 \001(\t\022:\n\010nodeTyp" + + "e\030\003 \001(\0132(.org.opendaylight.controller.md" + + "sal.QName\022K\n\tattribute\030\004 \003(\01328.org.opend" + + "aylight.controller.mdsal.PathArgumentAtt" + + "ribute\022@\n\nattributes\030\005 \003(\0132,.org.openday" + + "light.controller.mdsal.Attribute\022\017\n\007intT" + + "ype\030\006 \001(\005\"f\n\022InstanceIdentifier\022B\n\targum" + + "ents\030\001 \003(\0132/.org.opendaylight.controller" + + ".mdsal.PathArgument\022\014\n\004code\030\002 \003(\t\"\271\003\n\004No", + "de\022\014\n\004path\030\001 \001(\t\022\014\n\004type\030\002 \001(\t\022E\n\014pathAr" + + "gument\030\003 \001(\0132/.org.opendaylight.controll" + + "er.mdsal.PathArgument\022\017\n\007intType\030\004 \001(\005\022@" + "\n\nattributes\030\005 \003(\0132,.org.opendaylight.co" + - "ntroller.mdsal.Attribute\022\017\n\007intType\030\006 \001(" + - "\005\"f\n\022InstanceIdentifier\022B\n\targuments\030\001 \003" + - "(\0132/.org.opendaylight.controller.mdsal.P" + - "athArgument\022\014\n\004code\030\002 \003(\t\"\245\003\n\004Node\022\014\n\004pa" + - "th\030\001 \001(\t\022\014\n\004type\030\002 \001(\t\022E\n\014pathArgument\030\003" + - " \001(\0132/.org.opendaylight.controller.mdsal" + - ".PathArgument\022\017\n\007intType\030\004 \001(\005\022@\n\nattrib", - "utes\030\005 \003(\0132,.org.opendaylight.controller" + - ".mdsal.Attribute\0226\n\005child\030\006 \003(\0132\'.org.op" + - "endaylight.controller.mdsal.Node\022\r\n\005valu" + - "e\030\007 \001(\t\022\021\n\tvalueType\030\010 \001(\t\022\024\n\014intValueTy" + - "pe\030\t \001(\005\022V\n\027instanceIdentifierValue\030\n \001(" + - "\01325.org.opendaylight.controller.mdsal.In" + - "stanceIdentifier\022\021\n\tbitsValue\030\013 \003(\t\022\014\n\004c" + - "ode\030\014 \003(\t\"`\n\tContainer\022\022\n\nparentPath\030\001 \002" + - "(\t\022?\n\016normalizedNode\030\002 \001(\0132\'.org.openday" + - "light.controller.mdsal.Node\"\246\001\n\014NodeMapE", - "ntry\022U\n\026instanceIdentifierPath\030\001 \002(\01325.o" + - "rg.opendaylight.controller.mdsal.Instanc" + - "eIdentifier\022?\n\016normalizedNode\030\002 \001(\0132\'.or" + - "g.opendaylight.controller.mdsal.Node\"N\n\007" + - "NodeMap\022C\n\nmapEntries\030\001 \003(\0132/.org.openda" + - "ylight.controller.mdsal.NodeMapEntryBO\n5" + - "org.opendaylight.controller.protobuff.me" + - "ssages.commonB\026NormalizedNodeMessages" + "ntroller.mdsal.Attribute\0226\n\005child\030\006 \003(\0132" + + "\'.org.opendaylight.controller.mdsal.Node" + + "\022\r\n\005value\030\007 \001(\t\022\021\n\tvalueType\030\010 \001(\t\022\024\n\014in" + + "tValueType\030\t \001(\005\022V\n\027instanceIdentifierVa" + + "lue\030\n \001(\01325.org.opendaylight.controller." + + "mdsal.InstanceIdentifier\022\021\n\tbitsValue\030\013 ", + "\003(\t\022\014\n\004code\030\014 \003(\t\022\022\n\nbytesValue\030\r \001(\014\"`\n" + + "\tContainer\022\022\n\nparentPath\030\001 \002(\t\022?\n\016normal" + + "izedNode\030\002 \001(\0132\'.org.opendaylight.contro" + + "ller.mdsal.Node\"\246\001\n\014NodeMapEntry\022U\n\026inst" + + "anceIdentifierPath\030\001 \002(\01325.org.opendayli" + + "ght.controller.mdsal.InstanceIdentifier\022" + + "?\n\016normalizedNode\030\002 \001(\0132\'.org.opendaylig" + + "ht.controller.mdsal.Node\"N\n\007NodeMap\022C\n\nm" + + "apEntries\030\001 \003(\0132/.org.opendaylight.contr" + + "oller.mdsal.NodeMapEntryBO\n5org.opendayl", + "ight.controller.protobuff.messages.commo" + + "nB\026NormalizedNodeMessages" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { @@ -10326,7 +11027,7 @@ public final class NormalizedNodeMessages { internal_static_org_opendaylight_controller_mdsal_PathArgumentAttribute_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_opendaylight_controller_mdsal_PathArgumentAttribute_descriptor, - new java.lang.String[] { "Name", "Value", "Type", }); + new java.lang.String[] { "Name", "Value", "Type", "InstanceIdentifierValue", "BitsValue", "BytesValue", }); internal_static_org_opendaylight_controller_mdsal_QName_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_org_opendaylight_controller_mdsal_QName_fieldAccessorTable = new @@ -10350,7 +11051,7 @@ public final class NormalizedNodeMessages { internal_static_org_opendaylight_controller_mdsal_Node_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_opendaylight_controller_mdsal_Node_descriptor, - new java.lang.String[] { "Path", "Type", "PathArgument", "IntType", "Attributes", "Child", "Value", "ValueType", "IntValueType", "InstanceIdentifierValue", "BitsValue", "Code", }); + new java.lang.String[] { "Path", "Type", "PathArgument", "IntType", "Attributes", "Child", "Value", "ValueType", "IntValueType", "InstanceIdentifierValue", "BitsValue", "Code", "BytesValue", }); internal_static_org_opendaylight_controller_mdsal_Container_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_org_opendaylight_controller_mdsal_Container_fieldAccessorTable = new diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java index 96a39bddd3..3a1cfaa443 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java @@ -668,6 +668,16 @@ public final class ShardTransactionMessages { */ com.google.protobuf.ByteString getTransactionChainIdBytes(); + + // optional int32 messageVersion = 4; + /** + * optional int32 messageVersion = 4; + */ + boolean hasMessageVersion(); + /** + * optional int32 messageVersion = 4; + */ + int getMessageVersion(); } /** * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransaction} @@ -735,6 +745,11 @@ public final class ShardTransactionMessages { transactionChainId_ = input.readBytes(); break; } + case 32: { + bitField0_ |= 0x00000008; + messageVersion_ = input.readInt32(); + break; + } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { @@ -877,10 +892,27 @@ public final class ShardTransactionMessages { } } + // optional int32 messageVersion = 4; + public static final int MESSAGEVERSION_FIELD_NUMBER = 4; + private int messageVersion_; + /** + * optional int32 messageVersion = 4; + */ + public boolean hasMessageVersion() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * optional int32 messageVersion = 4; + */ + public int getMessageVersion() { + return messageVersion_; + } + private void initFields() { transactionId_ = ""; transactionType_ = 0; transactionChainId_ = ""; + messageVersion_ = 0; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { @@ -911,6 +943,9 @@ public final class ShardTransactionMessages { if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getTransactionChainIdBytes()); } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeInt32(4, messageVersion_); + } getUnknownFields().writeTo(output); } @@ -932,6 +967,10 @@ public final class ShardTransactionMessages { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getTransactionChainIdBytes()); } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(4, messageVersion_); + } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; @@ -1054,6 +1093,8 @@ public final class ShardTransactionMessages { bitField0_ = (bitField0_ & ~0x00000002); transactionChainId_ = ""; bitField0_ = (bitField0_ & ~0x00000004); + messageVersion_ = 0; + bitField0_ = (bitField0_ & ~0x00000008); return this; } @@ -1094,6 +1135,10 @@ public final class ShardTransactionMessages { to_bitField0_ |= 0x00000004; } result.transactionChainId_ = transactionChainId_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.messageVersion_ = messageVersion_; result.bitField0_ = to_bitField0_; onBuilt(); return result; @@ -1123,6 +1168,9 @@ public final class ShardTransactionMessages { transactionChainId_ = other.transactionChainId_; onChanged(); } + if (other.hasMessageVersion()) { + setMessageVersion(other.getMessageVersion()); + } this.mergeUnknownFields(other.getUnknownFields()); return this; } @@ -1339,6 +1387,39 @@ public final class ShardTransactionMessages { return this; } + // optional int32 messageVersion = 4; + private int messageVersion_ ; + /** + * optional int32 messageVersion = 4; + */ + public boolean hasMessageVersion() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * optional int32 messageVersion = 4; + */ + public int getMessageVersion() { + return messageVersion_; + } + /** + * optional int32 messageVersion = 4; + */ + public Builder setMessageVersion(int value) { + bitField0_ |= 0x00000008; + messageVersion_ = value; + onChanged(); + return this; + } + /** + * optional int32 messageVersion = 4; + */ + public Builder clearMessageVersion() { + bitField0_ = (bitField0_ & ~0x00000008); + messageVersion_ = 0; + onChanged(); + return this; + } + // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CreateTransaction) } @@ -1382,6 +1463,16 @@ public final class ShardTransactionMessages { */ com.google.protobuf.ByteString getTransactionIdBytes(); + + // optional int32 messageVersion = 3; + /** + * optional int32 messageVersion = 3; + */ + boolean hasMessageVersion(); + /** + * optional int32 messageVersion = 3; + */ + int getMessageVersion(); } /** * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransactionReply} @@ -1444,6 +1535,11 @@ public final class ShardTransactionMessages { transactionId_ = input.readBytes(); break; } + case 24: { + bitField0_ |= 0x00000004; + messageVersion_ = input.readInt32(); + break; + } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { @@ -1570,9 +1666,26 @@ public final class ShardTransactionMessages { } } + // optional int32 messageVersion = 3; + public static final int MESSAGEVERSION_FIELD_NUMBER = 3; + private int messageVersion_; + /** + * optional int32 messageVersion = 3; + */ + public boolean hasMessageVersion() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * optional int32 messageVersion = 3; + */ + public int getMessageVersion() { + return messageVersion_; + } + private void initFields() { transactionActorPath_ = ""; transactionId_ = ""; + messageVersion_ = 0; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { @@ -1600,6 +1713,9 @@ public final class ShardTransactionMessages { if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getTransactionIdBytes()); } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeInt32(3, messageVersion_); + } getUnknownFields().writeTo(output); } @@ -1617,6 +1733,10 @@ public final class ShardTransactionMessages { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getTransactionIdBytes()); } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(3, messageVersion_); + } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; @@ -1737,6 +1857,8 @@ public final class ShardTransactionMessages { bitField0_ = (bitField0_ & ~0x00000001); transactionId_ = ""; bitField0_ = (bitField0_ & ~0x00000002); + messageVersion_ = 0; + bitField0_ = (bitField0_ & ~0x00000004); return this; } @@ -1773,6 +1895,10 @@ public final class ShardTransactionMessages { to_bitField0_ |= 0x00000002; } result.transactionId_ = transactionId_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.messageVersion_ = messageVersion_; result.bitField0_ = to_bitField0_; onBuilt(); return result; @@ -1799,6 +1925,9 @@ public final class ShardTransactionMessages { transactionId_ = other.transactionId_; onChanged(); } + if (other.hasMessageVersion()) { + setMessageVersion(other.getMessageVersion()); + } this.mergeUnknownFields(other.getUnknownFields()); return this; } @@ -1982,6 +2111,39 @@ public final class ShardTransactionMessages { return this; } + // optional int32 messageVersion = 3; + private int messageVersion_ ; + /** + * optional int32 messageVersion = 3; + */ + public boolean hasMessageVersion() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * optional int32 messageVersion = 3; + */ + public int getMessageVersion() { + return messageVersion_; + } + /** + * optional int32 messageVersion = 3; + */ + public Builder setMessageVersion(int value) { + bitField0_ |= 0x00000004; + messageVersion_ = value; + onChanged(); + return this; + } + /** + * optional int32 messageVersion = 3; + */ + public Builder clearMessageVersion() { + bitField0_ = (bitField0_ & ~0x00000004); + messageVersion_ = 0; + onChanged(); + return this; + } + // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CreateTransactionReply) } @@ -7753,37 +7915,38 @@ public final class ShardTransactionMessages { java.lang.String[] descriptorData = { "\n\026ShardTransaction.proto\022!org.opendaylig" + "ht.controller.mdsal\032\014Common.proto\"\022\n\020Clo" + - "seTransaction\"\027\n\025CloseTransactionReply\"_" + + "seTransaction\"\027\n\025CloseTransactionReply\"w" + "\n\021CreateTransaction\022\025\n\rtransactionId\030\001 \002" + "(\t\022\027\n\017transactionType\030\002 \002(\005\022\032\n\022transacti" + - "onChainId\030\003 \001(\t\"M\n\026CreateTransactionRepl" + - "y\022\034\n\024transactionActorPath\030\001 \002(\t\022\025\n\rtrans" + - "actionId\030\002 \002(\t\"\022\n\020ReadyTransaction\"*\n\025Re" + - "adyTransactionReply\022\021\n\tactorPath\030\001 \002(\t\"l" + - "\n\nDeleteData\022^\n\037instanceIdentifierPathAr", + "onChainId\030\003 \001(\t\022\026\n\016messageVersion\030\004 \001(\005\"" + + "e\n\026CreateTransactionReply\022\034\n\024transaction" + + "ActorPath\030\001 \002(\t\022\025\n\rtransactionId\030\002 \002(\t\022\026" + + "\n\016messageVersion\030\003 \001(\005\"\022\n\020ReadyTransacti" + + "on\"*\n\025ReadyTransactionReply\022\021\n\tactorPath", + "\030\001 \002(\t\"l\n\nDeleteData\022^\n\037instanceIdentifi" + + "erPathArguments\030\001 \002(\01325.org.opendaylight" + + ".controller.mdsal.InstanceIdentifier\"\021\n\017" + + "DeleteDataReply\"j\n\010ReadData\022^\n\037instanceI" + + "dentifierPathArguments\030\001 \002(\01325.org.opend" + + "aylight.controller.mdsal.InstanceIdentif" + + "ier\"P\n\rReadDataReply\022?\n\016normalizedNode\030\001" + + " \001(\0132\'.org.opendaylight.controller.mdsal" + + ".Node\"\254\001\n\tWriteData\022^\n\037instanceIdentifie" + + "rPathArguments\030\001 \002(\01325.org.opendaylight.", + "controller.mdsal.InstanceIdentifier\022?\n\016n" + + "ormalizedNode\030\002 \002(\0132\'.org.opendaylight.c" + + "ontroller.mdsal.Node\"\020\n\016WriteDataReply\"\254" + + "\001\n\tMergeData\022^\n\037instanceIdentifierPathAr" + "guments\030\001 \002(\01325.org.opendaylight.control" + - "ler.mdsal.InstanceIdentifier\"\021\n\017DeleteDa" + - "taReply\"j\n\010ReadData\022^\n\037instanceIdentifie" + - "rPathArguments\030\001 \002(\01325.org.opendaylight." + - "controller.mdsal.InstanceIdentifier\"P\n\rR" + - "eadDataReply\022?\n\016normalizedNode\030\001 \001(\0132\'.o" + - "rg.opendaylight.controller.mdsal.Node\"\254\001" + - "\n\tWriteData\022^\n\037instanceIdentifierPathArg" + - "uments\030\001 \002(\01325.org.opendaylight.controll" + - "er.mdsal.InstanceIdentifier\022?\n\016normalize", - "dNode\030\002 \002(\0132\'.org.opendaylight.controlle" + - "r.mdsal.Node\"\020\n\016WriteDataReply\"\254\001\n\tMerge" + - "Data\022^\n\037instanceIdentifierPathArguments\030" + - "\001 \002(\01325.org.opendaylight.controller.mdsa" + - "l.InstanceIdentifier\022?\n\016normalizedNode\030\002" + - " \002(\0132\'.org.opendaylight.controller.mdsal" + - ".Node\"\020\n\016MergeDataReply\"l\n\nDataExists\022^\n" + - "\037instanceIdentifierPathArguments\030\001 \002(\01325" + - ".org.opendaylight.controller.mdsal.Insta" + - "nceIdentifier\"!\n\017DataExistsReply\022\016\n\006exis", - "ts\030\001 \002(\010BV\n:org.opendaylight.controller." + - "protobuff.messages.transactionB\030ShardTra" + - "nsactionMessages" + "ler.mdsal.InstanceIdentifier\022?\n\016normaliz" + + "edNode\030\002 \002(\0132\'.org.opendaylight.controll" + + "er.mdsal.Node\"\020\n\016MergeDataReply\"l\n\nDataE" + + "xists\022^\n\037instanceIdentifierPathArguments" + + "\030\001 \002(\01325.org.opendaylight.controller.mds", + "al.InstanceIdentifier\"!\n\017DataExistsReply" + + "\022\016\n\006exists\030\001 \002(\010BV\n:org.opendaylight.con" + + "troller.protobuff.messages.transactionB\030" + + "ShardTransactionMessages" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { @@ -7807,13 +7970,13 @@ public final class ShardTransactionMessages { internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor, - new java.lang.String[] { "TransactionId", "TransactionType", "TransactionChainId", }); + new java.lang.String[] { "TransactionId", "TransactionType", "TransactionChainId", "MessageVersion", }); internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor, - new java.lang.String[] { "TransactionActorPath", "TransactionId", }); + new java.lang.String[] { "TransactionActorPath", "TransactionId", "MessageVersion", }); internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable = new diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/resources/Cohort.proto b/opendaylight/md-sal/sal-clustering-commons/src/main/resources/Cohort.proto index 49c6cd07a8..222f68ab4f 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/resources/Cohort.proto +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/resources/Cohort.proto @@ -5,7 +5,7 @@ option java_outer_classname = "ThreePhaseCommitCohortMessages"; message CanCommitTransaction{ - required string transactionId = 1; + optional string transactionId = 1; } message CanCommitTransactionReply{ @@ -14,7 +14,7 @@ message CanCommitTransactionReply{ } message AbortTransaction{ - required string transactionId = 1; + optional string transactionId = 1; } message AbortTransactionReply { @@ -22,7 +22,7 @@ message AbortTransactionReply { } message CommitTransaction{ - required string transactionId = 1; + optional string transactionId = 1; } message CommitTransactionReply{ diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/resources/Common.proto b/opendaylight/md-sal/sal-clustering-commons/src/main/resources/Common.proto index 356bfbf684..a2c161cfda 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/resources/Common.proto +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/resources/Common.proto @@ -14,6 +14,11 @@ message PathArgumentAttribute{ optional QName name =1; optional string value=2; optional int32 type=3; + // Specific values + optional InstanceIdentifier instanceIdentifierValue = 4; // intValueType = YangInstanceIdentifier + repeated string bitsValue = 5; // intValueType = Bits + optional bytes bytesValue = 6; + } @@ -63,6 +68,8 @@ message Node{ repeated string bitsValue = 11; // intValueType = Bits repeated string code = 12; // A list of string codes which can be used for any repeated strings in the NormalizedNode + + optional bytes bytesValue = 13; } message Container{ diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/resources/ShardTransaction.proto b/opendaylight/md-sal/sal-clustering-commons/src/main/resources/ShardTransaction.proto index 26581478d9..c5e4ee45c0 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/resources/ShardTransaction.proto +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/resources/ShardTransaction.proto @@ -16,12 +16,13 @@ message CreateTransaction{ required string transactionId = 1; required int32 transactionType =2; optional string transactionChainId = 3; + optional int32 messageVersion = 4; } message CreateTransactionReply{ -required string transactionActorPath = 1; -required string transactionId = 2; - + required string transactionActorPath = 1; + required string transactionId = 2; + optional int32 messageVersion = 3; } message ReadyTransaction{ @@ -29,7 +30,7 @@ message ReadyTransaction{ } message ReadyTransactionReply{ -required string actorPath = 1; + required string actorPath = 1; } message DeleteData { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailboxTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailboxTest.java index d33e79f533..60efb9d7ca 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailboxTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailboxTest.java @@ -81,6 +81,7 @@ public class MeteredBoundedMailboxTest { public static Props props(final ReentrantLock lock){ return Props.create(new Creator(){ + private static final long serialVersionUID = 1L; @Override public PingPongActor create() throws Exception { return new PingPongActor(lock); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java index 6de1083cbe..0b408e2e1e 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java @@ -26,8 +26,8 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import java.util.List; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class NormalizedNodeToNodeCodecTest { @@ -60,7 +60,7 @@ public class NormalizedNodeToNodeCodecTest { PathUtils.toString(YangInstanceIdentifier.builder().build()), documentOne); // Validate the value of id can be retrieved from the normalized node - NormalizedNode output = normalizedNodeGetter.getOutput(); + NormalizedNode output = normalizedNodeGetter.getOutput(); assertNotNull(output); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java index 4da7d8c483..13dfff3a8a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java @@ -10,7 +10,7 @@ package org.opendaylight.controller.cluster.datastore.node.utils; -import junit.framework.Assert; +import static org.junit.Assert.assertTrue; import org.junit.Test; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; @@ -22,8 +22,7 @@ public class NodeIdentifierFactoryTest { NodeIdentifierFactory .getArgument("AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}"); - Assert - .assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier); + assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtilsTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtilsTest.java index d1e3eb202f..75e8e2aa4a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtilsTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtilsTest.java @@ -1,15 +1,13 @@ package org.opendaylight.controller.cluster.datastore.node.utils; +import com.google.common.collect.ImmutableSet; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.util.TestModel; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; - import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; - import static junit.framework.TestCase.assertEquals; public class PathUtilsTest { @@ -92,8 +90,7 @@ public class PathUtilsTest { } private YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier(){ - Set childNames = new HashSet(); - childNames.add(QNameFactory.create("(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics")); + Set childNames = ImmutableSet.of(QNameFactory.create("(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics")); return new YangInstanceIdentifier.AugmentationIdentifier(childNames); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactoryTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactoryTest.java index 76d4ceb2f5..2ae83bd6c6 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactoryTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactoryTest.java @@ -4,9 +4,9 @@ import org.junit.Test; import org.opendaylight.controller.cluster.datastore.util.TestModel; import org.opendaylight.yangtools.yang.common.QName; -import static junit.framework.Assert.assertTrue; -import static junit.framework.TestCase.assertEquals; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class QNameFactoryTest { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializerTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializerTest.java index cdb2e69e83..816442f885 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializerTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializerTest.java @@ -1,15 +1,20 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; +import com.google.common.base.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.opendaylight.controller.cluster.datastore.util.TestModel; import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; +import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class NormalizedNodeSerializerTest { @@ -40,7 +45,7 @@ public class NormalizedNodeSerializerTest { start = System.nanoTime(); - NormalizedNode actualNode = + NormalizedNode actualNode = NormalizedNodeSerializer.deSerialize(expected); System.out.println("DeSerialize Time = " + (System.nanoTime() - start)/1000000); @@ -49,6 +54,37 @@ public class NormalizedNodeSerializerTest { // created by serializing the original node and deSerializing it back. assertEquals(expectedNode, actualNode); + byte[] binaryData = new byte[5]; + for(byte i=0;i<5;i++){ + binaryData[i] = i; + } + + ContainerNode node1 = TestModel.createBaseTestContainerBuilder() + .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATE_QNAME, binaryData)) + .build(); + + NormalizedNodeMessages.Node serializedNode1 = NormalizedNodeSerializer + .serialize(node1); + + ContainerNode node2 = + (ContainerNode) NormalizedNodeSerializer.deSerialize(serializedNode1); + + + // FIXME: This will not work due to BUG 2326. Once that is fixed we can uncomment this assertion + // assertEquals(node1, node2); + + Optional> child = node2.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.SOME_BINARY_DATE_QNAME)); + + Object value = child.get().getValue(); + + assertTrue("value should be of type byte[]", value instanceof byte[]); + + byte[] bytesValue = (byte[]) value; + + for(byte i=0;i<5;i++){ + assertEquals(i, bytesValue[i]); + } + } @Test(expected = NullPointerException.class) diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializerTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializerTest.java index 88c2695075..d9b7a18fda 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializerTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializerTest.java @@ -1,7 +1,15 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; +import com.google.protobuf.ByteString; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -10,12 +18,6 @@ import org.opendaylight.controller.cluster.datastore.util.TestModel; import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; public class ValueSerializerTest{ @@ -118,7 +120,8 @@ public class ValueSerializerTest{ ImmutableSet.of("foo", "bar")); assertEquals(ValueType.BITS_TYPE.ordinal(), builder1.getType()); - assertEquals("[foo, bar]", builder1.getValue()); + assertTrue( "foo not in bits", builder1.getBitsValueList().contains("foo")); + assertTrue( "bar not in bits", builder1.getBitsValueList().contains("bar")); } @@ -218,6 +221,21 @@ public class ValueSerializerTest{ assertEquals(1, serializedYangInstanceIdentifier.getArgumentsCount()); Mockito.verify(mockContext).addLocalName(TestModel.TEST_QNAME.getLocalName()); Mockito.verify(mockContext).addNamespace(TestModel.TEST_QNAME.getNamespace()); + + NormalizedNodeMessages.PathArgumentAttribute.Builder argumentBuilder + = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + + mockContext = mock(QNameSerializationContext.class); + + ValueSerializer.serialize(argumentBuilder, mockContext, v1); + + serializedYangInstanceIdentifier = + argumentBuilder.getInstanceIdentifierValue(); + + assertEquals(1, serializedYangInstanceIdentifier.getArgumentsCount()); + Mockito.verify(mockContext).addLocalName(TestModel.TEST_QNAME.getLocalName()); + Mockito.verify(mockContext).addNamespace(TestModel.TEST_QNAME.getNamespace()); + } @Test @@ -255,6 +273,25 @@ public class ValueSerializerTest{ } + @Test + public void testSerializeBinary(){ + NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); + byte[] bytes = new byte[] {1,2,3,4}; + ValueSerializer.serialize(builder, mock(QNameSerializationContext.class),bytes); + + assertEquals(ValueType.BINARY_TYPE.ordinal(), builder.getIntValueType()); + assertEquals(ByteString.copyFrom(bytes), builder.getBytesValue()); + + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + + ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class),bytes); + + assertEquals(ValueType.BINARY_TYPE.ordinal(), builder1.getType()); + assertEquals(ByteString.copyFrom(bytes), builder1.getBytesValue()); + + } + + @Test public void testDeSerializeShort(){ NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); @@ -355,8 +392,22 @@ public class ValueSerializerTest{ nodeBuilder.build()); assertTrue(o instanceof Set); - assertTrue(((Set)o).contains("foo")); - assertTrue(((Set) o).contains("bar")); + assertTrue(((Set)o).contains("foo")); + assertTrue(((Set) o).contains("bar")); + + NormalizedNodeMessages.PathArgumentAttribute.Builder argumentBuilder + = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + + argumentBuilder.setType(ValueType.BITS_TYPE.ordinal()); + argumentBuilder.addAllBitsValue(ImmutableList.of("foo", "bar")); + + o = ValueSerializer + .deSerialize(mock(QNameDeSerializationContext.class), + argumentBuilder.build()); + + assertTrue(o instanceof Set); + assertTrue(((Set)o).contains("foo")); + assertTrue(((Set) o).contains("bar")); } @@ -386,6 +437,16 @@ public class ValueSerializerTest{ assertTrue(o instanceof YangInstanceIdentifier); assertEquals(TestModel.TEST_PATH, o); + NormalizedNodeMessages.PathArgumentAttribute.Builder argumentBuilder = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + + argumentBuilder.setType(ValueType.YANG_IDENTIFIER_TYPE.ordinal()); + argumentBuilder.setInstanceIdentifierValue(idBuilder); + + o = ValueSerializer.deSerialize(mockContext, argumentBuilder.build()); + + assertTrue(o instanceof YangInstanceIdentifier); + assertEquals(TestModel.TEST_PATH, o); } @Test @@ -432,4 +493,31 @@ public class ValueSerializerTest{ } + + @Test + public void testDeSerializeBinaryType(){ + NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); + nodeBuilder.setIntValueType(ValueType.BINARY_TYPE.ordinal()); + byte[] bytes = new byte[] {1,2,3,4}; + nodeBuilder.setBytesValue(ByteString.copyFrom(bytes)); + + Object o = ValueSerializer.deSerialize(mock(QNameDeSerializationContext.class),nodeBuilder.build()); + + assertTrue("not a byte array", o instanceof byte[]); + assertTrue("bytes value does not match" , Arrays.equals(bytes, (byte[]) o)); + + NormalizedNodeMessages.PathArgumentAttribute.Builder argumentBuilder = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + argumentBuilder.setType(ValueType.BINARY_TYPE.ordinal()); + argumentBuilder.setBytesValue(ByteString.copyFrom(bytes)); + + o = ValueSerializer.deSerialize(mock(QNameDeSerializationContext.class), argumentBuilder.build()); + + assertTrue("not a byte array", o instanceof byte[]); + assertTrue("bytes value does not match" ,Arrays.equals(bytes, (byte[]) o)); + + + } + + } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueTypeTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueTypeTest.java new file mode 100644 index 0000000000..8fe0633b6e --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueTypeTest.java @@ -0,0 +1,18 @@ +package org.opendaylight.controller.cluster.datastore.node.utils.serialization; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ValueTypeTest { + + @Test + public void testGetSerializableType(){ + byte[] b = new byte[10]; + b[0] = 1; + b[2] = 2; + + ValueType serializableType = ValueType.getSerializableType(b); + assertEquals(ValueType.BINARY_TYPE, serializableType); + } +} \ No newline at end of file diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReaderWriterTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReaderWriterTest.java new file mode 100644 index 0000000000..ae548dba23 --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReaderWriterTest.java @@ -0,0 +1,62 @@ +/* + * + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + */ + +package org.opendaylight.controller.cluster.datastore.node.utils.stream; + + +import org.apache.commons.lang.SerializationUtils; +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.cluster.datastore.util.TestModel; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter; +import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class NormalizedNodeStreamReaderWriterTest { + + final NormalizedNode input = TestModel.createTestContainer(); + + @Test + public void testNormalizedNodeStreamReaderWriter() throws IOException { + + byte[] byteData = null; + + try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + NormalizedNodeStreamWriter writer = new NormalizedNodeOutputStreamWriter(byteArrayOutputStream)) { + + NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(writer); + normalizedNodeWriter.write(input); + byteData = byteArrayOutputStream.toByteArray(); + + } + + try(NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( + new ByteArrayInputStream(byteData))) { + + NormalizedNode node = reader.readNormalizedNode(); + Assert.assertEquals(input, node); + + } + } + + @Test + public void testWithSerializable() { + SampleNormalizedNodeSerializable serializable = new SampleNormalizedNodeSerializable(input); + SampleNormalizedNodeSerializable clone = (SampleNormalizedNodeSerializable)SerializationUtils.clone(serializable); + + Assert.assertEquals(input, clone.getInput()); + + } + +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/SampleNormalizedNodeSerializable.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/SampleNormalizedNodeSerializable.java new file mode 100644 index 0000000000..10a2ad90a5 --- /dev/null +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/SampleNormalizedNodeSerializable.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.datastore.node.utils.stream; + + +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter; +import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.net.URISyntaxException; + +public class SampleNormalizedNodeSerializable implements Serializable { + private static final long serialVersionUID = 1L; + + private NormalizedNode input; + + public SampleNormalizedNodeSerializable(NormalizedNode input) { + this.input = input; + } + + public NormalizedNode getInput() { + return input; + } + + private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException, URISyntaxException { + NormalizedNodeStreamReader reader = new NormalizedNodeInputStreamReader(stream); + this.input = reader.readNormalizedNode(); + } + + private void writeObject(final ObjectOutputStream stream) throws IOException { + NormalizedNodeStreamWriter writer = new NormalizedNodeOutputStreamWriter(stream); + NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(writer); + + normalizedNodeWriter.write(this.input); + } + +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java index 6cd06e9c1c..d15f534f80 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java @@ -10,6 +10,7 @@ package org.opendaylight.controller.cluster.datastore.util; +import com.google.common.collect.ImmutableSet; import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.node.utils.serialization.QNameDeSerializationContext; @@ -20,7 +21,6 @@ import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.List; public class InstanceIdentifierUtilsTest { @@ -116,8 +116,8 @@ public class InstanceIdentifierUtilsTest { @Test public void testAugmentationIdentifier() { - YangInstanceIdentifier.PathArgument p1 = new YangInstanceIdentifier.AugmentationIdentifier(new HashSet( - Arrays.asList(TEST_QNAME))); + YangInstanceIdentifier.PathArgument p1 = new YangInstanceIdentifier.AugmentationIdentifier( + ImmutableSet.of(TEST_QNAME)); List arguments = new ArrayList<>(); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java index cda4b06e29..99df01a32e 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java @@ -62,6 +62,7 @@ public class TestModel { public static final QName DESC_QNAME = QName.create(TEST_QNAME, "desc"); public static final QName POINTER_QNAME = QName.create(TEST_QNAME, "pointer"); + public static final QName SOME_BINARY_DATE_QNAME = QName.create(TEST_QNAME, "some-binary-data"); public static final QName SOME_REF_QNAME = QName.create(TEST_QNAME, "some-ref"); public static final QName MYIDENTITY_QNAME = QName.create(TEST_QNAME, @@ -282,114 +283,115 @@ public class TestModel { } - public static ContainerNode createTestContainer() { - - - // Create a list of shoes - // This is to test leaf list entry - final LeafSetEntryNode nike = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue(QName.create( - TEST_QNAME, "shoe"), "nike")).withValue("nike").build(); - - final LeafSetEntryNode puma = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue(QName.create( - TEST_QNAME, "shoe"), "puma")).withValue("puma").build(); - - final LeafSetNode shoes = - ImmutableLeafSetNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(QName.create( - TEST_QNAME, "shoe"))).withChild(nike).withChild(puma) - .build(); - - - // Test a leaf-list where each entry contains an identity - final LeafSetEntryNode cap1 = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue(QName.create( - TEST_QNAME, "capability"), DESC_QNAME)) - .withValue(DESC_QNAME).build(); - - final LeafSetNode capabilities = - ImmutableLeafSetNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(QName.create( - TEST_QNAME, "capability"))).withChild(cap1).build(); - - ContainerNode switchFeatures = - ImmutableContainerNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(SWITCH_FEATURES_QNAME)) - .withChild(capabilities).build(); - - // Create a leaf list with numbers - final LeafSetEntryNode five = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - (new YangInstanceIdentifier.NodeWithValue(QName.create( - TEST_QNAME, "number"), 5))).withValue(5).build(); - final LeafSetEntryNode fifteen = - ImmutableLeafSetEntryNodeBuilder - .create() - .withNodeIdentifier( - (new YangInstanceIdentifier.NodeWithValue(QName.create( - TEST_QNAME, "number"), 15))).withValue(15).build(); - final LeafSetNode numbers = - ImmutableLeafSetNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(QName.create( - TEST_QNAME, "number"))).withChild(five).withChild(fifteen) - .build(); - - - // Create augmentations - MapEntryNode mapEntry = createAugmentedListEntry(1, "First Test"); - - // Create a bits leaf + public static DataContainerNodeAttrBuilder createBaseTestContainerBuilder() { + // Create a list of shoes + // This is to test leaf list entry + final LeafSetEntryNode nike = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "shoe"), "nike")).withValue("nike").build(); + + final LeafSetEntryNode puma = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "shoe"), "puma")).withValue("puma").build(); + + final LeafSetNode shoes = + ImmutableLeafSetNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(QName.create( + TEST_QNAME, "shoe"))).withChild(nike).withChild(puma) + .build(); + + + // Test a leaf-list where each entry contains an identity + final LeafSetEntryNode cap1 = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "capability"), DESC_QNAME)) + .withValue(DESC_QNAME).build(); + + final LeafSetNode capabilities = + ImmutableLeafSetNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(QName.create( + TEST_QNAME, "capability"))).withChild(cap1).build(); + + ContainerNode switchFeatures = + ImmutableContainerNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(SWITCH_FEATURES_QNAME)) + .withChild(capabilities).build(); + + // Create a leaf list with numbers + final LeafSetEntryNode five = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + (new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "number"), 5))).withValue(5).build(); + final LeafSetEntryNode fifteen = + ImmutableLeafSetEntryNodeBuilder + .create() + .withNodeIdentifier( + (new YangInstanceIdentifier.NodeWithValue(QName.create( + TEST_QNAME, "number"), 15))).withValue(15).build(); + final LeafSetNode numbers = + ImmutableLeafSetNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(QName.create( + TEST_QNAME, "number"))).withChild(five).withChild(fifteen) + .build(); + + + // Create augmentations + MapEntryNode mapEntry = createAugmentedListEntry(1, "First Test"); + + // Create a bits leaf NormalizedNodeAttrBuilder> - myBits = Builders.leafBuilder().withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier( - QName.create(TEST_QNAME, "my-bits"))).withValue( - ImmutableSet.of("foo", "bar")); + myBits = Builders.leafBuilder().withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier( + QName.create(TEST_QNAME, "my-bits"))).withValue( + ImmutableSet.of("foo", "bar")); // Create the document - return ImmutableContainerNodeBuilder - .create() - .withNodeIdentifier( - new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)) - .withChild(myBits.build()) - .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC)) - .withChild(ImmutableNodes.leafNode(POINTER_QNAME, "pointer")) - .withChild( - ImmutableNodes.leafNode(SOME_REF_QNAME, YangInstanceIdentifier - .builder().build())) - .withChild(ImmutableNodes.leafNode(MYIDENTITY_QNAME, DESC_QNAME)) - - // .withChild(augmentationNode) - .withChild(shoes) - .withChild(numbers) - .withChild(switchFeatures) - .withChild( - mapNodeBuilder(AUGMENTED_LIST_QNAME).withChild(mapEntry).build()) - .withChild( - mapNodeBuilder(OUTER_LIST_QNAME) - .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID)) - .withChild(BAR_NODE).build()).build(); + return ImmutableContainerNodeBuilder + .create() + .withNodeIdentifier( + new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)) + .withChild(myBits.build()) + .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC)) + .withChild(ImmutableNodes.leafNode(POINTER_QNAME, "pointer")) + .withChild( + ImmutableNodes.leafNode(SOME_REF_QNAME, YangInstanceIdentifier + .builder().build())) + .withChild(ImmutableNodes.leafNode(MYIDENTITY_QNAME, DESC_QNAME)) + + // .withChild(augmentationNode) + .withChild(shoes) + .withChild(numbers) + .withChild(switchFeatures) + .withChild( + mapNodeBuilder(AUGMENTED_LIST_QNAME).withChild(mapEntry).build()) + .withChild( + mapNodeBuilder(OUTER_LIST_QNAME) + .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID)) + .withChild(BAR_NODE).build()); + } + public static ContainerNode createTestContainer() { + return createBaseTestContainerBuilder().build(); } public static MapEntryNode createAugmentedListEntry(int id, String name) { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/xml/codec/XmlUtilsTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/xml/codec/XmlUtilsTest.java index 0688bfbc5c..cac58587a5 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/xml/codec/XmlUtilsTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/xml/codec/XmlUtilsTest.java @@ -8,11 +8,16 @@ package org.opendaylight.controller.xml.codec; - import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.io.ByteSource; -import junit.framework.Assert; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import javax.xml.parsers.DocumentBuilderFactory; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.opendaylight.yangtools.yang.common.QName; @@ -27,15 +32,6 @@ import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl; -import javax.xml.parsers.DocumentBuilderFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - - public class XmlUtilsTest { private static final DocumentBuilderFactory BUILDERFACTORY; @@ -85,18 +81,18 @@ public class XmlUtilsTest { @Test public void testInputXmlToCompositeNode() { CompositeNode node = XmlUtils.inputXmlToCompositeNode(testRpc.getQName(), XML_CONTENT, schema); - ImmutableList input = (ImmutableList)node.getValue().get(0).getValue(); - SimpleNode firstNode = input.get(0); + ImmutableList> input = (ImmutableList>)node.getValue().get(0).getValue(); + SimpleNode firstNode = input.get(0); Assert.assertEquals("id", firstNode.getNodeType().getLocalName()); Assert.assertEquals("flowid", firstNode.getValue()); - SimpleNode secondNode = input.get(1); + SimpleNode secondNode = input.get(1); Assert.assertEquals("flow", secondNode.getNodeType().getLocalName()); YangInstanceIdentifier instance = (YangInstanceIdentifier) secondNode.getValue(); Iterable iterable = instance.getPathArguments(); - Iterator it = iterable.iterator(); + Iterator it = iterable.iterator(); YangInstanceIdentifier.NodeIdentifier firstPath = (YangInstanceIdentifier.NodeIdentifier) it.next(); Assert.assertEquals("node", firstPath.getNodeType().getLocalName()); YangInstanceIdentifier.NodeIdentifierWithPredicates secondPath = (YangInstanceIdentifier.NodeIdentifierWithPredicates)it.next(); @@ -108,7 +104,7 @@ public class XmlUtilsTest { @Test public void testInputCompositeNodeToXML() { CompositeNode input = XmlUtils.inputXmlToCompositeNode(testRpc.getQName(), XML_CONTENT, schema); - List> childNodes = new ArrayList(); + List> childNodes = new ArrayList<>(); childNodes.add(input); QName rpcQName = schema.getOperations().iterator().next().getQName(); CompositeNode node = new ImmutableCompositeNode(rpcQName, input.getValue(), ModifyAction.REPLACE); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/resources/odl-datastore-test.yang b/opendaylight/md-sal/sal-clustering-commons/src/test/resources/odl-datastore-test.yang index 246cc682cd..a1fbc1fdad 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/resources/odl-datastore-test.yang +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/resources/odl-datastore-test.yang @@ -107,6 +107,10 @@ module odl-datastore-test { } } + leaf some-binary-data { + type binary; + } + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/pom.xml b/opendaylight/md-sal/sal-distributed-datastore/pom.xml index d7e7d56d49..bd42a9cdd9 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/pom.xml +++ b/opendaylight/md-sal/sal-distributed-datastore/pom.xml @@ -80,7 +80,6 @@ org.opendaylight.controller sal-inmemory-datastore - 1.2.0-SNAPSHOT @@ -131,7 +130,6 @@ org.opendaylight.controller sal-clustering-commons - 1.2.0-SNAPSHOT @@ -164,7 +162,6 @@ org.slf4j slf4j-simple - ${slf4j.version} test diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ClusterWrapper.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ClusterWrapper.java index 2eac2400b5..81a8c7e53f 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ClusterWrapper.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ClusterWrapper.java @@ -9,8 +9,10 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorRef; +import akka.actor.Address; public interface ClusterWrapper { void subscribeToMemberEvents(ActorRef actorRef); String getCurrentMemberName(); + Address getSelfAddress(); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ClusterWrapperImpl.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ClusterWrapperImpl.java index 8910137ec4..4edd60a33a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ClusterWrapperImpl.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ClusterWrapperImpl.java @@ -10,6 +10,7 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorRef; import akka.actor.ActorSystem; +import akka.actor.Address; import akka.cluster.Cluster; import akka.cluster.ClusterEvent; import com.google.common.base.Preconditions; @@ -17,6 +18,7 @@ import com.google.common.base.Preconditions; public class ClusterWrapperImpl implements ClusterWrapper { private final Cluster cluster; private final String currentMemberName; + private final Address selfAddress; public ClusterWrapperImpl(ActorSystem actorSystem){ Preconditions.checkNotNull(actorSystem, "actorSystem should not be null"); @@ -31,6 +33,7 @@ public class ClusterWrapperImpl implements ClusterWrapper { ); currentMemberName = (String) cluster.getSelfRoles().toArray()[0]; + selfAddress = cluster.selfAddress(); } @@ -45,4 +48,8 @@ public class ClusterWrapperImpl implements ClusterWrapper { public String getCurrentMemberName() { return currentMemberName; } + + public Address getSelfAddress() { + return selfAddress; + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ConfigurationImpl.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ConfigurationImpl.java index 1a0a5dd659..061e1ab448 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ConfigurationImpl.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ConfigurationImpl.java @@ -13,12 +13,6 @@ import com.google.common.base.Preconditions; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigObject; -import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy; -import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy; -import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.File; import java.util.ArrayList; import java.util.Collections; @@ -27,6 +21,11 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy; +import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy; +import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ConfigurationImpl implements Configuration { @@ -40,15 +39,15 @@ public class ConfigurationImpl implements Configuration { // Look up maps to speed things up // key = memberName, value = list of shardNames - private Map> memberShardNames = new HashMap<>(); + private final Map> memberShardNames = new HashMap<>(); // key = shardName, value = list of replicaNames (replicaNames are the same as memberNames) - private Map> shardReplicaNames = new HashMap<>(); + private final Map> shardReplicaNames = new HashMap<>(); - public ConfigurationImpl(String moduleShardsConfigPath, + public ConfigurationImpl(final String moduleShardsConfigPath, - String modulesConfigPath){ + final String modulesConfigPath){ Preconditions.checkNotNull(moduleShardsConfigPath, "moduleShardsConfigPath should not be null"); Preconditions.checkNotNull(modulesConfigPath, "modulesConfigPath should not be null"); @@ -80,7 +79,7 @@ public class ConfigurationImpl implements Configuration { readModules(modulesConfig); } - @Override public List getMemberShardNames(String memberName){ + @Override public List getMemberShardNames(final String memberName){ Preconditions.checkNotNull(memberName, "memberName should not be null"); @@ -88,7 +87,7 @@ public class ConfigurationImpl implements Configuration { return memberShardNames.get(memberName); } - List shards = new ArrayList(); + List shards = new ArrayList<>(); for(ModuleShard ms : moduleShards){ for(Shard s : ms.getShards()){ for(String m : s.getReplicas()){ @@ -105,7 +104,7 @@ public class ConfigurationImpl implements Configuration { } - @Override public Optional getModuleNameFromNameSpace(String nameSpace) { + @Override public Optional getModuleNameFromNameSpace(final String nameSpace) { Preconditions.checkNotNull(nameSpace, "nameSpace should not be null"); @@ -125,7 +124,7 @@ public class ConfigurationImpl implements Configuration { return map; } - @Override public List getShardNamesFromModuleName(String moduleName) { + @Override public List getShardNamesFromModuleName(final String moduleName) { Preconditions.checkNotNull(moduleName, "moduleName should not be null"); @@ -139,10 +138,10 @@ public class ConfigurationImpl implements Configuration { } } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } - @Override public List getMembersFromShardName(String shardName) { + @Override public List getMembersFromShardName(final String shardName) { Preconditions.checkNotNull(shardName, "shardName should not be null"); @@ -159,8 +158,8 @@ public class ConfigurationImpl implements Configuration { } } } - shardReplicaNames.put(shardName, Collections.EMPTY_LIST); - return Collections.EMPTY_LIST; + shardReplicaNames.put(shardName, Collections.emptyList()); + return Collections.emptyList(); } @Override public Set getAllShardNames() { @@ -175,7 +174,7 @@ public class ConfigurationImpl implements Configuration { - private void readModules(Config modulesConfig) { + private void readModules(final Config modulesConfig) { List modulesConfigObjectList = modulesConfig.getObjectList("modules"); @@ -186,7 +185,7 @@ public class ConfigurationImpl implements Configuration { } } - private void readModuleShards(Config moduleShardsConfig) { + private void readModuleShards(final Config moduleShardsConfig) { List moduleShardsConfigObjectList = moduleShardsConfig.getObjectList("module-shards"); @@ -214,7 +213,7 @@ public class ConfigurationImpl implements Configuration { private final String moduleName; private final List shards; - public ModuleShard(String moduleName, List shards) { + public ModuleShard(final String moduleName, final List shards) { this.moduleName = moduleName; this.shards = shards; } @@ -232,7 +231,7 @@ public class ConfigurationImpl implements Configuration { private final String name; private final List replicas; - Shard(String name, List replicas) { + Shard(final String name, final List replicas) { this.name = name; this.replicas = replicas; } @@ -252,7 +251,7 @@ public class ConfigurationImpl implements Configuration { private final String nameSpace; private final ShardStrategy shardStrategy; - Module(String name, String nameSpace, String shardStrategy) { + Module(final String name, final String nameSpace, final String shardStrategy) { this.name = name; this.nameSpace = nameSpace; if(ModuleShardStrategy.NAME.equals(shardStrategy)){ @@ -280,11 +279,11 @@ public class ConfigurationImpl implements Configuration { private final ConfigObject configObject; - ConfigObjectWrapper(ConfigObject configObject){ + ConfigObjectWrapper(final ConfigObject configObject){ this.configObject = configObject; } - public String stringValue(String name){ + public String stringValue(final String name){ return configObject.get(name).unwrapped().toString(); } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListener.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListener.java index a498826e98..9a77e4d568 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListener.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListener.java @@ -19,8 +19,12 @@ import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class DataChangeListener extends AbstractUntypedActor { + private static final Logger LOG = LoggerFactory.getLogger(DataChangeListener.class); + private final AsyncDataChangeListener> listener; private boolean notificationsEnabled = false; @@ -29,7 +33,8 @@ public class DataChangeListener extends AbstractUntypedActor { this.listener = Preconditions.checkNotNull(listener, "listener should not be null"); } - @Override public void handleReceive(Object message) throws Exception { + @Override + public void handleReceive(Object message) throws Exception { if(message instanceof DataChanged){ dataChanged(message); } else if(message instanceof EnableNotification){ @@ -39,18 +44,24 @@ public class DataChangeListener extends AbstractUntypedActor { private void enableNotification(EnableNotification message) { notificationsEnabled = message.isEnabled(); + LOG.debug("{} notifications for listener {}", (notificationsEnabled ? "Enabled" : "Disabled"), + listener); } private void dataChanged(Object message) { // Do nothing if notifications are not enabled - if(!notificationsEnabled){ + if(!notificationsEnabled) { + LOG.debug("Notifications not enabled for listener {} - dropping change notification", + listener); return; } DataChanged reply = (DataChanged) message; - AsyncDataChangeEvent> - change = reply.getChange(); + AsyncDataChangeEvent> change = reply.getChange(); + + LOG.debug("Sending change notification {} to listener {}", change, listener); + this.listener.onDataChanged(change); // It seems the sender is never null but it doesn't hurt to check. If the caller passes in diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistration.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistration.java index 342611298c..a8d7d22105 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistration.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistration.java @@ -53,6 +53,7 @@ public class DataChangeListenerRegistration extends AbstractUntypedActor { private static class DataChangeListenerRegistrationCreator implements Creator { + private static final long serialVersionUID = 1L; final ListenerRegistration>> registration; diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxy.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxy.java index acf630e2e9..06f3afc57c 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxy.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxy.java @@ -11,11 +11,22 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorRef; import akka.actor.ActorSelection; import akka.actor.PoisonPill; +import akka.dispatch.OnComplete; +import org.opendaylight.controller.cluster.datastore.exceptions.LocalShardNotFoundException; import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistration; +import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener; +import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply; +import org.opendaylight.controller.cluster.datastore.utils.ActorContext; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.google.common.annotations.VisibleForTesting; +import scala.concurrent.Future; /** * ListenerRegistrationProxy acts as a proxy for a ListenerRegistration that was done on a remote shard @@ -24,25 +35,34 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; * The ListenerRegistrationProxy talks to a remote ListenerRegistration actor. *

      */ +@SuppressWarnings("rawtypes") public class DataChangeListenerRegistrationProxy implements ListenerRegistration { + + private static final Logger LOG = LoggerFactory.getLogger(DataChangeListenerRegistrationProxy.class); + private volatile ActorSelection listenerRegistrationActor; - private final AsyncDataChangeListener listener; - private final ActorRef dataChangeListenerActor; + private final AsyncDataChangeListener> listener; + private ActorRef dataChangeListenerActor; + private final String shardName; + private final ActorContext actorContext; private boolean closed = false; public >> - DataChangeListenerRegistrationProxy( - ActorSelection listenerRegistrationActor, - L listener, ActorRef dataChangeListenerActor) { - this.listenerRegistrationActor = listenerRegistrationActor; + DataChangeListenerRegistrationProxy ( + String shardName, ActorContext actorContext, L listener) { + this.shardName = shardName; + this.actorContext = actorContext; this.listener = listener; - this.dataChangeListenerActor = dataChangeListenerActor; } - public >> - DataChangeListenerRegistrationProxy( - L listener, ActorRef dataChangeListenerActor) { - this(null, listener, dataChangeListenerActor); + @VisibleForTesting + ActorSelection getListenerRegistrationActor() { + return listenerRegistrationActor; + } + + @VisibleForTesting + ActorRef getDataChangeListenerActor() { + return dataChangeListenerActor; } @Override @@ -50,7 +70,11 @@ public class DataChangeListenerRegistrationProxy implements ListenerRegistration return listener; } - public void setListenerRegistrationActor(ActorSelection listenerRegistrationActor) { + private void setListenerRegistrationActor(ActorSelection listenerRegistrationActor) { + if(listenerRegistrationActor == null) { + return; + } + boolean sendCloseMessage = false; synchronized(this) { if(closed) { @@ -59,16 +83,55 @@ public class DataChangeListenerRegistrationProxy implements ListenerRegistration this.listenerRegistrationActor = listenerRegistrationActor; } } + if(sendCloseMessage) { listenerRegistrationActor.tell(new CloseDataChangeListenerRegistration().toSerializable(), null); } + } + + public void init(final YangInstanceIdentifier path, final AsyncDataBroker.DataChangeScope scope) { - this.listenerRegistrationActor = listenerRegistrationActor; + dataChangeListenerActor = actorContext.getActorSystem().actorOf( + DataChangeListener.props(listener)); + + Future findFuture = actorContext.findLocalShardAsync(shardName); + findFuture.onComplete(new OnComplete() { + @Override + public void onComplete(Throwable failure, ActorRef shard) { + if(failure instanceof LocalShardNotFoundException) { + LOG.debug("No local shard found for {} - DataChangeListener {} at path {} " + + "cannot be registered", shardName, listener, path); + } else if(failure != null) { + LOG.error("Failed to find local shard {} - DataChangeListener {} at path {} " + + "cannot be registered: {}", shardName, listener, path, failure); + } else { + doRegistration(shard, path, scope); + } + } + }, actorContext.getActorSystem().dispatcher()); } - public ActorSelection getListenerRegistrationActor() { - return listenerRegistrationActor; + private void doRegistration(ActorRef shard, final YangInstanceIdentifier path, + DataChangeScope scope) { + + Future future = actorContext.executeOperationAsync(shard, + new RegisterChangeListener(path, dataChangeListenerActor.path(), scope), + actorContext.getDatastoreContext().getShardInitializationTimeout()); + + future.onComplete(new OnComplete(){ + @Override + public void onComplete(Throwable failure, Object result) { + if(failure != null) { + LOG.error("Failed to register DataChangeListener {} at path {}", + listener, path.toString(), failure); + } else { + RegisterChangeListenerReply reply = (RegisterChangeListenerReply) result; + setListenerRegistrationActor(actorContext.actorSelection( + reply.getListenerRegistrationPath())); + } + } + }, actorContext.getActorSystem().dispatcher()); } @Override @@ -79,11 +142,16 @@ public class DataChangeListenerRegistrationProxy implements ListenerRegistration sendCloseMessage = !closed && listenerRegistrationActor != null; closed = true; } + if(sendCloseMessage) { - listenerRegistrationActor.tell(new - CloseDataChangeListenerRegistration().toSerializable(), null); + listenerRegistrationActor.tell(new CloseDataChangeListenerRegistration().toSerializable(), + ActorRef.noSender()); + listenerRegistrationActor = null; } - dataChangeListenerActor.tell(PoisonPill.getInstance(), null); + if(dataChangeListenerActor != null) { + dataChangeListenerActor.tell(PoisonPill.getInstance(), ActorRef.noSender()); + dataChangeListenerActor = null; + } } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DatastoreContext.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DatastoreContext.java index 722e23046e..e18c00ec4b 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DatastoreContext.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DatastoreContext.java @@ -8,11 +8,15 @@ package org.opendaylight.controller.cluster.datastore; +import org.opendaylight.controller.cluster.datastore.config.ConfigurationReader; +import org.opendaylight.controller.cluster.datastore.config.FileConfigurationReader; import org.opendaylight.controller.cluster.raft.ConfigParams; import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl; import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreConfigProperties; +import akka.util.Timeout; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; + import java.util.concurrent.TimeUnit; /** @@ -29,11 +33,17 @@ public class DatastoreContext { private final ConfigParams shardRaftConfig; private final int shardTransactionCommitTimeoutInSeconds; private final int shardTransactionCommitQueueCapacity; + private final Timeout shardInitializationTimeout; + private final Timeout shardLeaderElectionTimeout; + private final boolean persistent; + private final ConfigurationReader configurationReader; private DatastoreContext(InMemoryDOMDataStoreConfigProperties dataStoreProperties, ConfigParams shardRaftConfig, String dataStoreMXBeanType, int operationTimeoutInSeconds, Duration shardTransactionIdleTimeout, int shardTransactionCommitTimeoutInSeconds, - int shardTransactionCommitQueueCapacity) { + int shardTransactionCommitQueueCapacity, Timeout shardInitializationTimeout, + Timeout shardLeaderElectionTimeout, + boolean persistent, ConfigurationReader configurationReader) { this.dataStoreProperties = dataStoreProperties; this.shardRaftConfig = shardRaftConfig; this.dataStoreMXBeanType = dataStoreMXBeanType; @@ -41,6 +51,10 @@ public class DatastoreContext { this.shardTransactionIdleTimeout = shardTransactionIdleTimeout; this.shardTransactionCommitTimeoutInSeconds = shardTransactionCommitTimeoutInSeconds; this.shardTransactionCommitQueueCapacity = shardTransactionCommitQueueCapacity; + this.shardInitializationTimeout = shardInitializationTimeout; + this.shardLeaderElectionTimeout = shardLeaderElectionTimeout; + this.persistent = persistent; + this.configurationReader = configurationReader; } public static Builder newBuilder() { @@ -75,6 +89,22 @@ public class DatastoreContext { return shardTransactionCommitQueueCapacity; } + public Timeout getShardInitializationTimeout() { + return shardInitializationTimeout; + } + + public Timeout getShardLeaderElectionTimeout() { + return shardLeaderElectionTimeout; + } + + public boolean isPersistent() { + return persistent; + } + + public ConfigurationReader getConfigurationReader() { + return configurationReader; + } + public static class Builder { private InMemoryDOMDataStoreConfigProperties dataStoreProperties; private Duration shardTransactionIdleTimeout = Duration.create(10, TimeUnit.MINUTES); @@ -85,6 +115,11 @@ public class DatastoreContext { private int shardSnapshotBatchCount = 20000; private int shardHeartbeatIntervalInMillis = 500; private int shardTransactionCommitQueueCapacity = 20000; + private Timeout shardInitializationTimeout = new Timeout(5, TimeUnit.MINUTES); + private Timeout shardLeaderElectionTimeout = new Timeout(30, TimeUnit.SECONDS); + private boolean persistent = true; + private ConfigurationReader configurationReader = new FileConfigurationReader(); + private int shardIsolatedLeaderCheckIntervalInMillis = shardHeartbeatIntervalInMillis * 10; public Builder shardTransactionIdleTimeout(Duration shardTransactionIdleTimeout) { this.shardTransactionIdleTimeout = shardTransactionIdleTimeout; @@ -131,16 +166,45 @@ public class DatastoreContext { return this; } + public Builder shardInitializationTimeout(long timeout, TimeUnit unit) { + this.shardInitializationTimeout = new Timeout(timeout, unit); + return this; + } + + public Builder shardLeaderElectionTimeout(long timeout, TimeUnit unit) { + this.shardLeaderElectionTimeout = new Timeout(timeout, unit); + return this; + } + + public Builder configurationReader(ConfigurationReader configurationReader){ + this.configurationReader = configurationReader; + return this; + } + + public Builder persistent(boolean persistent){ + this.persistent = persistent; + return this; + } + + public Builder shardIsolatedLeaderCheckIntervalInMillis(int shardIsolatedLeaderCheckIntervalInMillis) { + this.shardIsolatedLeaderCheckIntervalInMillis = shardIsolatedLeaderCheckIntervalInMillis; + return this; + } + public DatastoreContext build() { DefaultConfigParamsImpl raftConfig = new DefaultConfigParamsImpl(); raftConfig.setHeartBeatInterval(new FiniteDuration(shardHeartbeatIntervalInMillis, TimeUnit.MILLISECONDS)); raftConfig.setJournalRecoveryLogBatchSize(shardJournalRecoveryLogBatchSize); raftConfig.setSnapshotBatchCount(shardSnapshotBatchCount); + raftConfig.setIsolatedLeaderCheckInterval( + new FiniteDuration(shardIsolatedLeaderCheckIntervalInMillis, TimeUnit.MILLISECONDS)); return new DatastoreContext(dataStoreProperties, raftConfig, dataStoreMXBeanType, operationTimeoutInSeconds, shardTransactionIdleTimeout, - shardTransactionCommitTimeoutInSeconds, shardTransactionCommitQueueCapacity); + shardTransactionCommitTimeoutInSeconds, shardTransactionCommitQueueCapacity, + shardInitializationTimeout, shardLeaderElectionTimeout, + persistent, configurationReader); } } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStore.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStore.java index f6c31aab04..930c5f7257 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStore.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStore.java @@ -8,16 +8,10 @@ package org.opendaylight.controller.cluster.datastore; -import akka.actor.ActorRef; import akka.actor.ActorSystem; -import akka.dispatch.OnComplete; -import akka.util.Timeout; -import com.google.common.base.Optional; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier; -import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener; -import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply; import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory; import org.opendaylight.controller.cluster.datastore.utils.ActorContext; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker; @@ -34,7 +28,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import scala.concurrent.Future; /** * @@ -60,9 +53,8 @@ public class DistributedDataStore implements DOMStore, SchemaContextListener, Au actorContext = new ActorContext(actorSystem, actorSystem.actorOf( ShardManager.props(type, cluster, configuration, datastoreContext) - .withMailbox(ActorContext.MAILBOX), shardManagerId ), cluster, configuration); - - actorContext.setOperationTimeout(datastoreContext.getOperationTimeoutInSeconds()); + .withMailbox(ActorContext.MAILBOX), shardManagerId ), + cluster, configuration, datastoreContext); } public DistributedDataStore(ActorContext actorContext) { @@ -83,39 +75,11 @@ public class DistributedDataStore implements DOMStore, SchemaContextListener, Au String shardName = ShardStrategyFactory.getStrategy(path).findShard(path); - Optional shard = actorContext.findLocalShard(shardName); - - //if shard is NOT local - if (!shard.isPresent()) { - LOG.debug("No local shard for shardName {} was found so returning a noop registration", shardName); - return new NoOpDataChangeListenerRegistration(listener); - } - //if shard is local - ActorRef dataChangeListenerActor = actorContext.getActorSystem().actorOf(DataChangeListener.props(listener)); - Future future = actorContext.executeOperationAsync(shard.get(), - new RegisterChangeListener(path, dataChangeListenerActor.path(), scope), - new Timeout(actorContext.getOperationDuration().$times(REGISTER_DATA_CHANGE_LISTENER_TIMEOUT_FACTOR))); - final DataChangeListenerRegistrationProxy listenerRegistrationProxy = - new DataChangeListenerRegistrationProxy(listener, dataChangeListenerActor); - - future.onComplete(new OnComplete() { - - @Override - public void onComplete(Throwable failure, Object result) - throws Throwable { - if (failure != null) { - LOG.error("Failed to register listener at path " + path.toString(), failure); - return; - } - RegisterChangeListenerReply reply = (RegisterChangeListenerReply) result; - listenerRegistrationProxy.setListenerRegistrationActor(actorContext - .actorSelection(reply.getListenerRegistrationPath())); - } - }, actorContext.getActorSystem().dispatcher()); + new DataChangeListenerRegistrationProxy(shardName, actorContext, listener); + listenerRegistrationProxy.init(path, scope); return listenerRegistrationProxy; - } @Override diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreFactory.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreFactory.java index a6f187d065..004faf2de1 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreFactory.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreFactory.java @@ -11,27 +11,26 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorSystem; import akka.actor.Props; import akka.osgi.BundleDelegatingClassLoader; -import com.google.common.base.Preconditions; -import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; +import org.opendaylight.controller.cluster.datastore.config.ConfigurationReader; import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory; import org.opendaylight.controller.sal.core.api.model.SchemaService; import org.osgi.framework.BundleContext; -import java.io.File; import java.util.concurrent.atomic.AtomicReference; public class DistributedDataStoreFactory { - public static final String AKKA_CONF_PATH = "./configuration/initial/akka.conf"; public static final String ACTOR_SYSTEM_NAME = "opendaylight-cluster-data"; + public static final String CONFIGURATION_NAME = "odl-cluster-data"; - private static AtomicReference actorSystem = new AtomicReference<>(); + + private static AtomicReference persistentActorSystem = new AtomicReference<>(); public static DistributedDataStore createInstance(String name, SchemaService schemaService, DatastoreContext datastoreContext, BundleContext bundleContext) { - ActorSystem actorSystem = getOrCreateInstance(bundleContext); + ActorSystem actorSystem = getOrCreateInstance(bundleContext, datastoreContext.getConfigurationReader()); Configuration config = new ConfigurationImpl("module-shards.conf", "modules.conf"); final DistributedDataStore dataStore = new DistributedDataStore(actorSystem, name, new ClusterWrapperImpl(actorSystem), @@ -42,27 +41,26 @@ public class DistributedDataStoreFactory { return dataStore; } - synchronized private static final ActorSystem getOrCreateInstance(final BundleContext bundleContext) { + synchronized private static final ActorSystem getOrCreateInstance(final BundleContext bundleContext, ConfigurationReader configurationReader) { + + AtomicReference actorSystemReference = persistentActorSystem; + String configurationName = CONFIGURATION_NAME; + String actorSystemName = ACTOR_SYSTEM_NAME; - if (actorSystem.get() != null){ - return actorSystem.get(); + if (actorSystemReference.get() != null){ + return actorSystemReference.get(); } + // Create an OSGi bundle classloader for actor system BundleDelegatingClassLoader classLoader = new BundleDelegatingClassLoader(bundleContext.getBundle(), Thread.currentThread().getContextClassLoader()); - ActorSystem system = ActorSystem.create(ACTOR_SYSTEM_NAME, - ConfigFactory.load(readAkkaConfiguration()).getConfig(CONFIGURATION_NAME), classLoader); + ActorSystem system = ActorSystem.create(actorSystemName, + ConfigFactory.load(configurationReader.read()).getConfig(configurationName), classLoader); system.actorOf(Props.create(TerminationMonitor.class), "termination-monitor"); - actorSystem.set(system); + actorSystemReference.set(system); return system; } - - private static final Config readAkkaConfiguration() { - File defaultConfigFile = new File(AKKA_CONF_PATH); - Preconditions.checkState(defaultConfigFile.exists(), "akka.conf is missing"); - return ConfigFactory.parseFile(defaultConfigFile); - } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/NoOpCohort.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/NoOpCohort.java deleted file mode 100644 index eb28159025..0000000000 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/NoOpCohort.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.cluster.datastore; - -import akka.actor.UntypedActor; -import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction; -import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply; -import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction; -import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply; -import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction; -import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply; -import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransaction; -import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransactionReply; - -public class NoOpCohort extends UntypedActor { - - @Override public void onReceive(Object message) throws Exception { - if (message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) { - getSender().tell(new CanCommitTransactionReply(false).toSerializable(), getSelf()); - } else if (message.getClass().equals(PreCommitTransaction.SERIALIZABLE_CLASS)) { - getSender().tell( - new PreCommitTransactionReply().toSerializable(), - getSelf()); - } else if (message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) { - getSender().tell(new CommitTransactionReply().toSerializable(), getSelf()); - } else if (message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) { - getSender().tell(new AbortTransactionReply().toSerializable(), getSelf()); - } else { - throw new Exception ("Not recognized message received,message="+message); - } - - } -} - diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/NoOpDataChangeListenerRegistration.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/NoOpDataChangeListenerRegistration.java deleted file mode 100644 index 14af31e898..0000000000 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/NoOpDataChangeListenerRegistration.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.cluster.datastore; - -import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * When a consumer registers a data change listener and no local shard is - * available to register that listener with then we return an instance of - * NoOpDataChangeListenerRegistration - * - *

      - * - * The NoOpDataChangeListenerRegistration as it's name suggests does - * nothing when an operation is invoked on it - */ -public class NoOpDataChangeListenerRegistration - implements ListenerRegistration { - - private final AsyncDataChangeListener> - listener; - - public >> NoOpDataChangeListenerRegistration( - AsyncDataChangeListener> listener) { - - this.listener = listener; - } - - @Override - public AsyncDataChangeListener> getInstance() { - return listener; - } - - @Override public void close() { - - } -} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java index fef7e22873..4b130950f2 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java @@ -27,16 +27,26 @@ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nonnull; +import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.common.actor.CommonConfig; import org.opendaylight.controller.cluster.common.actor.MeteringBehavior; import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry; +import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort; +import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException; import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier; import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier; import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory; import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats; -import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized; import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction; import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply; +import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized; import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction; import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain; import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction; @@ -74,14 +84,6 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import javax.annotation.Nonnull; /** * A Shard represents a portion of the logical data tree
      @@ -103,19 +105,20 @@ public class Shard extends RaftActor { private final LoggingAdapter LOG = Logging.getLogger(getContext().system(), this); - // By default persistent will be true and can be turned off using the system - // property shard.persistent - private final boolean persistent; - /// The name of this shard private final ShardIdentifier name; private final ShardStats shardMBean; - private final List dataChangeListeners = new ArrayList<>(); + private final List dataChangeListeners = Lists.newArrayList(); + + private final List delayedListenerRegistrations = + Lists.newArrayList(); private final DatastoreContext datastoreContext; + private final DataPersistenceProvider dataPersistenceProvider; + private SchemaContext schemaContext; private ActorRef createSnapshotTransaction; @@ -144,12 +147,9 @@ public class Shard extends RaftActor { this.name = name; this.datastoreContext = datastoreContext; this.schemaContext = schemaContext; + this.dataPersistenceProvider = (datastoreContext.isPersistent()) ? new PersistentDataProvider() : new NonPersistentRaftDataProvider(); - String setting = System.getProperty("shard.persistent"); - - this.persistent = !"false".equals(setting); - - LOG.info("Shard created : {} persistent : {}", name, persistent); + LOG.info("Shard created : {} persistent : {}", name, datastoreContext.isPersistent()); store = InMemoryDOMDataStoreFactory.create(name.toString(), null, datastoreContext.getDataStoreProperties()); @@ -207,7 +207,7 @@ public class Shard extends RaftActor { } @Override - public void onReceiveRecover(Object message) { + public void onReceiveRecover(Object message) throws Exception { if(LOG.isDebugEnabled()) { LOG.debug("onReceiveRecover: Received message {} from {}", message.getClass().toString(), @@ -216,13 +216,17 @@ public class Shard extends RaftActor { if (message instanceof RecoveryFailure){ LOG.error(((RecoveryFailure) message).cause(), "Recovery failed because of this cause"); + + // Even though recovery failed, we still need to finish our recovery, eg send the + // ActorInitialized message and start the txCommitTimeoutCheckSchedule. + onRecoveryComplete(); } else { super.onReceiveRecover(message); } } @Override - public void onReceiveCommand(Object message) { + public void onReceiveCommand(Object message) throws Exception { if(LOG.isDebugEnabled()) { LOG.debug("onReceiveCommand: Received message {} from {}", message, getSender()); } @@ -300,12 +304,8 @@ public class Shard extends RaftActor { // currently uses a same thread executor anyway. cohortEntry.getCohort().preCommit().get(); - if(persistent) { - Shard.this.persistData(getSender(), transactionID, - new CompositeModificationPayload(cohortEntry.getModification().toSerializable())); - } else { - Shard.this.finishCommit(getSender(), transactionID); - } + Shard.this.persistData(getSender(), transactionID, + new CompositeModificationPayload(cohortEntry.getModification().toSerializable())); } catch (InterruptedException | ExecutionException e) { LOG.error(e, "An exception occurred while preCommitting transaction {}", cohortEntry.getTransactionID()); @@ -374,7 +374,8 @@ public class Shard extends RaftActor { } private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) { - LOG.debug("Readying transaction {}", ready.getTransactionID()); + LOG.debug("Readying transaction {}, client version {}", ready.getTransactionID(), + ready.getTxnClientVersion()); // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the // commitCoordinator in preparation for the subsequent three phase commit initiated by @@ -382,9 +383,22 @@ public class Shard extends RaftActor { commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(), ready.getModification()); - // Return our actor path as we'll handle the three phase commit. - getSender().tell(new ReadyTransactionReply(Serialization.serializedActorPath(self())). - toSerializable(), getSelf()); + // Return our actor path as we'll handle the three phase commit, except if the Tx client + // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version + // node. In that case, the subsequent 3-phase commit messages won't contain the + // transactionId so to maintain backwards compatibility, we create a separate cohort actor + // to provide the compatible behavior. + ActorRef replyActorPath = self(); + if(ready.getTxnClientVersion() < CreateTransaction.HELIUM_1_VERSION) { + LOG.debug("Creating BackwardsCompatibleThreePhaseCommitCohort"); + replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props( + ready.getTransactionID())); + } + + ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply( + Serialization.serializedActorPath(replyActorPath)); + getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() : + readyTransactionReply, getSelf()); } private void handleAbortTransaction(AbortTransaction abort) { @@ -432,9 +446,9 @@ public class Shard extends RaftActor { } else if (getLeader() != null) { getLeader().forward(message, getContext()); } else { - getSender().tell(new akka.actor.Status.Failure(new IllegalStateException( + getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException( "Could not find shard leader so transaction cannot be created. This typically happens" + - " when system is coming up or recovering and a leader is being elected. Try again" + + " when the system is coming up or recovering and a leader is being elected. Try again" + " later.")), getSelf()); } } @@ -462,10 +476,8 @@ public class Shard extends RaftActor { } } - private ActorRef createTypedTransactionActor( - int transactionType, - ShardTransactionIdentifier transactionId, - String transactionChainId ) { + private ActorRef createTypedTransactionActor(int transactionType, + ShardTransactionIdentifier transactionId, String transactionChainId, int clientVersion ) { DOMStoreTransactionFactory factory = store; @@ -478,8 +490,8 @@ public class Shard extends RaftActor { } } - if(this.schemaContext == null){ - throw new NullPointerException("schemaContext should not be null"); + if(this.schemaContext == null) { + throw new IllegalStateException("SchemaContext is not set"); } if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) { @@ -489,7 +501,8 @@ public class Shard extends RaftActor { return getContext().actorOf( ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(), schemaContext,datastoreContext, shardMBean, - transactionId.getRemoteTransactionId()), transactionId.toString()); + transactionId.getRemoteTransactionId(), clientVersion), + transactionId.toString()); } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) { @@ -498,7 +511,8 @@ public class Shard extends RaftActor { return getContext().actorOf( ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(), schemaContext, datastoreContext, shardMBean, - transactionId.getRemoteTransactionId()), transactionId.toString()); + transactionId.getRemoteTransactionId(), clientVersion), + transactionId.toString()); } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) { @@ -508,7 +522,8 @@ public class Shard extends RaftActor { return getContext().actorOf( ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(), schemaContext, datastoreContext, shardMBean, - transactionId.getRemoteTransactionId()), transactionId.toString()); + transactionId.getRemoteTransactionId(), clientVersion), + transactionId.toString()); } else { throw new IllegalArgumentException( "Shard="+name + ":CreateTransaction message has unidentified transaction type=" @@ -517,27 +532,32 @@ public class Shard extends RaftActor { } private void createTransaction(CreateTransaction createTransaction) { - createTransaction(createTransaction.getTransactionType(), - createTransaction.getTransactionId(), createTransaction.getTransactionChainId()); + try { + ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(), + createTransaction.getTransactionId(), createTransaction.getTransactionChainId(), + createTransaction.getVersion()); + + getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor), + createTransaction.getTransactionId()).toSerializable(), getSelf()); + } catch (Exception e) { + getSender().tell(new akka.actor.Status.Failure(e), getSelf()); + } } - private ActorRef createTransaction(int transactionType, String remoteTransactionId, String transactionChainId) { + private ActorRef createTransaction(int transactionType, String remoteTransactionId, + String transactionChainId, int clientVersion) { ShardTransactionIdentifier transactionId = ShardTransactionIdentifier.builder() .remoteTransactionId(remoteTransactionId) .build(); + if(LOG.isDebugEnabled()) { LOG.debug("Creating transaction : {} ", transactionId); } - ActorRef transactionActor = - createTypedTransactionActor(transactionType, transactionId, transactionChainId); - getSender() - .tell(new CreateTransactionReply( - Serialization.serializedActorPath(transactionActor), - remoteTransactionId).toSerializable(), - getSelf()); + ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId, + transactionChainId, clientVersion); return transactionActor; } @@ -568,53 +588,60 @@ public class Shard extends RaftActor { store.onGlobalContextUpdated(message.getSchemaContext()); } - @VisibleForTesting void updateSchemaContext(SchemaContext schemaContext) { + @VisibleForTesting + void updateSchemaContext(SchemaContext schemaContext) { store.onGlobalContextUpdated(schemaContext); } - private void registerChangeListener( - RegisterChangeListener registerChangeListener) { + private void registerChangeListener(RegisterChangeListener registerChangeListener) { - if(LOG.isDebugEnabled()) { - LOG.debug("registerDataChangeListener for {}", registerChangeListener - .getPath()); + LOG.debug("registerDataChangeListener for {}", registerChangeListener.getPath()); + + ListenerRegistration>> registration; + if(isLeader()) { + registration = doChangeListenerRegistration(registerChangeListener); + } else { + LOG.debug("Shard is not the leader - delaying registration"); + + DelayedListenerRegistration delayedReg = + new DelayedListenerRegistration(registerChangeListener); + delayedListenerRegistrations.add(delayedReg); + registration = delayedReg; } + ActorRef listenerRegistration = getContext().actorOf( + DataChangeListenerRegistration.props(registration)); - ActorSelection dataChangeListenerPath = getContext() - .system().actorSelection( - registerChangeListener.getDataChangeListenerPath()); + LOG.debug("registerDataChangeListener sending reply, listenerRegistrationPath = {} ", + listenerRegistration.path()); + + getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf()); + } + private ListenerRegistration>> doChangeListenerRegistration( + RegisterChangeListener registerChangeListener) { + + ActorSelection dataChangeListenerPath = getContext().system().actorSelection( + registerChangeListener.getDataChangeListenerPath()); // Notify the listener if notifications should be enabled or not // If this shard is the leader then it will enable notifications else // it will not - dataChangeListenerPath - .tell(new EnableNotification(isLeader()), getSelf()); + dataChangeListenerPath.tell(new EnableNotification(true), getSelf()); // Now store a reference to the data change listener so it can be notified // at a later point if notifications should be enabled or disabled dataChangeListeners.add(dataChangeListenerPath); - AsyncDataChangeListener> - listener = new DataChangeListenerProxy(schemaContext, dataChangeListenerPath); + AsyncDataChangeListener> listener = + new DataChangeListenerProxy(schemaContext, dataChangeListenerPath); - ListenerRegistration>> - registration = store.registerChangeListener(registerChangeListener.getPath(), - listener, registerChangeListener.getScope()); - ActorRef listenerRegistration = - getContext().actorOf( - DataChangeListenerRegistration.props(registration)); - - if(LOG.isDebugEnabled()) { - LOG.debug( - "registerDataChangeListener sending reply, listenerRegistrationPath = {} " - , listenerRegistration.path().toString()); - } + LOG.debug("Registering for path {}", registerChangeListener.getPath()); - getSender() - .tell(new RegisterChangeListenerReply(listenerRegistration.path()), - getSelf()); + return store.registerChangeListener(registerChangeListener.getPath(), listener, + registerChangeListener.getScope()); } private boolean isMetricsCaptureEnabled(){ @@ -695,12 +722,15 @@ public class Shard extends RaftActor { //notify shard manager getContext().parent().tell(new ActorInitialized(), getSelf()); - // Schedule a message to be periodically sent to check if the current in-progress - // transaction should be expired and aborted. - FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS); - txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule( - period, period, getSelf(), - TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender()); + // Being paranoid here - this method should only be called once but just in case... + if(txCommitTimeoutCheckSchedule == null) { + // Schedule a message to be periodically sent to check if the current in-progress + // transaction should be expired and aborted. + FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS); + txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule( + period, period, getSelf(), + TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender()); + } } @Override @@ -752,7 +782,8 @@ public class Shard extends RaftActor { // so that this actor does not get block building the snapshot createSnapshotTransaction = createTransaction( TransactionProxy.TransactionType.READ_ONLY.ordinal(), - "createSnapshot" + ++createSnapshotTransactionCounter, ""); + "createSnapshot" + ++createSnapshotTransactionCounter, "", + CreateTransaction.CURRENT_VERSION); createSnapshotTransaction.tell( new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self()); @@ -787,17 +818,28 @@ public class Shard extends RaftActor { } } - @Override protected void onStateChanged() { + @Override + protected void onStateChanged() { + boolean isLeader = isLeader(); for (ActorSelection dataChangeListener : dataChangeListeners) { - dataChangeListener - .tell(new EnableNotification(isLeader()), getSelf()); + dataChangeListener.tell(new EnableNotification(isLeader), getSelf()); + } + + if(isLeader) { + for(DelayedListenerRegistration reg: delayedListenerRegistrations) { + if(!reg.isClosed()) { + reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener())); + } + } + + delayedListenerRegistrations.clear(); } shardMBean.setRaftState(getRaftState().name()); shardMBean.setCurrentTerm(getCurrentTerm()); // If this actor is no longer the leader close all the transaction chains - if(!isLeader()){ + if(!isLeader){ for(Map.Entry entry : transactionChains.entrySet()){ if(LOG.isDebugEnabled()) { LOG.debug( @@ -811,6 +853,11 @@ public class Shard extends RaftActor { } } + @Override + protected DataPersistenceProvider persistence() { + return dataPersistenceProvider; + } + @Override protected void onLeaderChanged(String oldLeader, String newLeader) { shardMBean.setLeader(newLeader); } @@ -819,6 +866,11 @@ public class Shard extends RaftActor { return this.name.toString(); } + @VisibleForTesting + DataPersistenceProvider getDataPersistenceProvider() { + return dataPersistenceProvider; + } + private static class ShardCreator implements Creator { private static final long serialVersionUID = 1L; @@ -851,4 +903,45 @@ public class Shard extends RaftActor { ShardStats getShardMBean() { return shardMBean; } + + private static class DelayedListenerRegistration implements + ListenerRegistration>> { + + private volatile boolean closed; + + private final RegisterChangeListener registerChangeListener; + + private volatile ListenerRegistration>> delegate; + + DelayedListenerRegistration(RegisterChangeListener registerChangeListener) { + this.registerChangeListener = registerChangeListener; + } + + void setDelegate( ListenerRegistration>> registration) { + this.delegate = registration; + } + + boolean isClosed() { + return closed; + } + + RegisterChangeListener getRegisterChangeListener() { + return registerChangeListener; + } + + @Override + public AsyncDataChangeListener> getInstance() { + return delegate != null ? delegate.getInstance() : null; + } + + @Override + public void close() { + closed = true; + if(delegate != null) { + delegate.close(); + } + } + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardManager.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardManager.java index 157f1cb377..88f818f0fa 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardManager.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardManager.java @@ -25,6 +25,8 @@ import akka.persistence.RecoveryFailure; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; +import com.google.common.collect.Lists; +import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering; import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier; import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier; @@ -43,6 +45,7 @@ import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContex import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import scala.concurrent.duration.Duration; + import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @@ -90,6 +93,8 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { private final Collection knownModules = new HashSet<>(128); + private final DataPersistenceProvider dataPersistenceProvider; + /** * @param type defines the kind of data that goes into shards created by this shard manager. Examples of type would be * configuration or operational @@ -101,6 +106,7 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null"); this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null"); this.datastoreContext = datastoreContext; + this.dataPersistenceProvider = createDataPersistenceProvider(datastoreContext.isPersistent()); // Subscribe this actor to cluster member events cluster.subscribeToMemberEvents(getSelf()); @@ -108,6 +114,10 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { createLocalShards(); } + protected DataPersistenceProvider createDataPersistenceProvider(boolean persistent) { + return (persistent) ? new PersistentDataProvider() : new NonPersistentDataProvider(); + } + public static Props props(final String type, final ClusterWrapper cluster, final Configuration configuration, @@ -163,24 +173,33 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { LOG.debug("Initializing shard [{}]", shardName); ShardInformation shardInformation = localShards.get(shardName); if (shardInformation != null) { - shardInformation.setShardInitialized(true); + shardInformation.setActorInitialized(); } } @Override protected void handleRecover(Object message) throws Exception { - if(message instanceof SchemaContextModules){ - SchemaContextModules msg = (SchemaContextModules) message; - knownModules.clear(); - knownModules.addAll(msg.getModules()); - } else if(message instanceof RecoveryFailure){ - RecoveryFailure failure = (RecoveryFailure) message; - LOG.error(failure.cause(), "Recovery failed"); - } else if(message instanceof RecoveryCompleted){ - LOG.info("Recovery complete : {}", persistenceId()); - - // Delete all the messages from the akka journal except the last one - deleteMessages(lastSequenceNr() - 1); + if(dataPersistenceProvider.isRecoveryApplicable()) { + if (message instanceof SchemaContextModules) { + SchemaContextModules msg = (SchemaContextModules) message; + knownModules.clear(); + knownModules.addAll(msg.getModules()); + } else if (message instanceof RecoveryFailure) { + RecoveryFailure failure = (RecoveryFailure) message; + LOG.error(failure.cause(), "Recovery failed"); + } else if (message instanceof RecoveryCompleted) { + LOG.info("Recovery complete : {}", persistenceId()); + + // Delete all the messages from the akka journal except the last one + deleteMessages(lastSequenceNr() - 1); + } + } else { + if (message instanceof RecoveryCompleted) { + LOG.info("Recovery complete : {}", persistenceId()); + + // Delete all the messages from the akka journal + deleteMessages(lastSequenceNr()); + } } } @@ -192,7 +211,7 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { return; } - sendResponse(shardInformation, new Supplier() { + sendResponse(shardInformation, message.isWaitUntilInitialized(), new Supplier() { @Override public Object get() { return new LocalShardFound(shardInformation.getActor()); @@ -200,9 +219,22 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { }); } - private void sendResponse(ShardInformation shardInformation, Supplier messageSupplier) { - if (shardInformation.getActor() == null || !shardInformation.isShardInitialized()) { - getSender().tell(new ActorNotInitialized(), getSelf()); + private void sendResponse(ShardInformation shardInformation, boolean waitUntilInitialized, + final Supplier messageSupplier) { + if (!shardInformation.isShardInitialized()) { + if(waitUntilInitialized) { + final ActorRef sender = getSender(); + final ActorRef self = self(); + shardInformation.addRunnableOnInitialized(new Runnable() { + @Override + public void run() { + sender.tell(messageSupplier.get(), self); + } + }); + } else { + getSender().tell(new ActorNotInitialized(), getSelf()); + } + return; } @@ -248,15 +280,15 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { knownModules.clear(); knownModules.addAll(newModules); - persist(new SchemaContextModules(newModules), new Procedure() { + dataPersistenceProvider.persist(new SchemaContextModules(newModules), new Procedure() { @Override public void apply(SchemaContextModules param) throws Exception { LOG.info("Sending new SchemaContext to Shards"); for (ShardInformation info : localShards.values()) { - if(info.getActor() == null) { + if (info.getActor() == null) { info.setActor(getContext().actorOf(Shard.props(info.getShardId(), - info.getPeerAddresses(), datastoreContext, schemaContext), + info.getPeerAddresses(), datastoreContext, schemaContext), info.getShardId().toString())); } else { info.getActor().tell(message, getSelf()); @@ -277,7 +309,7 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { // First see if the there is a local replica for the shard final ShardInformation info = localShards.get(shardName); if (info != null) { - sendResponse(info, new Supplier() { + sendResponse(info, message.isWaitUntilInitialized(), new Supplier() { @Override public Object get() { return new PrimaryFound(info.getActorPath().toString()).toSerializable(); @@ -416,13 +448,22 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { return knownModules; } + @VisibleForTesting + DataPersistenceProvider getDataPersistenceProvider() { + return dataPersistenceProvider; + } + private class ShardInformation { private final ShardIdentifier shardId; private final String shardName; private ActorRef actor; private ActorPath actorPath; private final Map peerAddresses; - private boolean shardInitialized = false; // flag that determines if the actor is ready for business + + // flag that determines if the actor is ready for business + private boolean actorInitialized = false; + + private final List runnablesOnInitialized = Lists.newArrayList(); private ShardInformation(String shardName, ShardIdentifier shardId, Map peerAddresses) { @@ -474,11 +515,21 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { } boolean isShardInitialized() { - return shardInitialized; + return getActor() != null && actorInitialized; } - void setShardInitialized(boolean shardInitialized) { - this.shardInitialized = shardInitialized; + void setActorInitialized() { + this.actorInitialized = true; + + for(Runnable runnable: runnablesOnInitialized) { + runnable.run(); + } + + runnablesOnInitialized.clear(); + } + + void addRunnableOnInitialized(Runnable runnable) { + runnablesOnInitialized.add(runnable); } } @@ -506,7 +557,6 @@ public class ShardManager extends AbstractUntypedPersistentActorWithMetering { static class SchemaContextModules implements Serializable { private static final long serialVersionUID = 1L; - private final Set modules; SchemaContextModules(Set modules){ diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardReadTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardReadTransaction.java index 29f22b28f4..9d8f57252a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardReadTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardReadTransaction.java @@ -11,7 +11,6 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorRef; - import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats; import org.opendaylight.controller.cluster.datastore.messages.DataExists; import org.opendaylight.controller.cluster.datastore.messages.ReadData; @@ -27,17 +26,26 @@ public class ShardReadTransaction extends ShardTransaction { private final DOMStoreReadTransaction transaction; public ShardReadTransaction(DOMStoreReadTransaction transaction, ActorRef shardActor, - SchemaContext schemaContext, ShardStats shardStats, String transactionID) { - super(shardActor, schemaContext, shardStats, transactionID); + SchemaContext schemaContext, ShardStats shardStats, String transactionID, + int txnClientVersion) { + super(shardActor, schemaContext, shardStats, transactionID, txnClientVersion); this.transaction = transaction; } @Override public void handleReceive(Object message) throws Exception { - if(ReadData.SERIALIZABLE_CLASS.equals(message.getClass())) { - readData(transaction, ReadData.fromSerializable(message)); + if(message instanceof ReadData) { + readData(transaction, (ReadData) message, !SERIALIZED_REPLY); + + } else if (message instanceof DataExists) { + dataExists(transaction, (DataExists) message, !SERIALIZED_REPLY); + + } else if(ReadData.SERIALIZABLE_CLASS.equals(message.getClass())) { + readData(transaction, ReadData.fromSerializable(message), SERIALIZED_REPLY); + } else if(DataExists.SERIALIZABLE_CLASS.equals(message.getClass())) { - dataExists(transaction, DataExists.fromSerializable(message)); + dataExists(transaction, DataExists.fromSerializable(message), SERIALIZED_REPLY); + } else { super.handleReceive(message); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardReadWriteTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardReadWriteTransaction.java index 2e174ebf56..e558677ebb 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardReadWriteTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardReadWriteTransaction.java @@ -26,17 +26,26 @@ public class ShardReadWriteTransaction extends ShardWriteTransaction { private final DOMStoreReadWriteTransaction transaction; public ShardReadWriteTransaction(DOMStoreReadWriteTransaction transaction, ActorRef shardActor, - SchemaContext schemaContext, ShardStats shardStats, String transactionID) { - super(transaction, shardActor, schemaContext, shardStats, transactionID); + SchemaContext schemaContext, ShardStats shardStats, String transactionID, + int txnClientVersion) { + super(transaction, shardActor, schemaContext, shardStats, transactionID, txnClientVersion); this.transaction = transaction; } @Override public void handleReceive(Object message) throws Exception { - if(ReadData.SERIALIZABLE_CLASS.equals(message.getClass())) { - readData(transaction, ReadData.fromSerializable(message)); + if (message instanceof ReadData) { + readData(transaction, (ReadData) message, !SERIALIZED_REPLY); + + } else if (message instanceof DataExists) { + dataExists(transaction, (DataExists) message, !SERIALIZED_REPLY); + + } else if(ReadData.SERIALIZABLE_CLASS.equals(message.getClass())) { + readData(transaction, ReadData.fromSerializable(message), SERIALIZED_REPLY); + } else if(DataExists.SERIALIZABLE_CLASS.equals(message.getClass())) { - dataExists(transaction, DataExists.fromSerializable(message)); + dataExists(transaction, DataExists.fromSerializable(message), SERIALIZED_REPLY); + } else { super.handleReceive(message); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransaction.java index edaf935678..59bb4bfd77 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransaction.java @@ -15,7 +15,7 @@ import akka.actor.ReceiveTimeout; import akka.japi.Creator; import com.google.common.base.Optional; import com.google.common.util.concurrent.CheckedFuture; -import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActor; +import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActorWithMetering; import org.opendaylight.controller.cluster.datastore.exceptions.UnknownMessageException; import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats; import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction; @@ -55,26 +55,31 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; *
    • {@link org.opendaylight.controller.cluster.datastore.messages.CloseTransaction} *

      */ -public abstract class ShardTransaction extends AbstractUntypedActor { +public abstract class ShardTransaction extends AbstractUntypedActorWithMetering { + + protected static final boolean SERIALIZED_REPLY = true; private final ActorRef shardActor; private final SchemaContext schemaContext; private final ShardStats shardStats; private final String transactionID; + private final int txnClientVersion; protected ShardTransaction(ActorRef shardActor, SchemaContext schemaContext, - ShardStats shardStats, String transactionID) { + ShardStats shardStats, String transactionID, int txnClientVersion) { + super("shard-tx"); //actor name override used for metering. This does not change the "real" actor name this.shardActor = shardActor; this.schemaContext = schemaContext; this.shardStats = shardStats; this.transactionID = transactionID; + this.txnClientVersion = txnClientVersion; } public static Props props(DOMStoreTransaction transaction, ActorRef shardActor, SchemaContext schemaContext,DatastoreContext datastoreContext, ShardStats shardStats, - String transactionID) { + String transactionID, int txnClientVersion) { return Props.create(new ShardTransactionCreator(transaction, shardActor, schemaContext, - datastoreContext, shardStats, transactionID)); + datastoreContext, shardStats, transactionID, txnClientVersion)); } protected abstract DOMStoreTransaction getDOMStoreTransaction(); @@ -91,6 +96,10 @@ public abstract class ShardTransaction extends AbstractUntypedActor { return schemaContext; } + protected int getTxnClientVersion() { + return txnClientVersion; + } + @Override public void handleReceive(Object message) throws Exception { if (message.getClass().equals(CloseTransaction.SERIALIZABLE_CLASS)) { @@ -115,23 +124,24 @@ public abstract class ShardTransaction extends AbstractUntypedActor { getSelf().tell(PoisonPill.getInstance(), getSelf()); } - protected void readData(DOMStoreReadTransaction transaction,ReadData message) { + protected void readData(DOMStoreReadTransaction transaction, ReadData message, final boolean returnSerialized) { final ActorRef sender = getSender(); final ActorRef self = getSelf(); final YangInstanceIdentifier path = message.getPath(); final CheckedFuture>, ReadFailedException> future = transaction.read(path); + future.addListener(new Runnable() { @Override public void run() { try { Optional> optional = future.checkedGet(); - if (optional.isPresent()) { - sender.tell(new ReadDataReply(schemaContext,optional.get()).toSerializable(), self); - } else { - sender.tell(new ReadDataReply(schemaContext,null).toSerializable(), self); - } + ReadDataReply readDataReply = new ReadDataReply(schemaContext, optional.orNull()); + + sender.tell((returnSerialized ? readDataReply.toSerializable(): + readDataReply), self); + } catch (Exception e) { shardStats.incrementFailedReadTransactionsCount(); sender.tell(new akka.actor.Status.Failure(e), self); @@ -141,12 +151,15 @@ public abstract class ShardTransaction extends AbstractUntypedActor { }, getContext().dispatcher()); } - protected void dataExists(DOMStoreReadTransaction transaction, DataExists message) { + protected void dataExists(DOMStoreReadTransaction transaction, DataExists message, + final boolean returnSerialized) { final YangInstanceIdentifier path = message.getPath(); try { Boolean exists = transaction.exists(path).checkedGet(); - getSender().tell(new DataExistsReply(exists).toSerializable(), getSelf()); + DataExistsReply dataExistsReply = new DataExistsReply(exists); + getSender().tell(returnSerialized ? dataExistsReply.toSerializable() : + dataExistsReply, getSelf()); } catch (ReadFailedException e) { getSender().tell(new akka.actor.Status.Failure(e),getSelf()); } @@ -163,16 +176,18 @@ public abstract class ShardTransaction extends AbstractUntypedActor { final DatastoreContext datastoreContext; final ShardStats shardStats; final String transactionID; + final int txnClientVersion; ShardTransactionCreator(DOMStoreTransaction transaction, ActorRef shardActor, SchemaContext schemaContext, DatastoreContext datastoreContext, - ShardStats shardStats, String transactionID) { + ShardStats shardStats, String transactionID, int txnClientVersion) { this.transaction = transaction; this.shardActor = shardActor; this.shardStats = shardStats; this.schemaContext = schemaContext; this.datastoreContext = datastoreContext; this.transactionID = transactionID; + this.txnClientVersion = txnClientVersion; } @Override @@ -180,13 +195,13 @@ public abstract class ShardTransaction extends AbstractUntypedActor { ShardTransaction tx; if(transaction instanceof DOMStoreReadWriteTransaction) { tx = new ShardReadWriteTransaction((DOMStoreReadWriteTransaction)transaction, - shardActor, schemaContext, shardStats, transactionID); + shardActor, schemaContext, shardStats, transactionID, txnClientVersion); } else if(transaction instanceof DOMStoreReadTransaction) { tx = new ShardReadTransaction((DOMStoreReadTransaction)transaction, shardActor, - schemaContext, shardStats, transactionID); + schemaContext, shardStats, transactionID, txnClientVersion); } else { tx = new ShardWriteTransaction((DOMStoreWriteTransaction)transaction, - shardActor, schemaContext, shardStats, transactionID); + shardActor, schemaContext, shardStats, transactionID, txnClientVersion); } tx.getContext().setReceiveTimeout(datastoreContext.getShardTransactionIdleTimeout()); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransactionChain.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransactionChain.java index 943a82f6f9..78c6a558f4 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransactionChain.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransactionChain.java @@ -63,19 +63,22 @@ public class ShardTransactionChain extends AbstractUntypedActor { return getContext().actorOf( ShardTransaction.props( chain.newReadOnlyTransaction(), getShardActor(), schemaContext, datastoreContext, shardStats, - createTransaction.getTransactionId()), transactionName); + createTransaction.getTransactionId(), + createTransaction.getVersion()), transactionName); } else if (createTransaction.getTransactionType() == TransactionProxy.TransactionType.READ_WRITE.ordinal()) { return getContext().actorOf( ShardTransaction.props( chain.newReadWriteTransaction(), getShardActor(), schemaContext, datastoreContext, shardStats, - createTransaction.getTransactionId()), transactionName); + createTransaction.getTransactionId(), + createTransaction.getVersion()), transactionName); } else if (createTransaction.getTransactionType() == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) { return getContext().actorOf( ShardTransaction.props( chain.newWriteOnlyTransaction(), getShardActor(), schemaContext, datastoreContext, shardStats, - createTransaction.getTransactionId()), transactionName); + createTransaction.getTransactionId(), + createTransaction.getVersion()), transactionName); } else { throw new IllegalArgumentException ( "CreateTransaction message has unidentified transaction type=" + diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardWriteTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardWriteTransaction.java index e993e4b55c..44f2c7bd0a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardWriteTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardWriteTransaction.java @@ -11,6 +11,7 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorRef; +import akka.actor.PoisonPill; import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats; import org.opendaylight.controller.cluster.datastore.messages.DeleteData; import org.opendaylight.controller.cluster.datastore.messages.DeleteDataReply; @@ -41,8 +42,9 @@ public class ShardWriteTransaction extends ShardTransaction { private final DOMStoreWriteTransaction transaction; public ShardWriteTransaction(DOMStoreWriteTransaction transaction, ActorRef shardActor, - SchemaContext schemaContext, ShardStats shardStats, String transactionID) { - super(shardActor, schemaContext, shardStats, transactionID); + SchemaContext schemaContext, ShardStats shardStats, String transactionID, + int txnClientVersion) { + super(shardActor, schemaContext, shardStats, transactionID, txnClientVersion); this.transaction = transaction; } @@ -53,14 +55,31 @@ public class ShardWriteTransaction extends ShardTransaction { @Override public void handleReceive(Object message) throws Exception { - if(WriteData.SERIALIZABLE_CLASS.equals(message.getClass())) { - writeData(transaction, WriteData.fromSerializable(message, getSchemaContext())); + + if (message instanceof WriteData) { + writeData(transaction, (WriteData) message, !SERIALIZED_REPLY); + + } else if (message instanceof MergeData) { + mergeData(transaction, (MergeData) message, !SERIALIZED_REPLY); + + } else if (message instanceof DeleteData) { + deleteData(transaction, (DeleteData) message, !SERIALIZED_REPLY); + + } else if (message instanceof ReadyTransaction) { + readyTransaction(transaction, new ReadyTransaction(), !SERIALIZED_REPLY); + + } else if(WriteData.SERIALIZABLE_CLASS.equals(message.getClass())) { + writeData(transaction, WriteData.fromSerializable(message, getSchemaContext()), SERIALIZED_REPLY); + } else if(MergeData.SERIALIZABLE_CLASS.equals(message.getClass())) { - mergeData(transaction, MergeData.fromSerializable(message, getSchemaContext())); + mergeData(transaction, MergeData.fromSerializable(message, getSchemaContext()), SERIALIZED_REPLY); + } else if(DeleteData.SERIALIZABLE_CLASS.equals(message.getClass())) { - deleteData(transaction, DeleteData.fromSerializable(message)); + deleteData(transaction, DeleteData.fromSerializable(message), SERIALIZED_REPLY); + } else if(ReadyTransaction.SERIALIZABLE_CLASS.equals(message.getClass())) { - readyTransaction(transaction, new ReadyTransaction()); + readyTransaction(transaction, new ReadyTransaction(), SERIALIZED_REPLY); + } else if (message instanceof GetCompositedModification) { // This is here for testing only getSender().tell(new GetCompositeModificationReply( @@ -70,52 +89,67 @@ public class ShardWriteTransaction extends ShardTransaction { } } - private void writeData(DOMStoreWriteTransaction transaction, WriteData message) { + private void writeData(DOMStoreWriteTransaction transaction, WriteData message, + boolean returnSerialized) { + LOG.debug("writeData at path : {}", message.getPath()); + modification.addModification( new WriteModification(message.getPath(), message.getData(), getSchemaContext())); - if(LOG.isDebugEnabled()) { - LOG.debug("writeData at path : " + message.getPath().toString()); - } try { transaction.write(message.getPath(), message.getData()); - getSender().tell(new WriteDataReply().toSerializable(), getSelf()); + WriteDataReply writeDataReply = new WriteDataReply(); + getSender().tell(returnSerialized ? writeDataReply.toSerializable() : writeDataReply, + getSelf()); }catch(Exception e){ getSender().tell(new akka.actor.Status.Failure(e), getSelf()); } } - private void mergeData(DOMStoreWriteTransaction transaction, MergeData message) { + private void mergeData(DOMStoreWriteTransaction transaction, MergeData message, + boolean returnSerialized) { + LOG.debug("mergeData at path : {}", message.getPath()); + modification.addModification( new MergeModification(message.getPath(), message.getData(), getSchemaContext())); - if(LOG.isDebugEnabled()) { - LOG.debug("mergeData at path : " + message.getPath().toString()); - } + try { transaction.merge(message.getPath(), message.getData()); - getSender().tell(new MergeDataReply().toSerializable(), getSelf()); + MergeDataReply mergeDataReply = new MergeDataReply(); + getSender().tell(returnSerialized ? mergeDataReply.toSerializable() : mergeDataReply , + getSelf()); }catch(Exception e){ getSender().tell(new akka.actor.Status.Failure(e), getSelf()); } } - private void deleteData(DOMStoreWriteTransaction transaction, DeleteData message) { - if(LOG.isDebugEnabled()) { - LOG.debug("deleteData at path : " + message.getPath().toString()); - } + private void deleteData(DOMStoreWriteTransaction transaction, DeleteData message, + boolean returnSerialized) { + LOG.debug("deleteData at path : {}", message.getPath()); + modification.addModification(new DeleteModification(message.getPath())); try { transaction.delete(message.getPath()); - getSender().tell(new DeleteDataReply().toSerializable(), getSelf()); + DeleteDataReply deleteDataReply = new DeleteDataReply(); + getSender().tell(returnSerialized ? deleteDataReply.toSerializable() : deleteDataReply, + getSelf()); }catch(Exception e){ getSender().tell(new akka.actor.Status.Failure(e), getSelf()); } } - private void readyTransaction(DOMStoreWriteTransaction transaction, ReadyTransaction message) { + private void readyTransaction(DOMStoreWriteTransaction transaction, ReadyTransaction message, + boolean returnSerialized) { + String transactionID = getTransactionID(); + + LOG.debug("readyTransaction : {}", transactionID); + DOMStoreThreePhaseCommitCohort cohort = transaction.ready(); - getShardActor().forward(new ForwardedReadyTransaction(getTransactionID(), cohort, modification), - getContext()); + getShardActor().forward(new ForwardedReadyTransaction(transactionID, getTxnClientVersion(), + cohort, modification, returnSerialized), getContext()); + + // The shard will handle the commit from here so we're no longer needed - self-destruct. + getSelf().tell(PoisonPill.getInstance(), getSelf()); } // These classes are in here for test purposes only diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxy.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxy.java index b467ee4ddb..87959efe8a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxy.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxy.java @@ -9,71 +9,209 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorSelection; -import akka.dispatch.Futures; +import akka.dispatch.OnComplete; +import com.google.common.base.Preconditions; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain; import org.opendaylight.controller.cluster.datastore.utils.ActorContext; +import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException; import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction; import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction; import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain; import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction; -import scala.concurrent.Await; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import scala.concurrent.Future; - -import java.util.Collections; -import java.util.List; +import scala.concurrent.Promise; /** * TransactionChainProxy acts as a proxy for a DOMStoreTransactionChain created on a remote shard */ -public class TransactionChainProxy implements DOMStoreTransactionChain{ +public class TransactionChainProxy implements DOMStoreTransactionChain { + + private static final Logger LOG = LoggerFactory.getLogger(TransactionChainProxy.class); + + private interface State { + boolean isReady(); + + List> getPreviousReadyFutures(); + } + + private static class Allocated implements State { + private final ChainedTransactionProxy transaction; + + Allocated(ChainedTransactionProxy transaction) { + this.transaction = transaction; + } + + @Override + public boolean isReady() { + return transaction.isReady(); + } + + @Override + public List> getPreviousReadyFutures() { + return transaction.getReadyFutures(); + } + } + + private static abstract class AbstractDefaultState implements State { + @Override + public List> getPreviousReadyFutures() { + return Collections.emptyList(); + } + } + + private static final State IDLE_STATE = new AbstractDefaultState() { + @Override + public boolean isReady() { + return true; + } + }; + + private static final State CLOSED_STATE = new AbstractDefaultState() { + @Override + public boolean isReady() { + throw new TransactionChainClosedException("Transaction chain has been closed"); + } + }; + + private static final AtomicInteger counter = new AtomicInteger(0); + private final ActorContext actorContext; private final String transactionChainId; - private volatile List> cohortFutures = Collections.emptyList(); + private volatile State currentState = IDLE_STATE; public TransactionChainProxy(ActorContext actorContext) { this.actorContext = actorContext; - transactionChainId = actorContext.getCurrentMemberName() + "-" + System.currentTimeMillis(); + transactionChainId = actorContext.getCurrentMemberName() + "-txn-chain-" + counter.incrementAndGet(); + } + + public String getTransactionChainId() { + return transactionChainId; } @Override public DOMStoreReadTransaction newReadOnlyTransaction() { - return new TransactionProxy(actorContext, - TransactionProxy.TransactionType.READ_ONLY, this); + State localState = currentState; + checkReadyState(localState); + + return new ChainedTransactionProxy(actorContext, TransactionProxy.TransactionType.READ_ONLY, + transactionChainId, localState.getPreviousReadyFutures()); } @Override public DOMStoreReadWriteTransaction newReadWriteTransaction() { - return new TransactionProxy(actorContext, - TransactionProxy.TransactionType.READ_WRITE, this); + return allocateWriteTransaction(TransactionProxy.TransactionType.READ_WRITE); } @Override public DOMStoreWriteTransaction newWriteOnlyTransaction() { - return new TransactionProxy(actorContext, - TransactionProxy.TransactionType.WRITE_ONLY, this); + return allocateWriteTransaction(TransactionProxy.TransactionType.WRITE_ONLY); } @Override public void close() { + currentState = CLOSED_STATE; + // Send a close transaction chain request to each and every shard actorContext.broadcast(new CloseTransactionChain(transactionChainId)); } - public String getTransactionChainId() { - return transactionChainId; + private ChainedTransactionProxy allocateWriteTransaction(TransactionProxy.TransactionType type) { + State localState = currentState; + + checkReadyState(localState); + + // Pass the ready Futures from the previous Tx. + ChainedTransactionProxy txProxy = new ChainedTransactionProxy(actorContext, type, + transactionChainId, localState.getPreviousReadyFutures()); + + currentState = new Allocated(txProxy); + + return txProxy; } - public void onTransactionReady(List> cohortFutures){ - this.cohortFutures = cohortFutures; + private void checkReadyState(State state) { + Preconditions.checkState(state.isReady(), "Previous transaction is not ready yet"); } - public void waitTillCurrentTransactionReady(){ - try { - Await.result(Futures - .sequence(this.cohortFutures, actorContext.getActorSystem().dispatcher()), - actorContext.getOperationDuration()); - } catch (Exception e) { - throw new IllegalStateException("Failed when waiting for transaction on a chain to become ready", e); + private static class ChainedTransactionProxy extends TransactionProxy { + + /** + * Stores the ready Futures from the previous Tx in the chain. + */ + private final List> previousReadyFutures; + + /** + * Stores the ready Futures from this transaction when it is readied. + */ + private volatile List> readyFutures; + + private ChainedTransactionProxy(ActorContext actorContext, TransactionType transactionType, + String transactionChainId, List> previousReadyFutures) { + super(actorContext, transactionType, transactionChainId); + this.previousReadyFutures = previousReadyFutures; + } + + List> getReadyFutures() { + return readyFutures; + } + + boolean isReady() { + return readyFutures != null; + } + + @Override + protected void onTransactionReady(List> readyFutures) { + LOG.debug("onTransactionReady {} pending readyFutures size {} chain {}", getIdentifier(), + readyFutures.size(), getTransactionChainId()); + this.readyFutures = readyFutures; + } + + /** + * This method is overridden to ensure the previous Tx's ready operations complete + * before we create the next shard Tx in the chain to avoid creation failures if the + * previous Tx's ready operations haven't completed yet. + */ + @Override + protected Future sendCreateTransaction(final ActorSelection shard, + final Object serializedCreateMessage) { + + // Check if there are any previous ready Futures, otherwise let the super class handle it. + if(previousReadyFutures.isEmpty()) { + return super.sendCreateTransaction(shard, serializedCreateMessage); + } + + // Combine the ready Futures into 1. + Future> combinedFutures = akka.dispatch.Futures.sequence( + previousReadyFutures, getActorContext().getActorSystem().dispatcher()); + + // Add a callback for completion of the combined Futures. + final Promise createTxPromise = akka.dispatch.Futures.promise(); + OnComplete> onComplete = new OnComplete>() { + @Override + public void onComplete(Throwable failure, Iterable notUsed) { + if(failure != null) { + // A Ready Future failed so fail the returned Promise. + createTxPromise.failure(failure); + } else { + LOG.debug("Previous Tx readied - sending CreateTransaction for {} on chain {}", + getIdentifier(), getTransactionChainId()); + + // Send the CreateTx message and use the resulting Future to complete the + // returned Promise. + createTxPromise.completeWith(getActorContext().executeOperationAsync(shard, + serializedCreateMessage)); + } + } + }; + + combinedFutures.onComplete(onComplete, getActorContext().getActorSystem().dispatcher()); + + return createTxPromise.future(); } } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionProxy.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionProxy.java index ec198510d3..ebed05b6a7 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionProxy.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionProxy.java @@ -9,8 +9,8 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorSelection; +import akka.dispatch.Mapper; import akka.dispatch.OnComplete; - import com.google.common.annotations.VisibleForTesting; import com.google.common.base.FinalizablePhantomReference; import com.google.common.base.FinalizableReferenceQueue; @@ -18,10 +18,18 @@ import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.SettableFuture; - -import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import javax.annotation.concurrent.GuardedBy; +import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException; import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier; import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction; import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction; @@ -46,17 +54,9 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import scala.Function1; import scala.concurrent.Future; -import scala.runtime.AbstractFunction1; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; +import scala.concurrent.Promise; +import scala.concurrent.duration.FiniteDuration; /** * TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard @@ -72,18 +72,14 @@ import java.util.concurrent.atomic.AtomicLong; */ public class TransactionProxy implements DOMStoreReadWriteTransaction { - private final TransactionChainProxy transactionChainProxy; - - - - public enum TransactionType { + public static enum TransactionType { READ_ONLY, WRITE_ONLY, READ_WRITE } - static Function1 SAME_FAILURE_TRANSFORMER = new AbstractFunction1< - Throwable, Throwable>() { + static final Mapper SAME_FAILURE_TRANSFORMER = + new Mapper() { @Override public Throwable apply(Throwable failure) { return failure; @@ -92,9 +88,13 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { private static final AtomicLong counter = new AtomicLong(); - private static final Logger - LOG = LoggerFactory.getLogger(TransactionProxy.class); + private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class); + /** + * Time interval in between transaction create retries. + */ + private static final FiniteDuration CREATE_TX_TRY_INTERVAL = + FiniteDuration.create(1, TimeUnit.SECONDS); /** * Used to enqueue the PhantomReferences for read-only TransactionProxy instances. The @@ -173,36 +173,31 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { private List remoteTransactionActors; private AtomicBoolean remoteTransactionActorsMB; - private final Map remoteTransactionPaths = new HashMap<>(); + /** + * Stores the create transaction results per shard. + */ + private final Map txFutureCallbackMap = new HashMap<>(); private final TransactionType transactionType; private final ActorContext actorContext; private final TransactionIdentifier identifier; + private final String transactionChainId; private final SchemaContext schemaContext; private boolean inReadyState; public TransactionProxy(ActorContext actorContext, TransactionType transactionType) { - this(actorContext, transactionType, null); - } - - @VisibleForTesting - List> getRecordedOperationFutures() { - List> recordedOperationFutures = Lists.newArrayList(); - for(TransactionContext transactionContext : remoteTransactionPaths.values()) { - recordedOperationFutures.addAll(transactionContext.getRecordedOperationFutures()); - } - - return recordedOperationFutures; + this(actorContext, transactionType, ""); } - public TransactionProxy(ActorContext actorContext, TransactionType transactionType, TransactionChainProxy transactionChainProxy) { + public TransactionProxy(ActorContext actorContext, TransactionType transactionType, + String transactionChainId) { this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null"); this.transactionType = Preconditions.checkNotNull(transactionType, "transactionType should not be null"); this.schemaContext = Preconditions.checkNotNull(actorContext.getSchemaContext(), "schemaContext should not be null"); - this.transactionChainProxy = transactionChainProxy; + this.transactionChainId = transactionChainId; String memberName = actorContext.getCurrentMemberName(); if(memberName == null){ @@ -224,9 +219,33 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { new TransactionProxyCleanupPhantomReference(this); phantomReferenceCache.put(cleanup, cleanup); } - if(LOG.isDebugEnabled()) { - LOG.debug("Created txn {} of type {}", identifier, transactionType); + + LOG.debug("Created txn {} of type {} on chain {}", identifier, transactionType, transactionChainId); + } + + @VisibleForTesting + List> getRecordedOperationFutures() { + List> recordedOperationFutures = Lists.newArrayList(); + for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) { + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + if(transactionContext != null) { + recordedOperationFutures.addAll(transactionContext.getRecordedOperationFutures()); + } + } + + return recordedOperationFutures; + } + + @VisibleForTesting + boolean hasTransactionContext() { + for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) { + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + if(transactionContext != null) { + return true; + } } + + return false; } @Override @@ -236,26 +255,82 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY, "Read operation on write-only transaction is not allowed"); - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} read {}", identifier, path); + LOG.debug("Tx {} read {}", identifier, path); + + TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path); + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + + CheckedFuture>, ReadFailedException> future; + if(transactionContext != null) { + future = transactionContext.readData(path); + } else { + // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future + // callback to be executed after the Tx is created. + final SettableFuture>> proxyFuture = SettableFuture.create(); + txFutureCallback.addTxOperationOnComplete(new TransactionOperation() { + @Override + public void invoke(TransactionContext transactionContext) { + Futures.addCallback(transactionContext.readData(path), + new FutureCallback>>() { + @Override + public void onSuccess(Optional> data) { + proxyFuture.set(data); + } + + @Override + public void onFailure(Throwable t) { + proxyFuture.setException(t); + } + }); + } + }); + + future = MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER); } - createTransactionIfMissing(actorContext, path); - return transactionContext(path).readData(path); + return future; } @Override - public CheckedFuture exists(YangInstanceIdentifier path) { + public CheckedFuture exists(final YangInstanceIdentifier path) { Preconditions.checkState(transactionType != TransactionType.WRITE_ONLY, "Exists operation on write-only transaction is not allowed"); - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} exists {}", identifier, path); + LOG.debug("Tx {} exists {}", identifier, path); + + TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path); + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + + CheckedFuture future; + if(transactionContext != null) { + future = transactionContext.dataExists(path); + } else { + // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future + // callback to be executed after the Tx is created. + final SettableFuture proxyFuture = SettableFuture.create(); + txFutureCallback.addTxOperationOnComplete(new TransactionOperation() { + @Override + public void invoke(TransactionContext transactionContext) { + Futures.addCallback(transactionContext.dataExists(path), + new FutureCallback() { + @Override + public void onSuccess(Boolean exists) { + proxyFuture.set(exists); + } + + @Override + public void onFailure(Throwable t) { + proxyFuture.setException(t); + } + }); + } + }); + + future = MappingCheckedFuture.create(proxyFuture, ReadFailedException.MAPPER); } - createTransactionIfMissing(actorContext, path); - return transactionContext(path).dataExists(path); + return future; } private void checkModificationState() { @@ -266,41 +341,72 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { } @Override - public void write(YangInstanceIdentifier path, NormalizedNode data) { + public void write(final YangInstanceIdentifier path, final NormalizedNode data) { checkModificationState(); - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} write {}", identifier, path); - } - createTransactionIfMissing(actorContext, path); + LOG.debug("Tx {} write {}", identifier, path); - transactionContext(path).writeData(path, data); + TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path); + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + if(transactionContext != null) { + transactionContext.writeData(path, data); + } else { + // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future + // callback to be executed after the Tx is created. + txFutureCallback.addTxOperationOnComplete(new TransactionOperation() { + @Override + public void invoke(TransactionContext transactionContext) { + transactionContext.writeData(path, data); + } + }); + } } @Override - public void merge(YangInstanceIdentifier path, NormalizedNode data) { + public void merge(final YangInstanceIdentifier path, final NormalizedNode data) { checkModificationState(); - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} merge {}", identifier, path); - } - createTransactionIfMissing(actorContext, path); + LOG.debug("Tx {} merge {}", identifier, path); - transactionContext(path).mergeData(path, data); + TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path); + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + if(transactionContext != null) { + transactionContext.mergeData(path, data); + } else { + // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future + // callback to be executed after the Tx is created. + txFutureCallback.addTxOperationOnComplete(new TransactionOperation() { + @Override + public void invoke(TransactionContext transactionContext) { + transactionContext.mergeData(path, data); + } + }); + } } @Override - public void delete(YangInstanceIdentifier path) { + public void delete(final YangInstanceIdentifier path) { checkModificationState(); - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} delete {}", identifier, path); - } - createTransactionIfMissing(actorContext, path); - transactionContext(path).deleteData(path); + LOG.debug("Tx {} delete {}", identifier, path); + + TransactionFutureCallback txFutureCallback = getOrCreateTxFutureCallback(path); + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + if(transactionContext != null) { + transactionContext.deleteData(path); + } else { + // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future + // callback to be executed after the Tx is created. + txFutureCallback.addTxOperationOnComplete(new TransactionOperation() { + @Override + public void invoke(TransactionContext transactionContext) { + transactionContext.deleteData(path); + } + }); + } } @Override @@ -310,29 +416,60 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { inReadyState = true; - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} Trying to get {} transactions ready for commit", identifier, - remoteTransactionPaths.size()); - } + LOG.debug("Tx {} Readying {} transactions for commit", identifier, + txFutureCallbackMap.size()); + List> cohortFutures = Lists.newArrayList(); - for(TransactionContext transactionContext : remoteTransactionPaths.values()) { + for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) { + + LOG.debug("Tx {} Readying transaction for shard {} chain {}", identifier, + txFutureCallback.getShardName(), transactionChainId); - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} Readying transaction for shard {}", identifier, - transactionContext.getShardName()); + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + if(transactionContext != null) { + cohortFutures.add(transactionContext.readyTransaction()); + } else { + // The shard Tx hasn't been created yet so create a promise to ready the Tx later + // after it's created. + final Promise cohortPromise = akka.dispatch.Futures.promise(); + txFutureCallback.addTxOperationOnComplete(new TransactionOperation() { + @Override + public void invoke(TransactionContext transactionContext) { + cohortPromise.completeWith(transactionContext.readyTransaction()); + } + }); + + cohortFutures.add(cohortPromise.future()); } - cohortFutures.add(transactionContext.readyTransaction()); } - if(transactionChainProxy != null){ - transactionChainProxy.onTransactionReady(cohortFutures); - } + onTransactionReady(cohortFutures); return new ThreePhaseCommitCohortProxy(actorContext, cohortFutures, identifier.toString()); } + /** + * Method for derived classes to be notified when the transaction has been readied. + * + * @param cohortFutures the cohort Futures for each shard transaction. + */ + protected void onTransactionReady(List> cohortFutures) { + } + + /** + * Method called to send a CreateTransaction message to a shard. + * + * @param shard the shard actor to send to + * @param serializedCreateMessage the serialized message to send + * @return the response Future + */ + protected Future sendCreateTransaction(ActorSelection shard, + Object serializedCreateMessage) { + return actorContext.executeOperationAsync(shard, serializedCreateMessage); + } + @Override public Object getIdentifier() { return this.identifier; @@ -340,11 +477,21 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { @Override public void close() { - for(TransactionContext transactionContext : remoteTransactionPaths.values()) { - transactionContext.closeTransaction(); + for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) { + TransactionContext transactionContext = txFutureCallback.getTransactionContext(); + if(transactionContext != null) { + transactionContext.closeTransaction(); + } else { + txFutureCallback.addTxOperationOnComplete(new TransactionOperation() { + @Override + public void invoke(TransactionContext transactionContext) { + transactionContext.closeTransaction(); + } + }); + } } - remoteTransactionPaths.clear(); + txFutureCallbackMap.clear(); if(transactionType == TransactionType.READ_ONLY) { remoteTransactionActors.clear(); @@ -352,90 +499,225 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { } } - private TransactionContext transactionContext(YangInstanceIdentifier path){ + private String shardNameFromIdentifier(YangInstanceIdentifier path){ + return ShardStrategyFactory.getStrategy(path).findShard(path); + } + + private TransactionFutureCallback getOrCreateTxFutureCallback(YangInstanceIdentifier path) { String shardName = shardNameFromIdentifier(path); - return remoteTransactionPaths.get(shardName); + TransactionFutureCallback txFutureCallback = txFutureCallbackMap.get(shardName); + if(txFutureCallback == null) { + Future findPrimaryFuture = actorContext.findPrimaryShardAsync(shardName); + + final TransactionFutureCallback newTxFutureCallback = + new TransactionFutureCallback(shardName); + + txFutureCallback = newTxFutureCallback; + txFutureCallbackMap.put(shardName, txFutureCallback); + + findPrimaryFuture.onComplete(new OnComplete() { + @Override + public void onComplete(Throwable failure, ActorSelection primaryShard) { + if(failure != null) { + newTxFutureCallback.onComplete(failure, null); + } else { + newTxFutureCallback.setPrimaryShard(primaryShard); + } + } + }, actorContext.getActorSystem().dispatcher()); + } + + return txFutureCallback; } - private String shardNameFromIdentifier(YangInstanceIdentifier path){ - return ShardStrategyFactory.getStrategy(path).findShard(path); + public String getTransactionChainId() { + return transactionChainId; + } + + protected ActorContext getActorContext() { + return actorContext; + } + + /** + * Interface for a transaction operation to be invoked later. + */ + private static interface TransactionOperation { + void invoke(TransactionContext transactionContext); } - private void createTransactionIfMissing(ActorContext actorContext, - YangInstanceIdentifier path) { + /** + * Implements a Future OnComplete callback for a CreateTransaction message. This class handles + * retries, up to a limit, if the shard doesn't have a leader yet. This is done by scheduling a + * retry task after a short delay. + *

      + * The end result from a completed CreateTransaction message is a TransactionContext that is + * used to perform transaction operations. Transaction operations that occur before the + * CreateTransaction completes are cache and executed once the CreateTransaction completes, + * successfully or not. + */ + private class TransactionFutureCallback extends OnComplete { + + /** + * The list of transaction operations to execute once the CreateTransaction completes. + */ + @GuardedBy("txOperationsOnComplete") + private final List txOperationsOnComplete = Lists.newArrayList(); + + /** + * The TransactionContext resulting from the CreateTransaction reply. + */ + private volatile TransactionContext transactionContext; + + /** + * The target primary shard. + */ + private volatile ActorSelection primaryShard; + + private volatile int createTxTries = (int) (actorContext.getDatastoreContext(). + getShardLeaderElectionTimeout().duration().toMillis() / + CREATE_TX_TRY_INTERVAL.toMillis()); + + private final String shardName; + + TransactionFutureCallback(String shardName) { + this.shardName = shardName; + } + + String getShardName() { + return shardName; + } - if(transactionChainProxy != null){ - transactionChainProxy.waitTillCurrentTransactionReady(); + TransactionContext getTransactionContext() { + return transactionContext; } - String shardName = ShardStrategyFactory.getStrategy(path).findShard(path); - TransactionContext transactionContext = - remoteTransactionPaths.get(shardName); + /** + * Sets the target primary shard and initiates a CreateTransaction try. + */ + void setPrimaryShard(ActorSelection primaryShard) { + LOG.debug("Tx {} Primary shard found - trying create transaction", identifier); - if (transactionContext != null) { - // A transaction already exists with that shard - return; + this.primaryShard = primaryShard; + tryCreateTransaction(); } - try { - Optional primaryShard = actorContext.findPrimaryShard(shardName); - if (!primaryShard.isPresent()) { - throw new PrimaryNotFoundException("Primary could not be found for shard " + shardName); + /** + * Adds a TransactionOperation to be executed after the CreateTransaction completes. + */ + void addTxOperationOnComplete(TransactionOperation operation) { + synchronized(txOperationsOnComplete) { + if(transactionContext == null) { + LOG.debug("Tx {} Adding operation on complete {}", identifier); + + txOperationsOnComplete.add(operation); + } else { + operation.invoke(transactionContext); + } } + } - Object response = actorContext.executeOperation(primaryShard.get(), - new CreateTransaction(identifier.toString(), this.transactionType.ordinal(), + /** + * Performs a CreateTransaction try async. + */ + private void tryCreateTransaction() { + Future createTxFuture = sendCreateTransaction(primaryShard, + new CreateTransaction(identifier.toString(), + TransactionProxy.this.transactionType.ordinal(), getTransactionChainId()).toSerializable()); - if (response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)) { - CreateTransactionReply reply = - CreateTransactionReply.fromSerializable(response); - String transactionPath = reply.getTransactionPath(); + createTxFuture.onComplete(this, actorContext.getActorSystem().dispatcher()); + } - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} Received transaction path = {}", identifier, transactionPath); + @Override + public void onComplete(Throwable failure, Object response) { + if(failure instanceof NoShardLeaderException) { + // There's no leader for the shard yet - schedule and try again, unless we're out + // of retries. Note: createTxTries is volatile as it may be written by different + // threads however not concurrently, therefore decrementing it non-atomically here + // is ok. + if(--createTxTries > 0) { + LOG.debug("Tx {} Shard {} has no leader yet - scheduling create Tx retry", + identifier, shardName); + + actorContext.getActorSystem().scheduler().scheduleOnce(CREATE_TX_TRY_INTERVAL, + new Runnable() { + @Override + public void run() { + tryCreateTransaction(); + } + }, actorContext.getActorSystem().dispatcher()); + return; } - ActorSelection transactionActor = actorContext.actorSelection(transactionPath); + } - if (transactionType == TransactionType.READ_ONLY) { - // Add the actor to the remoteTransactionActors list for access by the - // cleanup PhantonReference. - remoteTransactionActors.add(transactionActor); + // Create the TransactionContext from the response or failure and execute delayed + // TransactionOperations. This entire section is done atomically (ie synchronized) with + // respect to #addTxOperationOnComplete to handle timing issues and ensure no + // TransactionOperation is missed and that they are processed in the order they occurred. + synchronized(txOperationsOnComplete) { + // Store the new TransactionContext locally until we've completed invoking the + // TransactionOperations. This avoids thread timing issues which could cause + // out-of-order TransactionOperations. Eg, on a modification operation, if the + // TransactionContext is non-null, then we directly call the TransactionContext. + // However, at the same time, the code may be executing the cached + // TransactionOperations. So to avoid thus timing, we don't publish the + // TransactionContext until after we've executed all cached TransactionOperations. + TransactionContext localTransactionContext; + if(failure != null) { + LOG.debug("Tx {} Creating NoOpTransaction because of error: {}", identifier, + failure.getMessage()); + + localTransactionContext = new NoOpTransactionContext(failure, identifier); + } else if (response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)) { + localTransactionContext = createValidTransactionContext( + CreateTransactionReply.fromSerializable(response)); + } else { + IllegalArgumentException exception = new IllegalArgumentException(String.format( + "Invalid reply type %s for CreateTransaction", response.getClass())); + + localTransactionContext = new NoOpTransactionContext(exception, identifier); + } - // Write to the memory barrier volatile to publish the above update to the - // remoteTransactionActors list for thread visibility. - remoteTransactionActorsMB.set(true); + for(TransactionOperation oper: txOperationsOnComplete) { + oper.invoke(localTransactionContext); } - transactionContext = new TransactionContextImpl(shardName, transactionPath, - transactionActor, identifier, actorContext, schemaContext); + txOperationsOnComplete.clear(); - remoteTransactionPaths.put(shardName, transactionContext); - } else { - throw new IllegalArgumentException(String.format( - "Invalid reply type {} for CreateTransaction", response.getClass())); - } - } catch (Exception e) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} Creating NoOpTransaction because of : {}", identifier, e.getMessage()); + // We're done invoking the TransactionOperations so we can now publish the + // TransactionContext. + transactionContext = localTransactionContext; } - remoteTransactionPaths - .put(shardName, new NoOpTransactionContext(shardName, e, identifier)); } - } - public String getTransactionChainId() { - if(transactionChainProxy == null){ - return ""; + private TransactionContext createValidTransactionContext(CreateTransactionReply reply) { + String transactionPath = reply.getTransactionPath(); + + LOG.debug("Tx {} Received transaction actor path {}", identifier, transactionPath); + + ActorSelection transactionActor = actorContext.actorSelection(transactionPath); + + if (transactionType == TransactionType.READ_ONLY) { + // Add the actor to the remoteTransactionActors list for access by the + // cleanup PhantonReference. + remoteTransactionActors.add(transactionActor); + + // Write to the memory barrier volatile to publish the above update to the + // remoteTransactionActors list for thread visibility. + remoteTransactionActorsMB.set(true); + } + + // TxActor is always created where the leader of the shard is. + // Check if TxActor is created in the same node + boolean isTxActorLocal = actorContext.isPathLocal(transactionPath); + + return new TransactionContextImpl(transactionPath, transactionActor, identifier, + actorContext, schemaContext, isTxActorLocal, reply.getVersion()); } - return transactionChainProxy.getTransactionChainId(); } - private interface TransactionContext { - String getShardName(); - void closeTransaction(); Future readyTransaction(); @@ -457,19 +739,12 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { private static abstract class AbstractTransactionContext implements TransactionContext { protected final TransactionIdentifier identifier; - protected final String shardName; protected final List> recordedOperationFutures = Lists.newArrayList(); - AbstractTransactionContext(String shardName, TransactionIdentifier identifier) { - this.shardName = shardName; + AbstractTransactionContext(TransactionIdentifier identifier) { this.identifier = identifier; } - @Override - public String getShardName() { - return shardName; - } - @Override public List> getRecordedOperationFutures() { return recordedOperationFutures; @@ -481,17 +756,21 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { private final ActorContext actorContext; private final SchemaContext schemaContext; - private final String actorPath; + private final String transactionPath; private final ActorSelection actor; - - private TransactionContextImpl(String shardName, String actorPath, - ActorSelection actor, TransactionIdentifier identifier, ActorContext actorContext, - SchemaContext schemaContext) { - super(shardName, identifier); - this.actorPath = actorPath; + private final boolean isTxActorLocal; + private final int remoteTransactionVersion; + + private TransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier, + ActorContext actorContext, SchemaContext schemaContext, + boolean isTxActorLocal, int remoteTransactionVersion) { + super(identifier); + this.transactionPath = transactionPath; this.actor = actor; this.actorContext = actorContext; this.schemaContext = schemaContext; + this.isTxActorLocal = isTxActorLocal; + this.remoteTransactionVersion = remoteTransactionVersion; } private ActorSelection getActor() { @@ -500,22 +779,21 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { @Override public void closeTransaction() { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} closeTransaction called", identifier); - } + LOG.debug("Tx {} closeTransaction called", identifier); + actorContext.sendOperationAsync(getActor(), new CloseTransaction().toSerializable()); } @Override public Future readyTransaction() { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending", + LOG.debug("Tx {} readyTransaction called with {} previous recorded operations pending", identifier, recordedOperationFutures.size()); - } + // Send the ReadyTransaction message to the Tx actor. + ReadyTransaction readyTransaction = new ReadyTransaction(); final Future replyFuture = actorContext.executeOperationAsync(getActor(), - new ReadyTransaction().toSerializable()); + isTxActorLocal ? readyTransaction : readyTransaction.toSerializable()); // Combine all the previously recorded put/merge/delete operation reply Futures and the // ReadyTransactionReply Future into one Future. If any one fails then the combined @@ -533,13 +811,12 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { // Transform the combined Future into a Future that returns the cohort actor path from // the ReadyTransactionReply. That's the end result of the ready operation. - return combinedFutures.transform(new AbstractFunction1, ActorSelection>() { + return combinedFutures.transform(new Mapper, ActorSelection>() { @Override - public ActorSelection apply(Iterable notUsed) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded", + public ActorSelection checkedApply(Iterable notUsed) { + LOG.debug("Tx {} readyTransaction: pending recorded operations succeeded", identifier); - } + // At this point all the Futures succeeded and we need to extract the cohort // actor path from the ReadyTransactionReply. For the recorded operations, they // don't return any data so we're only interested that they completed @@ -549,15 +826,28 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { // Note the Future get call here won't block as it's complete. Object serializedReadyReply = replyFuture.value().get().get(); - if(serializedReadyReply.getClass().equals( - ReadyTransactionReply.SERIALIZABLE_CLASS)) { - ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable( - serializedReadyReply); + if (serializedReadyReply instanceof ReadyTransactionReply) { + return actorContext.actorSelection(((ReadyTransactionReply)serializedReadyReply).getCohortPath()); + + } else if(serializedReadyReply.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) { + ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(serializedReadyReply); + String cohortPath = reply.getCohortPath(); + + // In Helium we used to return the local path of the actor which represented + // a remote ThreePhaseCommitCohort. The local path would then be converted to + // a remote path using this resolvePath method. To maintain compatibility with + // a Helium node we need to continue to do this conversion. + // At some point in the future when upgrades from Helium are not supported + // we could remove this code to resolvePath and just use the cohortPath as the + // resolved cohortPath + if(TransactionContextImpl.this.remoteTransactionVersion < CreateTransaction.HELIUM_1_VERSION) { + cohortPath = actorContext.resolvePath(transactionPath, cohortPath); + } + + return actorContext.actorSelection(cohortPath); - return actorContext.actorSelection(reply.getCohortPath()); } else { // Throwing an exception here will fail the Future. - throw new IllegalArgumentException(String.format("Invalid reply type {}", serializedReadyReply.getClass())); } @@ -567,38 +857,37 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { @Override public void deleteData(YangInstanceIdentifier path) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} deleteData called path = {}", identifier, path); - } + LOG.debug("Tx {} deleteData called path = {}", identifier, path); + + DeleteData deleteData = new DeleteData(path); recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(), - new DeleteData(path).toSerializable())); + isTxActorLocal ? deleteData : deleteData.toSerializable())); } @Override public void mergeData(YangInstanceIdentifier path, NormalizedNode data) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} mergeData called path = {}", identifier, path); - } + LOG.debug("Tx {} mergeData called path = {}", identifier, path); + + MergeData mergeData = new MergeData(path, data, schemaContext); recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(), - new MergeData(path, data, schemaContext).toSerializable())); + isTxActorLocal ? mergeData : mergeData.toSerializable())); } @Override public void writeData(YangInstanceIdentifier path, NormalizedNode data) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} writeData called path = {}", identifier, path); - } + LOG.debug("Tx {} writeData called path = {}", identifier, path); + + WriteData writeData = new WriteData(path, data, schemaContext); recordedOperationFutures.add(actorContext.executeOperationAsync(getActor(), - new WriteData(path, data, schemaContext).toSerializable())); + isTxActorLocal ? writeData : writeData.toSerializable())); } @Override public CheckedFuture>, ReadFailedException> readData( final YangInstanceIdentifier path) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} readData called path = {}", identifier, path); - } + LOG.debug("Tx {} readData called path = {}", identifier, path); + final SettableFuture>> returnFuture = SettableFuture.create(); // If there were any previous recorded put/merge/delete operation reply Futures then we @@ -608,10 +897,9 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { if(recordedOperationFutures.isEmpty()) { finishReadData(path, returnFuture); } else { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} readData: verifying {} previous recorded operations", + LOG.debug("Tx {} readData: verifying {} previous recorded operations", identifier, recordedOperationFutures.size()); - } + // Note: we make a copy of recordedOperationFutures to be on the safe side in case // Futures#sequence accesses the passed List on a different thread, as // recordedOperationFutures is not synchronized. @@ -619,15 +907,14 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { Future> combinedFutures = akka.dispatch.Futures.sequence( Lists.newArrayList(recordedOperationFutures), actorContext.getActorSystem().dispatcher()); + OnComplete> onComplete = new OnComplete>() { @Override public void onComplete(Throwable failure, Iterable notUsed) throws Throwable { if(failure != null) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} readData: a recorded operation failed: {}", + LOG.debug("Tx {} readData: a recorded operation failed: {}", identifier, failure); - } returnFuture.setException(new ReadFailedException( "The read could not be performed because a previous put, merge," + "or delete operation failed", failure)); @@ -646,42 +933,39 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { private void finishReadData(final YangInstanceIdentifier path, final SettableFuture>> returnFuture) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} finishReadData called path = {}", identifier, path); - } + LOG.debug("Tx {} finishReadData called path = {}", identifier, path); + OnComplete onComplete = new OnComplete() { @Override public void onComplete(Throwable failure, Object readResponse) throws Throwable { if(failure != null) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} read operation failed: {}", identifier, failure); - } + LOG.debug("Tx {} read operation failed: {}", identifier, failure); returnFuture.setException(new ReadFailedException( "Error reading data for path " + path, failure)); } else { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} read operation succeeded", identifier, failure); - } - if (readResponse.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) { - ReadDataReply reply = ReadDataReply.fromSerializable(schemaContext, - path, readResponse); - if (reply.getNormalizedNode() == null) { - returnFuture.set(Optional.>absent()); - } else { - returnFuture.set(Optional.>of( - reply.getNormalizedNode())); - } + LOG.debug("Tx {} read operation succeeded", identifier, failure); + + if (readResponse instanceof ReadDataReply) { + ReadDataReply reply = (ReadDataReply) readResponse; + returnFuture.set(Optional.>fromNullable(reply.getNormalizedNode())); + + } else if (readResponse.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) { + ReadDataReply reply = ReadDataReply.fromSerializable(schemaContext, path, readResponse); + returnFuture.set(Optional.>fromNullable(reply.getNormalizedNode())); + } else { returnFuture.setException(new ReadFailedException( - "Invalid response reading data for path " + path)); + "Invalid response reading data for path " + path)); } } } }; + ReadData readData = new ReadData(path); Future readFuture = actorContext.executeOperationAsync(getActor(), - new ReadData(path).toSerializable()); + isTxActorLocal ? readData : readData.toSerializable()); + readFuture.onComplete(onComplete, actorContext.getActorSystem().dispatcher()); } @@ -689,9 +973,8 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { public CheckedFuture dataExists( final YangInstanceIdentifier path) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} dataExists called path = {}", identifier, path); - } + LOG.debug("Tx {} dataExists called path = {}", identifier, path); + final SettableFuture returnFuture = SettableFuture.create(); // If there were any previous recorded put/merge/delete operation reply Futures then we @@ -702,10 +985,9 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { if(recordedOperationFutures.isEmpty()) { finishDataExists(path, returnFuture); } else { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} dataExists: verifying {} previous recorded operations", + LOG.debug("Tx {} dataExists: verifying {} previous recorded operations", identifier, recordedOperationFutures.size()); - } + // Note: we make a copy of recordedOperationFutures to be on the safe side in case // Futures#sequence accesses the passed List on a different thread, as // recordedOperationFutures is not synchronized. @@ -718,10 +1000,8 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { public void onComplete(Throwable failure, Iterable notUsed) throws Throwable { if(failure != null) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} dataExists: a recorded operation failed: {}", + LOG.debug("Tx {} dataExists: a recorded operation failed: {}", identifier, failure); - } returnFuture.setException(new ReadFailedException( "The data exists could not be performed because a previous " + "put, merge, or delete operation failed", failure)); @@ -740,25 +1020,24 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { private void finishDataExists(final YangInstanceIdentifier path, final SettableFuture returnFuture) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} finishDataExists called path = {}", identifier, path); - } + LOG.debug("Tx {} finishDataExists called path = {}", identifier, path); + OnComplete onComplete = new OnComplete() { @Override public void onComplete(Throwable failure, Object response) throws Throwable { if(failure != null) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} dataExists operation failed: {}", identifier, failure); - } + LOG.debug("Tx {} dataExists operation failed: {}", identifier, failure); returnFuture.setException(new ReadFailedException( "Error checking data exists for path " + path, failure)); } else { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} dataExists operation succeeded", identifier, failure); - } - if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) { - returnFuture.set(Boolean.valueOf(DataExistsReply. - fromSerializable(response).exists())); + LOG.debug("Tx {} dataExists operation succeeded", identifier, failure); + + if (response instanceof DataExistsReply) { + returnFuture.set(Boolean.valueOf(((DataExistsReply) response).exists())); + + } else if (response.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) { + returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists())); + } else { returnFuture.setException(new ReadFailedException( "Invalid response checking exists for path " + path)); @@ -767,8 +1046,10 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { } }; + DataExists dataExists = new DataExists(path); Future future = actorContext.executeOperationAsync(getActor(), - new DataExists(path).toSerializable()); + isTxActorLocal ? dataExists : dataExists.toSerializable()); + future.onComplete(onComplete, actorContext.getActorSystem().dispatcher()); } } @@ -777,66 +1058,51 @@ public class TransactionProxy implements DOMStoreReadWriteTransaction { private final Logger LOG = LoggerFactory.getLogger(NoOpTransactionContext.class); - private final Exception failure; + private final Throwable failure; - public NoOpTransactionContext(String shardName, Exception failure, - TransactionIdentifier identifier){ - super(shardName, identifier); + public NoOpTransactionContext(Throwable failure, TransactionIdentifier identifier){ + super(identifier); this.failure = failure; } @Override public void closeTransaction() { - if(LOG.isDebugEnabled()) { - LOG.debug("NoOpTransactionContext {} closeTransaction called", identifier); - } + LOG.debug("NoOpTransactionContext {} closeTransaction called", identifier); } @Override public Future readyTransaction() { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} readyTransaction called", identifier); - } + LOG.debug("Tx {} readyTransaction called", identifier); return akka.dispatch.Futures.failed(failure); } @Override public void deleteData(YangInstanceIdentifier path) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} deleteData called path = {}", identifier, path); - } + LOG.debug("Tx {} deleteData called path = {}", identifier, path); } @Override public void mergeData(YangInstanceIdentifier path, NormalizedNode data) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} mergeData called path = {}", identifier, path); - } + LOG.debug("Tx {} mergeData called path = {}", identifier, path); } @Override public void writeData(YangInstanceIdentifier path, NormalizedNode data) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} writeData called path = {}", identifier, path); - } + LOG.debug("Tx {} writeData called path = {}", identifier, path); } @Override public CheckedFuture>, ReadFailedException> readData( - YangInstanceIdentifier path) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} readData called path = {}", identifier, path); - } + YangInstanceIdentifier path) { + LOG.debug("Tx {} readData called path = {}", identifier, path); return Futures.immediateFailedCheckedFuture(new ReadFailedException( "Error reading data for path " + path, failure)); } @Override public CheckedFuture dataExists( - YangInstanceIdentifier path) { - if(LOG.isDebugEnabled()) { - LOG.debug("Tx {} dataExists called path = {}", identifier, path); - } + YangInstanceIdentifier path) { + LOG.debug("Tx {} dataExists called path = {}", identifier, path); return Futures.immediateFailedCheckedFuture(new ReadFailedException( "Error checking exists for path " + path, failure)); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/compat/BackwardsCompatibleThreePhaseCommitCohort.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/compat/BackwardsCompatibleThreePhaseCommitCohort.java new file mode 100644 index 0000000000..30ab97ceb1 --- /dev/null +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/compat/BackwardsCompatibleThreePhaseCommitCohort.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.datastore.compat; + +import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActor; +import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction; +import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction; +import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction; +import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransaction; +import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransactionReply; +import akka.actor.PoisonPill; +import akka.actor.Props; +import akka.event.Logging; +import akka.event.LoggingAdapter; +import akka.japi.Creator; + +/** + * An actor to maintain backwards compatibility for the base Helium version where the 3-phase commit + * messages don't contain the transactionId. This actor just forwards a new message containing the + * transactionId to the parent Shard. + * + * @author Thomas Pantelis + */ +public class BackwardsCompatibleThreePhaseCommitCohort extends AbstractUntypedActor { + + private final LoggingAdapter LOG = Logging.getLogger(getContext().system(), this); + + private final String transactionId; + + private BackwardsCompatibleThreePhaseCommitCohort(String transactionId) { + this.transactionId = transactionId; + } + + @Override + public void handleReceive(Object message) throws Exception { + if(message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) { + LOG.debug("BackwardsCompatibleThreePhaseCommitCohort CanCommitTransaction"); + + getContext().parent().forward(new CanCommitTransaction(transactionId).toSerializable(), + getContext()); + } else if(message.getClass().equals(PreCommitTransaction.SERIALIZABLE_CLASS)) { + LOG.debug("BackwardsCompatibleThreePhaseCommitCohort PreCommitTransaction"); + + // The Shard doesn't need the PreCommitTransaction message so just return the reply here. + getSender().tell(new PreCommitTransactionReply().toSerializable(), self()); + } else if(message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) { + LOG.debug("BackwardsCompatibleThreePhaseCommitCohort CommitTransaction"); + + getContext().parent().forward(new CommitTransaction(transactionId).toSerializable(), + getContext()); + + // We're done now - we can self-destruct + self().tell(PoisonPill.getInstance(), self()); + } else if(message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) { + LOG.debug("BackwardsCompatibleThreePhaseCommitCohort AbortTransaction"); + + getContext().parent().forward(new AbortTransaction(transactionId).toSerializable(), + getContext()); + self().tell(PoisonPill.getInstance(), self()); + } + } + + public static Props props(String transactionId) { + return Props.create(new BackwardsCompatibleThreePhaseCommitCohortCreator(transactionId)); + } + + private static class BackwardsCompatibleThreePhaseCommitCohortCreator + implements Creator { + private static final long serialVersionUID = 1L; + + private final String transactionId; + + BackwardsCompatibleThreePhaseCommitCohortCreator(String transactionId) { + this.transactionId = transactionId; + } + + @Override + public BackwardsCompatibleThreePhaseCommitCohort create() throws Exception { + return new BackwardsCompatibleThreePhaseCommitCohort(transactionId); + } + } +} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/ConfigurationReader.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/ConfigurationReader.java new file mode 100644 index 0000000000..12afdbd21b --- /dev/null +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/ConfigurationReader.java @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.datastore.config; + +import com.typesafe.config.Config; + +public interface ConfigurationReader { + Config read(); +} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/FileConfigurationReader.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/FileConfigurationReader.java new file mode 100644 index 0000000000..fb84734119 --- /dev/null +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/FileConfigurationReader.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.datastore.config; + +import com.google.common.base.Preconditions; +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; + +import java.io.File; + +public class FileConfigurationReader implements ConfigurationReader{ + + public static final String AKKA_CONF_PATH = "./configuration/initial/akka.conf"; + + @Override + public Config read() { + File defaultConfigFile = new File(AKKA_CONF_PATH); + Preconditions.checkState(defaultConfigFile.exists(), "akka.conf is missing"); + return ConfigFactory.parseFile(defaultConfigFile); + + } +} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/ResourceConfigurationReader.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/ResourceConfigurationReader.java new file mode 100644 index 0000000000..df17f97a4e --- /dev/null +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/config/ResourceConfigurationReader.java @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.cluster.datastore.config; + +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; + +public class ResourceConfigurationReader implements ConfigurationReader { + @Override + public Config read() { + return ConfigFactory.load(); + } +} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/LocalShardNotFoundException.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/LocalShardNotFoundException.java new file mode 100644 index 0000000000..7a976b86ed --- /dev/null +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/LocalShardNotFoundException.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.datastore.exceptions; + +/** + * Exception thrown when attempting to find a local shard but it doesn't exist. + * + * @author Thomas Pantelis + */ +public class LocalShardNotFoundException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public LocalShardNotFoundException(String message){ + super(message); + } +} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/NoShardLeaderException.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/NoShardLeaderException.java new file mode 100644 index 0000000000..b205b0fe78 --- /dev/null +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/NoShardLeaderException.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.datastore.exceptions; + +/** + * Exception indicating a shard has no current leader. + * + * @author Thomas Pantelis + */ +public class NoShardLeaderException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public NoShardLeaderException(String message){ + super(message); + } +} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/NotInitializedException.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/NotInitializedException.java index 302d684322..839cce63e5 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/NotInitializedException.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/NotInitializedException.java @@ -8,6 +8,7 @@ package org.opendaylight.controller.cluster.datastore.exceptions; public class NotInitializedException extends RuntimeException { + private static final long serialVersionUID = 1L; public NotInitializedException(String message) { super(message); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/PrimaryNotFoundException.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/PrimaryNotFoundException.java index 7b07053fd9..c98e2bd384 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/PrimaryNotFoundException.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/PrimaryNotFoundException.java @@ -9,6 +9,7 @@ package org.opendaylight.controller.cluster.datastore.exceptions; public class PrimaryNotFoundException extends RuntimeException { + private static final long serialVersionUID = 1L; public PrimaryNotFoundException(String message){ super(message); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/TimeoutException.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/TimeoutException.java index 472cd38734..5590877aa7 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/TimeoutException.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/TimeoutException.java @@ -9,6 +9,7 @@ package org.opendaylight.controller.cluster.datastore.exceptions; public class TimeoutException extends RuntimeException { + private static final long serialVersionUID = 1L; public TimeoutException(String message, Exception e){ super(message, e); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/UnknownMessageException.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/UnknownMessageException.java index f4f2524a8d..bd804b8dde 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/UnknownMessageException.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/UnknownMessageException.java @@ -9,6 +9,7 @@ package org.opendaylight.controller.cluster.datastore.exceptions; public class UnknownMessageException extends Exception { + private static final long serialVersionUID = 1L; private final Object message; public UnknownMessageException(Object message) { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ActorInitialized.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ActorInitialized.java index b034f87d1c..71d5a48291 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ActorInitialized.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ActorInitialized.java @@ -10,4 +10,5 @@ package org.opendaylight.controller.cluster.datastore.messages; import java.io.Serializable; public class ActorInitialized implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ActorNotInitialized.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ActorNotInitialized.java index de25ef9ecc..576010f916 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ActorNotInitialized.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ActorNotInitialized.java @@ -10,4 +10,5 @@ package org.opendaylight.controller.cluster.datastore.messages; import java.io.Serializable; public class ActorNotInitialized implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CanCommitTransactionReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CanCommitTransactionReply.java index 9c8909c2dd..4d121bae0a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CanCommitTransactionReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CanCommitTransactionReply.java @@ -11,12 +11,12 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.cohort3pc.ThreePhaseCommitCohortMessages; public class CanCommitTransactionReply implements SerializableMessage { - public static Class SERIALIZABLE_CLASS = + public static final Class SERIALIZABLE_CLASS = ThreePhaseCommitCohortMessages.CanCommitTransactionReply.class; private final Boolean canCommit; - public CanCommitTransactionReply(Boolean canCommit) { + public CanCommitTransactionReply(final Boolean canCommit) { this.canCommit = canCommit; } @@ -29,7 +29,7 @@ public class CanCommitTransactionReply implements SerializableMessage { return ThreePhaseCommitCohortMessages.CanCommitTransactionReply.newBuilder().setCanCommit(canCommit).build(); } - public static CanCommitTransactionReply fromSerializable(Object message) { + public static CanCommitTransactionReply fromSerializable(final Object message) { return new CanCommitTransactionReply( ((ThreePhaseCommitCohortMessages.CanCommitTransactionReply) message).getCanCommit()); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistration.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistration.java index a54ee6209c..f711d6f7b5 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistration.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistration.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages; public class CloseDataChangeListenerRegistration implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = ListenerRegistrationMessages.CloseDataChangeListenerRegistration.class; + public static final Class SERIALIZABLE_CLASS = + ListenerRegistrationMessages.CloseDataChangeListenerRegistration.class; @Override public Object toSerializable() { return ListenerRegistrationMessages.CloseDataChangeListenerRegistration.newBuilder().build(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistrationReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistrationReply.java index faf73c87eb..9d8225c23a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistrationReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistrationReply.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages; public class CloseDataChangeListenerRegistrationReply implements SerializableMessage{ - public static Class SERIALIZABLE_CLASS = ListenerRegistrationMessages.CloseDataChangeListenerRegistrationReply.class; + public static final Class SERIALIZABLE_CLASS = + ListenerRegistrationMessages.CloseDataChangeListenerRegistrationReply.class; @Override public Object toSerializable() { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransaction.java index 451e39cf6a..c73111f2db 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransaction.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; public class CloseTransaction implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.CloseTransaction.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.CloseTransaction.class; @Override public Object toSerializable() { return ShardTransactionMessages.CloseTransaction.newBuilder().build(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionChain.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionChain.java index 74de6c5aea..7db39b77a3 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionChain.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionChain.java @@ -11,11 +11,11 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages; public class CloseTransactionChain implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = + public static final Class SERIALIZABLE_CLASS = ShardTransactionChainMessages.CloseTransactionChain.class; private final String transactionChainId; - public CloseTransactionChain(String transactionChainId){ + public CloseTransactionChain(final String transactionChainId){ this.transactionChainId = transactionChainId; } @@ -25,7 +25,7 @@ public class CloseTransactionChain implements SerializableMessage { .setTransactionChainId(transactionChainId).build(); } - public static CloseTransactionChain fromSerializable(Object message){ + public static CloseTransactionChain fromSerializable(final Object message){ ShardTransactionChainMessages.CloseTransactionChain closeTransactionChain = (ShardTransactionChainMessages.CloseTransactionChain) message; diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionChainReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionChainReply.java index 23699b7be6..c001ae185a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionChainReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionChainReply.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages; public class CloseTransactionChainReply implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = ShardTransactionChainMessages.CloseTransactionChainReply.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionChainMessages.CloseTransactionChainReply.class; @Override public Object toSerializable() { return ShardTransactionChainMessages.CloseTransactionChainReply.newBuilder().build(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionReply.java index 666d182aaf..124eeb2235 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseTransactionReply.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; public class CloseTransactionReply implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.CloseTransactionReply.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.CloseTransactionReply.class; @Override public Object toSerializable() { return ShardTransactionMessages.CloseTransactionReply.newBuilder().build(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransaction.java index 361d406ac8..bf82e66036 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransaction.java @@ -13,24 +13,33 @@ import org.opendaylight.controller.protobuff.messages.transaction.ShardTransacti public class CreateTransaction implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.CreateTransaction.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.CreateTransaction.class; + + public static final int HELIUM_1_VERSION = 1; + public static final int CURRENT_VERSION = HELIUM_1_VERSION; + private final String transactionId; private final int transactionType; private final String transactionChainId; + private final int version; public CreateTransaction(String transactionId, int transactionType) { this(transactionId, transactionType, ""); } public CreateTransaction(String transactionId, int transactionType, String transactionChainId) { + this(transactionId, transactionType, transactionChainId, CURRENT_VERSION); + } + private CreateTransaction(String transactionId, int transactionType, String transactionChainId, + int version) { this.transactionId = transactionId; this.transactionType = transactionType; this.transactionChainId = transactionChainId; - + this.version = version; } - public String getTransactionId() { return transactionId; } @@ -39,19 +48,25 @@ public class CreateTransaction implements SerializableMessage { return transactionType; } + public int getVersion() { + return version; + } + @Override public Object toSerializable() { return ShardTransactionMessages.CreateTransaction.newBuilder() .setTransactionId(transactionId) .setTransactionType(transactionType) - .setTransactionChainId(transactionChainId).build(); + .setTransactionChainId(transactionChainId) + .setMessageVersion(version).build(); } public static CreateTransaction fromSerializable(Object message) { ShardTransactionMessages.CreateTransaction createTransaction = (ShardTransactionMessages.CreateTransaction) message; return new CreateTransaction(createTransaction.getTransactionId(), - createTransaction.getTransactionType(), createTransaction.getTransactionChainId()); + createTransaction.getTransactionType(), createTransaction.getTransactionChainId(), + createTransaction.getMessageVersion()); } public String getTransactionChainId() { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransactionReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransactionReply.java index 096d131d5a..83e68c9cb4 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransactionReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransactionReply.java @@ -12,16 +12,25 @@ import org.opendaylight.controller.protobuff.messages.transaction.ShardTransacti public class CreateTransactionReply implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.CreateTransactionReply.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.CreateTransactionReply.class; private final String transactionPath; private final String transactionId; + private final int version; - public CreateTransactionReply(String transactionPath, - String transactionId) { + public CreateTransactionReply(final String transactionPath, + final String transactionId) { + this(transactionPath, transactionId, CreateTransaction.CURRENT_VERSION); + } + + public CreateTransactionReply(final String transactionPath, + final String transactionId, final int version) { this.transactionPath = transactionPath; this.transactionId = transactionId; + this.version = version; } + public String getTransactionPath() { return transactionPath; } @@ -30,16 +39,22 @@ public class CreateTransactionReply implements SerializableMessage { return transactionId; } + public int getVersion() { + return version; + } + + @Override public Object toSerializable(){ return ShardTransactionMessages.CreateTransactionReply.newBuilder() .setTransactionActorPath(transactionPath) .setTransactionId(transactionId) + .setMessageVersion(version) .build(); } - public static CreateTransactionReply fromSerializable(Object serializable){ + public static CreateTransactionReply fromSerializable(final Object serializable){ ShardTransactionMessages.CreateTransactionReply o = (ShardTransactionMessages.CreateTransactionReply) serializable; - return new CreateTransactionReply(o.getTransactionActorPath(), o.getTransactionId()); + return new CreateTransactionReply(o.getTransactionActorPath(), o.getTransactionId(), o.getMessageVersion()); } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChangedReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChangedReply.java index cffe985d18..e10a407292 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChangedReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChangedReply.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages; public class DataChangedReply implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = DataChangeListenerMessages.DataChangedReply.class; + public static final Class SERIALIZABLE_CLASS = + DataChangeListenerMessages.DataChangedReply.class; @Override public Object toSerializable() { return DataChangeListenerMessages.DataChangedReply.newBuilder().build(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataExists.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataExists.java index d52daabd84..84b8df1676 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataExists.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataExists.java @@ -14,11 +14,12 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class DataExists implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DataExists.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.DataExists.class; private final YangInstanceIdentifier path; - public DataExists(YangInstanceIdentifier path) { + public DataExists(final YangInstanceIdentifier path) { this.path = path; } @@ -32,7 +33,7 @@ public class DataExists implements SerializableMessage{ InstanceIdentifierUtils.toSerializable(path)).build(); } - public static DataExists fromSerializable(Object serializable){ + public static DataExists fromSerializable(final Object serializable){ ShardTransactionMessages.DataExists o = (ShardTransactionMessages.DataExists) serializable; return new DataExists(InstanceIdentifierUtils.fromSerializable(o.getInstanceIdentifierPathArguments())); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataExistsReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataExistsReply.java index 04fafa10e2..24ca646454 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataExistsReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataExistsReply.java @@ -11,13 +11,12 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; public class DataExistsReply implements SerializableMessage{ - - - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DataExistsReply.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.DataExistsReply.class; private final boolean exists; - public DataExistsReply(boolean exists) { + public DataExistsReply(final boolean exists) { this.exists = exists; } @@ -30,7 +29,7 @@ public class DataExistsReply implements SerializableMessage{ .setExists(exists).build(); } - public static DataExistsReply fromSerializable(Object serializable){ + public static DataExistsReply fromSerializable(final Object serializable){ ShardTransactionMessages.DataExistsReply o = (ShardTransactionMessages.DataExistsReply) serializable; return new DataExistsReply(o.getExists()); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DeleteData.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DeleteData.java index 6d3051c8c7..81bc1026e4 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DeleteData.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DeleteData.java @@ -14,11 +14,11 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class DeleteData implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DeleteData.class; + public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DeleteData.class; private final YangInstanceIdentifier path; - public DeleteData(YangInstanceIdentifier path) { + public DeleteData(final YangInstanceIdentifier path) { this.path = path; } @@ -31,7 +31,7 @@ public class DeleteData implements SerializableMessage { .setInstanceIdentifierPathArguments(InstanceIdentifierUtils.toSerializable(path)).build(); } - public static DeleteData fromSerializable(Object serializable){ + public static DeleteData fromSerializable(final Object serializable){ ShardTransactionMessages.DeleteData o = (ShardTransactionMessages.DeleteData) serializable; return new DeleteData(InstanceIdentifierUtils.fromSerializable(o.getInstanceIdentifierPathArguments())); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DeleteDataReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DeleteDataReply.java index 8e2a7b7295..2e02664e1d 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DeleteDataReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DeleteDataReply.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; public class DeleteDataReply implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.DeleteDataReply.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.DeleteDataReply.class; @Override public Object toSerializable() { return ShardTransactionMessages.DeleteDataReply.newBuilder().build(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/FindLocalShard.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/FindLocalShard.java index c415db6efe..b6560a8347 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/FindLocalShard.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/FindLocalShard.java @@ -14,12 +14,18 @@ package org.opendaylight.controller.cluster.datastore.messages; */ public class FindLocalShard { private final String shardName; + private final boolean waitUntilInitialized; - public FindLocalShard(String shardName) { + public FindLocalShard(String shardName, boolean waitUntilInitialized) { this.shardName = shardName; + this.waitUntilInitialized = waitUntilInitialized; } public String getShardName() { return shardName; } + + public boolean isWaitUntilInitialized() { + return waitUntilInitialized; + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/FindPrimary.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/FindPrimary.java index f5a6a34841..a34330bcf6 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/FindPrimary.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/FindPrimary.java @@ -15,26 +15,33 @@ import com.google.common.base.Preconditions; * */ public class FindPrimary implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = FindPrimary.class; + public static final Class SERIALIZABLE_CLASS = FindPrimary.class; + private final String shardName; + private final boolean waitUntilInitialized; - public FindPrimary(String shardName){ + public FindPrimary(String shardName, boolean waitUntilInitialized){ Preconditions.checkNotNull(shardName, "shardName should not be null"); this.shardName = shardName; + this.waitUntilInitialized = waitUntilInitialized; } public String getShardName() { return shardName; } - @Override - public Object toSerializable() { - return this; - } + public boolean isWaitUntilInitialized() { + return waitUntilInitialized; + } - public static FindPrimary fromSerializable(Object message){ - return (FindPrimary) message; - } + @Override + public Object toSerializable() { + return this; + } + + public static FindPrimary fromSerializable(Object message){ + return (FindPrimary) message; + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ForwardedReadyTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ForwardedReadyTransaction.java index 4f8ea51f78..38886c9a58 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ForwardedReadyTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ForwardedReadyTransaction.java @@ -19,12 +19,17 @@ public class ForwardedReadyTransaction { private final String transactionID; private final DOMStoreThreePhaseCommitCohort cohort; private final Modification modification; + private final boolean returnSerialized; + private final int txnClientVersion; - public ForwardedReadyTransaction(String transactionID, DOMStoreThreePhaseCommitCohort cohort, - Modification modification) { + public ForwardedReadyTransaction(String transactionID, int txnClientVersion, + DOMStoreThreePhaseCommitCohort cohort, Modification modification, + boolean returnSerialized) { this.transactionID = transactionID; this.cohort = cohort; this.modification = modification; + this.returnSerialized = returnSerialized; + this.txnClientVersion = txnClientVersion; } public String getTransactionID() { @@ -38,4 +43,12 @@ public class ForwardedReadyTransaction { public Modification getModification() { return modification; } + + public boolean isReturnSerialized() { + return returnSerialized; + } + + public int getTxnClientVersion() { + return txnClientVersion; + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/MergeDataReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/MergeDataReply.java index 81b1c3bbb1..92d6d72847 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/MergeDataReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/MergeDataReply.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; public class MergeDataReply implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.MergeDataReply.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.MergeDataReply.class; @Override public Object toSerializable() { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransaction.java index dae4cec3c3..3cec7e74a6 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransaction.java @@ -12,7 +12,8 @@ import org.opendaylight.controller.protobuff.messages.cohort3pc.ThreePhaseCommit public class PreCommitTransaction implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ThreePhaseCommitCohortMessages.PreCommitTransaction.class; + public static final Class SERIALIZABLE_CLASS = + ThreePhaseCommitCohortMessages.PreCommitTransaction.class; @Override public Object toSerializable() { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransactionReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransactionReply.java index fc07bfcb4b..d158049409 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransactionReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransactionReply.java @@ -12,7 +12,8 @@ import org.opendaylight.controller.protobuff.messages.cohort3pc.ThreePhaseCommit public class PreCommitTransactionReply implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ThreePhaseCommitCohortMessages.PreCommitTransactionReply.class; + public static final Class SERIALIZABLE_CLASS = + ThreePhaseCommitCohortMessages.PreCommitTransactionReply.class; @Override public Object toSerializable() { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryFound.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryFound.java index a2f6701524..a5565020ed 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryFound.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryFound.java @@ -10,10 +10,10 @@ package org.opendaylight.controller.cluster.datastore.messages; public class PrimaryFound implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = PrimaryFound.class; + public static final Class SERIALIZABLE_CLASS = PrimaryFound.class; private final String primaryPath; - public PrimaryFound(String primaryPath) { + public PrimaryFound(final String primaryPath) { this.primaryPath = primaryPath; } @@ -22,13 +22,19 @@ public class PrimaryFound implements SerializableMessage { } @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } PrimaryFound that = (PrimaryFound) o; - if (!primaryPath.equals(that.primaryPath)) return false; + if (!primaryPath.equals(that.primaryPath)) { + return false; + } return true; } @@ -51,7 +57,7 @@ public class PrimaryFound implements SerializableMessage { return this; } - public static PrimaryFound fromSerializable(Object message){ + public static PrimaryFound fromSerializable(final Object message){ return (PrimaryFound) message; } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryNotFound.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryNotFound.java index 731a5364db..b47c91b6e5 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryNotFound.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryNotFound.java @@ -11,11 +11,11 @@ package org.opendaylight.controller.cluster.datastore.messages; import com.google.common.base.Preconditions; public class PrimaryNotFound implements SerializableMessage { - public static final Class SERIALIZABLE_CLASS = PrimaryNotFound.class; + public static final Class SERIALIZABLE_CLASS = PrimaryNotFound.class; private final String shardName; - public PrimaryNotFound(String shardName){ + public PrimaryNotFound(final String shardName){ Preconditions.checkNotNull(shardName, "shardName should not be null"); @@ -23,13 +23,19 @@ public class PrimaryNotFound implements SerializableMessage { } @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } PrimaryNotFound that = (PrimaryNotFound) o; - if (shardName != null ? !shardName.equals(that.shardName) : that.shardName != null) return false; + if (shardName != null ? !shardName.equals(that.shardName) : that.shardName != null) { + return false; + } return true; } @@ -44,7 +50,7 @@ public class PrimaryNotFound implements SerializableMessage { return this; } - public static PrimaryNotFound fromSerializable(Object message){ + public static PrimaryNotFound fromSerializable(final Object message){ return (PrimaryNotFound) message; } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadData.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadData.java index d743d99fcc..a8a3e7d071 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadData.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadData.java @@ -13,10 +13,11 @@ import org.opendaylight.controller.protobuff.messages.transaction.ShardTransacti import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class ReadData { - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.ReadData.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.ReadData.class; private final YangInstanceIdentifier path; - public ReadData(YangInstanceIdentifier path) { + public ReadData(final YangInstanceIdentifier path) { this.path = path; } @@ -30,7 +31,7 @@ public class ReadData { .build(); } - public static ReadData fromSerializable(Object serializable){ + public static ReadData fromSerializable(final Object serializable){ ShardTransactionMessages.ReadData o = (ShardTransactionMessages.ReadData) serializable; return new ReadData(InstanceIdentifierUtils.fromSerializable(o.getInstanceIdentifierPathArguments())); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransaction.java index 3a51d9850b..581caefd04 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransaction.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransaction.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; public class ReadyTransaction implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.ReadyTransaction.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.ReadyTransaction.class; @Override public Object toSerializable() { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransactionReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransactionReply.java index eee489177a..282e23ed3b 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransactionReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransactionReply.java @@ -17,7 +17,6 @@ public class ReadyTransactionReply implements SerializableMessage { private final String cohortPath; public ReadyTransactionReply(String cohortPath) { - this.cohortPath = cohortPath; } @@ -27,8 +26,9 @@ public class ReadyTransactionReply implements SerializableMessage { @Override public ShardTransactionMessages.ReadyTransactionReply toSerializable() { - return ShardTransactionMessages.ReadyTransactionReply.newBuilder(). - setActorPath(cohortPath).build(); + return ShardTransactionMessages.ReadyTransactionReply.newBuilder() + .setActorPath(cohortPath) + .build(); } public static ReadyTransactionReply fromSerializable(Object serializable) { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/RegisterChangeListenerReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/RegisterChangeListenerReply.java index 8d980d283d..bbfbbaa80b 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/RegisterChangeListenerReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/RegisterChangeListenerReply.java @@ -13,10 +13,11 @@ import akka.actor.ActorSystem; import org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages; public class RegisterChangeListenerReply implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ListenerRegistrationMessages.RegisterChangeListenerReply.class; + public static final Class SERIALIZABLE_CLASS = + ListenerRegistrationMessages.RegisterChangeListenerReply.class; private final ActorPath listenerRegistrationPath; - public RegisterChangeListenerReply(ActorPath listenerRegistrationPath) { + public RegisterChangeListenerReply(final ActorPath listenerRegistrationPath) { this.listenerRegistrationPath = listenerRegistrationPath; } @@ -30,7 +31,7 @@ public class RegisterChangeListenerReply implements SerializableMessage{ .setListenerRegistrationPath(listenerRegistrationPath.toString()).build(); } - public static RegisterChangeListenerReply fromSerializable(ActorSystem actorSystem,Object serializable){ + public static RegisterChangeListenerReply fromSerializable(final ActorSystem actorSystem,final Object serializable){ ListenerRegistrationMessages.RegisterChangeListenerReply o = (ListenerRegistrationMessages.RegisterChangeListenerReply) serializable; return new RegisterChangeListenerReply( actorSystem.actorFor(o.getListenerRegistrationPath()).path() diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/WriteDataReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/WriteDataReply.java index 5404fb6510..876105de18 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/WriteDataReply.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/WriteDataReply.java @@ -11,7 +11,8 @@ package org.opendaylight.controller.cluster.datastore.messages; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; public class WriteDataReply implements SerializableMessage{ - public static final Class SERIALIZABLE_CLASS = ShardTransactionMessages.WriteDataReply.class; + public static final Class SERIALIZABLE_CLASS = + ShardTransactionMessages.WriteDataReply.class; @Override public Object toSerializable() { return ShardTransactionMessages.WriteDataReply.newBuilder().build(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MergeModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MergeModification.java index 24c4c6c50a..2f9d77660a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MergeModification.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MergeModification.java @@ -20,18 +20,19 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; * MergeModification stores all the parameters required to merge data into the specified path */ public class MergeModification extends WriteModification { + private static final long serialVersionUID = 1L; - public MergeModification(YangInstanceIdentifier path, NormalizedNode data, - SchemaContext schemaContext) { + public MergeModification(final YangInstanceIdentifier path, final NormalizedNode data, + final SchemaContext schemaContext) { super(path, data, schemaContext); } @Override - public void apply(DOMStoreWriteTransaction transaction) { + public void apply(final DOMStoreWriteTransaction transaction) { transaction.merge(path, data); } - public static MergeModification fromSerializable(Object serializable, SchemaContext schemaContext) { + public static MergeModification fromSerializable(final Object serializable, final SchemaContext schemaContext) { PersistentMessages.Modification o = (PersistentMessages.Modification) serializable; Decoded decoded = new NormalizedNodeToNodeCodec(schemaContext).decode(o.getPath(), o.getData()); return new MergeModification(decoded.getDecodedPath(), decoded.getDecodedNode(), schemaContext); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/WriteModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/WriteModification.java index 53cc35a88b..b2964086fd 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/WriteModification.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/WriteModification.java @@ -21,22 +21,22 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; * WriteModification stores all the parameters required to write data to the specified path */ public class WriteModification extends AbstractModification { - - protected final NormalizedNode data; + private static final long serialVersionUID = 1L; + protected final NormalizedNode data; private final SchemaContext schemaContext; - public WriteModification(YangInstanceIdentifier path, NormalizedNode data, SchemaContext schemaContext) { + public WriteModification(final YangInstanceIdentifier path, final NormalizedNode data, final SchemaContext schemaContext) { super(path); this.data = data; this.schemaContext = schemaContext; } @Override - public void apply(DOMStoreWriteTransaction transaction) { + public void apply(final DOMStoreWriteTransaction transaction) { transaction.write(path, data); } - public NormalizedNode getData() { + public NormalizedNode getData() { return data; } @@ -51,7 +51,7 @@ public class WriteModification extends AbstractModification { .build(); } - public static WriteModification fromSerializable(Object serializable, SchemaContext schemaContext) { + public static WriteModification fromSerializable(final Object serializable, final SchemaContext schemaContext) { PersistentMessages.Modification o = (PersistentMessages.Modification) serializable; Decoded decoded = new NormalizedNodeToNodeCodec(schemaContext).decode(o.getPath(), o.getData()); return new WriteModification(decoded.getDecodedPath(), decoded.getDecodedNode(), schemaContext); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ShardStrategyFactory.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ShardStrategyFactory.java index f4ab8fab6f..62fb65482b 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ShardStrategyFactory.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ShardStrategyFactory.java @@ -10,26 +10,25 @@ package org.opendaylight.controller.cluster.datastore.shardstrategy; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import org.opendaylight.controller.cluster.datastore.Configuration; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; - import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.opendaylight.controller.cluster.datastore.Configuration; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class ShardStrategyFactory { private static Map moduleNameToStrategyMap = - new ConcurrentHashMap(); + new ConcurrentHashMap<>(); private static final String UNKNOWN_MODULE_NAME = "unknown"; private static Configuration configuration; - public static void setConfiguration(Configuration configuration){ + public static void setConfiguration(final Configuration configuration){ ShardStrategyFactory.configuration = configuration; moduleNameToStrategyMap = configuration.getModuleNameToShardStrategyMap(); } - public static ShardStrategy getStrategy(YangInstanceIdentifier path) { + public static ShardStrategy getStrategy(final YangInstanceIdentifier path) { Preconditions.checkState(configuration != null, "configuration should not be missing"); Preconditions.checkNotNull(path, "path should not be null"); @@ -44,7 +43,7 @@ public class ShardStrategyFactory { } - private static String getModuleName(YangInstanceIdentifier path) { + private static String getModuleName(final YangInstanceIdentifier path) { String namespace = path.getPathArguments().iterator().next().getNodeType().getNamespace().toASCIIString(); Optional optional = diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/ActorContext.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/ActorContext.java index d8af09c86b..f81c2a87cd 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/ActorContext.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/ActorContext.java @@ -12,19 +12,30 @@ import akka.actor.ActorPath; import akka.actor.ActorRef; import akka.actor.ActorSelection; import akka.actor.ActorSystem; +import akka.actor.Address; import akka.actor.PoisonPill; +import akka.dispatch.Mapper; +import akka.pattern.AskTimeoutException; import akka.util.Timeout; import com.google.common.base.Optional; import com.google.common.base.Preconditions; +import com.google.common.base.Strings; +import java.util.concurrent.TimeUnit; import org.opendaylight.controller.cluster.datastore.ClusterWrapper; import org.opendaylight.controller.cluster.datastore.Configuration; +import org.opendaylight.controller.cluster.datastore.DatastoreContext; +import org.opendaylight.controller.cluster.datastore.exceptions.LocalShardNotFoundException; import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException; +import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException; import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException; +import org.opendaylight.controller.cluster.datastore.exceptions.UnknownMessageException; import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized; import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard; import org.opendaylight.controller.cluster.datastore.messages.FindPrimary; import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound; +import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound; import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound; +import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound; import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.slf4j.Logger; @@ -34,8 +45,6 @@ import scala.concurrent.Future; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; -import java.util.concurrent.TimeUnit; - import static akka.pattern.Patterns.ask; /** @@ -48,25 +57,63 @@ public class ActorContext { private static final Logger LOG = LoggerFactory.getLogger(ActorContext.class); - private static final FiniteDuration DEFAULT_OPER_DURATION = Duration.create(5, TimeUnit.SECONDS); - public static final String MAILBOX = "bounded-mailbox"; + private static final Mapper FIND_PRIMARY_FAILURE_TRANSFORMER = + new Mapper() { + @Override + public Throwable apply(Throwable failure) { + Throwable actualFailure = failure; + if(failure instanceof AskTimeoutException) { + // A timeout exception most likely means the shard isn't initialized. + actualFailure = new NotInitializedException( + "Timed out trying to find the primary shard. Most likely cause is the " + + "shard is not initialized yet."); + } + + return actualFailure; + } + }; + private final ActorSystem actorSystem; private final ActorRef shardManager; private final ClusterWrapper clusterWrapper; private final Configuration configuration; + private final DatastoreContext datastoreContext; private volatile SchemaContext schemaContext; - private FiniteDuration operationDuration = DEFAULT_OPER_DURATION; - private Timeout operationTimeout = new Timeout(operationDuration); + private final FiniteDuration operationDuration; + private final Timeout operationTimeout; + private final String selfAddressHostPort; public ActorContext(ActorSystem actorSystem, ActorRef shardManager, - ClusterWrapper clusterWrapper, - Configuration configuration) { + ClusterWrapper clusterWrapper, Configuration configuration) { + this(actorSystem, shardManager, clusterWrapper, configuration, + DatastoreContext.newBuilder().build()); + } + + public ActorContext(ActorSystem actorSystem, ActorRef shardManager, + ClusterWrapper clusterWrapper, Configuration configuration, + DatastoreContext datastoreContext) { this.actorSystem = actorSystem; this.shardManager = shardManager; this.clusterWrapper = clusterWrapper; this.configuration = configuration; + this.datastoreContext = datastoreContext; + + operationDuration = Duration.create(datastoreContext.getOperationTimeoutInSeconds(), + TimeUnit.SECONDS); + operationTimeout = new Timeout(operationDuration); + + Address selfAddress = clusterWrapper.getSelfAddress(); + if (selfAddress != null && !selfAddress.host().isEmpty()) { + selfAddressHostPort = selfAddress.host().get() + ":" + selfAddress.port().get(); + } else { + selfAddressHostPort = null; + } + } + + public DatastoreContext getDatastoreContext() { + return datastoreContext; } public ActorSystem getActorSystem() { @@ -93,11 +140,6 @@ public class ActorContext { } } - public void setOperationTimeout(int timeoutInSeconds) { - operationDuration = Duration.create(timeoutInSeconds, TimeUnit.SECONDS); - operationTimeout = new Timeout(operationDuration); - } - public SchemaContext getSchemaContext() { return schemaContext; } @@ -116,15 +158,43 @@ public class ActorContext { return Optional.of(actorSystem.actorSelection(path)); } + public Future findPrimaryShardAsync(final String shardName) { + Future future = executeOperationAsync(shardManager, + new FindPrimary(shardName, true).toSerializable(), + datastoreContext.getShardInitializationTimeout()); + + return future.transform(new Mapper() { + @Override + public ActorSelection checkedApply(Object response) throws Exception { + if(response.getClass().equals(PrimaryFound.SERIALIZABLE_CLASS)) { + PrimaryFound found = PrimaryFound.fromSerializable(response); + + LOG.debug("Primary found {}", found.getPrimaryPath()); + return actorSystem.actorSelection(found.getPrimaryPath()); + } else if(response instanceof ActorNotInitialized) { + throw new NotInitializedException( + String.format("Found primary shard %s but it's not initialized yet. " + + "Please try again later", shardName)); + } else if(response instanceof PrimaryNotFound) { + throw new PrimaryNotFoundException( + String.format("No primary shard found for %S.", shardName)); + } + + throw new UnknownMessageException(String.format( + "FindPrimary returned unkown response: %s", response)); + } + }, FIND_PRIMARY_FAILURE_TRANSFORMER, getActorSystem().dispatcher()); + } + /** - * Finds a local shard given it's shard name and return it's ActorRef + * Finds a local shard given its shard name and return it's ActorRef * * @param shardName the name of the local shard that needs to be found * @return a reference to a local shard actor which represents the shard * specified by the shardName */ public Optional findLocalShard(String shardName) { - Object result = executeOperation(shardManager, new FindLocalShard(shardName)); + Object result = executeOperation(shardManager, new FindLocalShard(shardName, false)); if (result instanceof LocalShardFound) { LocalShardFound found = (LocalShardFound) result; @@ -135,9 +205,40 @@ public class ActorContext { return Optional.absent(); } + /** + * Finds a local shard async given its shard name and return a Future from which to obtain the + * ActorRef. + * + * @param shardName the name of the local shard that needs to be found + */ + public Future findLocalShardAsync( final String shardName) { + Future future = executeOperationAsync(shardManager, + new FindLocalShard(shardName, true), datastoreContext.getShardInitializationTimeout()); + + return future.map(new Mapper() { + @Override + public ActorRef checkedApply(Object response) throws Throwable { + if(response instanceof LocalShardFound) { + LocalShardFound found = (LocalShardFound)response; + LOG.debug("Local shard found {}", found.getPath()); + return found.getPath(); + } else if(response instanceof ActorNotInitialized) { + throw new NotInitializedException( + String.format("Found local shard for %s but it's not initialized yet.", + shardName)); + } else if(response instanceof LocalShardNotFound) { + throw new LocalShardNotFoundException( + String.format("Local shard for %s does not exist.", shardName)); + } + + throw new UnknownMessageException(String.format( + "FindLocalShard returned unkown response: %s", response)); + } + }, getActorSystem().dispatcher()); + } private String findPrimaryPathOrNull(String shardName) { - Object result = executeOperation(shardManager, new FindPrimary(shardName).toSerializable()); + Object result = executeOperation(shardManager, new FindPrimary(shardName, false).toSerializable()); if (result.getClass().equals(PrimaryFound.SERIALIZABLE_CLASS)) { PrimaryFound found = PrimaryFound.fromSerializable(result); @@ -205,15 +306,28 @@ public class ActorContext { * * @param actor the ActorSelection * @param message the message to send + * @param timeout the operation timeout * @return a Future containing the eventual result */ - public Future executeOperationAsync(ActorSelection actor, Object message) { + public Future executeOperationAsync(ActorSelection actor, Object message, + Timeout timeout) { Preconditions.checkArgument(actor != null, "actor must not be null"); Preconditions.checkArgument(message != null, "message must not be null"); LOG.debug("Sending message {} to {}", message.getClass().toString(), actor.toString()); - return ask(actor, message, operationTimeout); + return ask(actor, message, timeout); + } + + /** + * Execute an operation on a remote actor asynchronously. + * + * @param actor the ActorSelection + * @param message the message to send + * @return a Future containing the eventual result + */ + public Future executeOperationAsync(ActorSelection actor, Object message) { + return executeOperationAsync(actor, message, operationTimeout); } /** @@ -237,6 +351,10 @@ public class ActorContext { actorSystem.shutdown(); } + public ClusterWrapper getClusterWrapper() { + return clusterWrapper; + } + public String getCurrentMemberName(){ return clusterWrapper.getCurrentMemberName(); } @@ -262,4 +380,55 @@ public class ActorContext { public FiniteDuration getOperationDuration() { return operationDuration; } + + public boolean isPathLocal(String path) { + if (Strings.isNullOrEmpty(path)) { + return false; + } + + int pathAtIndex = path.indexOf("@"); + if (pathAtIndex == -1) { + //if the path is of local format, then its local and is co-located + return true; + + } else if (selfAddressHostPort != null) { + // self-address and tx actor path, both are of remote path format + int slashIndex = path.indexOf("/", pathAtIndex); + + if (slashIndex == -1) { + return false; + } + + String hostPort = path.substring(pathAtIndex + 1, slashIndex); + return hostPort.equals(selfAddressHostPort); + + } else { + // self address is local format and tx actor path is remote format + return false; + } + } + + /** + * @deprecated This method is present only to support backward compatibility with Helium and should not be + * used any further + * + * + * @param primaryPath + * @param localPathOfRemoteActor + * @return + */ + @Deprecated + public String resolvePath(final String primaryPath, + final String localPathOfRemoteActor) { + StringBuilder builder = new StringBuilder(); + String[] primaryPathElements = primaryPath.split("/"); + builder.append(primaryPathElements[0]).append("//") + .append(primaryPathElements[1]).append(primaryPathElements[2]); + String[] remotePathElements = localPathOfRemoteActor.split("/"); + for (int i = 3; i < remotePathElements.length; i++) { + builder.append("/").append(remotePathElements[i]); + } + + return builder.toString(); + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedConfigDataStoreProviderModule.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedConfigDataStoreProviderModule.java index de33f55b96..8eb653a44f 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedConfigDataStoreProviderModule.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedConfigDataStoreProviderModule.java @@ -54,10 +54,17 @@ public class DistributedConfigDataStoreProviderModule extends getValue().intValue()) .shardSnapshotBatchCount(props.getShardSnapshotBatchCount().getValue().intValue()) .shardHeartbeatIntervalInMillis(props.getShardHearbeatIntervalInMillis().getValue()) + .shardInitializationTimeout(props.getShardInitializationTimeoutInSeconds().getValue(), + TimeUnit.SECONDS) + .shardLeaderElectionTimeout(props.getShardLeaderElectionTimeoutInSeconds().getValue(), + TimeUnit.SECONDS) .shardTransactionCommitTimeoutInSeconds( props.getShardTransactionCommitTimeoutInSeconds().getValue().intValue()) .shardTransactionCommitQueueCapacity( props.getShardTransactionCommitQueueCapacity().getValue().intValue()) + .persistent(props.getPersistent().booleanValue()) + .shardIsolatedLeaderCheckIntervalInMillis( + props.getShardIsolatedLeaderCheckIntervalInMillis().getValue()) .build(); return DistributedDataStoreFactory.createInstance("config", getConfigSchemaServiceDependency(), diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModule.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModule.java index ee1859d9ca..2a12aff4ef 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModule.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModule.java @@ -54,10 +54,17 @@ public class DistributedOperationalDataStoreProviderModule extends getValue().intValue()) .shardSnapshotBatchCount(props.getShardSnapshotBatchCount().getValue().intValue()) .shardHeartbeatIntervalInMillis(props.getShardHearbeatIntervalInMillis().getValue()) + .shardInitializationTimeout(props.getShardInitializationTimeoutInSeconds().getValue(), + TimeUnit.SECONDS) + .shardLeaderElectionTimeout(props.getShardLeaderElectionTimeoutInSeconds().getValue(), + TimeUnit.SECONDS) .shardTransactionCommitTimeoutInSeconds( props.getShardTransactionCommitTimeoutInSeconds().getValue().intValue()) .shardTransactionCommitQueueCapacity( props.getShardTransactionCommitQueueCapacity().getValue().intValue()) + .persistent(props.getPersistent().booleanValue()) + .shardIsolatedLeaderCheckIntervalInMillis( + props.getShardIsolatedLeaderCheckIntervalInMillis().getValue()) .build(); return DistributedDataStoreFactory.createInstance("operational", diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/yang/distributed-datastore-provider.yang b/opendaylight/md-sal/sal-distributed-datastore/src/main/yang/distributed-datastore-provider.yang index 167d530d18..4d3d438b32 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/yang/distributed-datastore-provider.yang +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/yang/distributed-datastore-provider.yang @@ -121,6 +121,21 @@ module distributed-datastore-provider { description "The maximum allowed capacity for each shard's transaction commit queue."; } + leaf shard-initialization-timeout-in-seconds { + default 300; // 5 minutes + type non-zero-uint32-type; + description "The maximum amount of time to wait for a shard to initialize from persistence + on startup before failing an operation (eg transaction create and change + listener registration)."; + } + + leaf shard-leader-election-timeout-in-seconds { + default 30; + type non-zero-uint32-type; + description "The maximum amount of time to wait for a shard to elect a leader before failing + an operation (eg transaction create)."; + } + leaf enable-metric-capture { default false; type boolean; @@ -132,6 +147,19 @@ module distributed-datastore-provider { type non-zero-uint32-type; description "Max queue size that an actor's mailbox can reach"; } + + leaf persistent { + default true; + type boolean; + description "Enable or disable data persistence"; + } + + leaf shard-isolated-leader-check-interval-in-millis { + default 5000; + type heartbeat-interval-type; + description "The interval at which the leader of the shard will check if its majority + followers are active and term itself as isolated"; + } } // Augments the 'configuration' choice node under modules/module. diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ConfigurationImplTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ConfigurationImplTest.java index 8c253596b8..afc060318c 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ConfigurationImplTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ConfigurationImplTest.java @@ -1,17 +1,15 @@ package org.opendaylight.controller.cluster.datastore; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import com.typesafe.config.ConfigFactory; -import junit.framework.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import java.io.File; import java.util.List; import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class ConfigurationImplTest { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxyTest.java index c79d762035..55250dd5e9 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxyTest.java @@ -3,6 +3,11 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorRef; import akka.actor.Props; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.messages.DataChanged; @@ -17,18 +22,12 @@ import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - public class DataChangeListenerProxyTest extends AbstractActorTest { private static class MockDataChangedEvent implements AsyncDataChangeEvent> { - Map> createdData = new HashMap(); - Map> updatedData = new HashMap(); - Map> originalData = new HashMap(); + Map> createdData = new HashMap<>(); + Map> updatedData = new HashMap<>(); + Map> originalData = new HashMap<>(); @@ -88,7 +87,7 @@ public class DataChangeListenerProxyTest extends AbstractActorTest { Assert.assertTrue(messages instanceof List); - List listMessages = (List) messages; + List listMessages = (List) messages; Assert.assertEquals(1, listMessages.size()); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxyTest.java index aaf080bdf7..9ac30095a5 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxyTest.java @@ -1,108 +1,257 @@ +/* + * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ package org.opendaylight.controller.cluster.datastore; +import java.util.concurrent.TimeUnit; import akka.actor.ActorRef; +import akka.actor.ActorSystem; import akka.actor.Props; -import junit.framework.Assert; +import akka.actor.Terminated; +import akka.dispatch.ExecutionContexts; +import akka.dispatch.Futures; +import akka.testkit.JavaTestKit; +import akka.util.Timeout; +import org.junit.Assert; import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized; import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistration; +import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard; +import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound; +import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound; +import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener; +import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply; import org.opendaylight.controller.cluster.datastore.utils.ActorContext; import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor; -import org.opendaylight.controller.cluster.datastore.utils.MessageCollectorActor; -import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper; -import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration; -import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; +import org.opendaylight.controller.md.cluster.datastore.model.TestModel; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.common.util.concurrent.Uninterruptibles; +import scala.concurrent.ExecutionContextExecutor; +import scala.concurrent.Future; +import scala.concurrent.duration.FiniteDuration; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.eq; -import java.util.List; +/** + * Unit tests for DataChangeListenerRegistrationProxy. + * + * @author Thomas Pantelis + */ +public class DataChangeListenerRegistrationProxyTest extends AbstractActorTest { -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertNotNull; -import static junit.framework.TestCase.assertTrue; + @SuppressWarnings("unchecked") + private final AsyncDataChangeListener> mockListener = + Mockito.mock(AsyncDataChangeListener.class); -public class DataChangeListenerRegistrationProxyTest extends AbstractActorTest{ + @Test + public void testGetInstance() throws Exception { + DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy( + "shard", Mockito.mock(ActorContext.class), mockListener); + + Assert.assertEquals(mockListener, proxy.getInstance()); + } + + @SuppressWarnings("unchecked") + @Test(timeout=10000) + public void testSuccessfulRegistration() { + new JavaTestKit(getSystem()) {{ + ActorContext actorContext = new ActorContext(getSystem(), getRef(), + mock(ClusterWrapper.class), mock(Configuration.class)); + + final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy( + "shard-1", actorContext, mockListener); + + final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME); + final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE; + new Thread() { + @Override + public void run() { + proxy.init(path, scope); + } + + }.start(); + + FiniteDuration timeout = duration("5 seconds"); + FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class); + Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName()); + + reply(new LocalShardFound(getRef())); + + RegisterChangeListener registerMsg = expectMsgClass(timeout, RegisterChangeListener.class); + Assert.assertEquals("getPath", path, registerMsg.getPath()); + Assert.assertEquals("getScope", scope, registerMsg.getScope()); + + reply(new RegisterChangeListenerReply(getRef().path())); + + for(int i = 0; (i < 20 * 5) && proxy.getListenerRegistrationActor() == null; i++) { + Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS); + } + + Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()), + proxy.getListenerRegistrationActor()); + + watch(proxy.getDataChangeListenerActor()); - private ActorRef dataChangeListenerActor = getSystem().actorOf(Props.create(DoNothingActor.class)); + proxy.close(); - private static class MockDataChangeListener implements - AsyncDataChangeListener> { + // The listener registration actor should get a Close message + expectMsgClass(timeout, CloseDataChangeListenerRegistration.SERIALIZABLE_CLASS); - @Override public void onDataChanged( - AsyncDataChangeEvent> change) { - throw new UnsupportedOperationException("onDataChanged"); - } + // The DataChangeListener actor should be terminated + expectMsgClass(timeout, Terminated.class); + + proxy.close(); + + expectNoMsg(); + }}; } - @Test - public void testGetInstance() throws Exception { - final Props props = Props.create(MessageCollectorActor.class); - final ActorRef actorRef = getSystem().actorOf(props); + @Test(timeout=10000) + public void testLocalShardNotFound() { + new JavaTestKit(getSystem()) {{ + ActorContext actorContext = new ActorContext(getSystem(), getRef(), + mock(ClusterWrapper.class), mock(Configuration.class)); - MockDataChangeListener listener = - new MockDataChangeListener(); - DataChangeListenerRegistrationProxy proxy = - new DataChangeListenerRegistrationProxy( - getSystem().actorSelection(actorRef.path()), - listener, dataChangeListenerActor); + final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy( + "shard-1", actorContext, mockListener); - Assert.assertEquals(listener, proxy.getInstance()); + final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME); + final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE; + new Thread() { + @Override + public void run() { + proxy.init(path, scope); + } + }.start(); + + FiniteDuration timeout = duration("5 seconds"); + FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class); + Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName()); + + reply(new LocalShardNotFound("shard-1")); + + expectNoMsg(duration("1 seconds")); + }}; } - @Test - public void testClose() throws Exception { - final Props props = Props.create(MessageCollectorActor.class); - final ActorRef actorRef = getSystem().actorOf(props); + @Test(timeout=10000) + public void testLocalShardNotInitialized() { + new JavaTestKit(getSystem()) {{ + ActorContext actorContext = new ActorContext(getSystem(), getRef(), + mock(ClusterWrapper.class), mock(Configuration.class)); - DataChangeListenerRegistrationProxy proxy = - new DataChangeListenerRegistrationProxy( - getSystem().actorSelection(actorRef.path()), - new MockDataChangeListener(), dataChangeListenerActor); + final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy( + "shard-1", actorContext, mockListener); - proxy.close(); + final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME); + final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE; + new Thread() { + @Override + public void run() { + proxy.init(path, scope); + } + + }.start(); + + FiniteDuration timeout = duration("5 seconds"); + FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class); + Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName()); + + reply(new ActorNotInitialized()); + + new Within(duration("1 seconds")) { + @Override + protected void run() { + expectNoMsg(); + } + }; + }}; + } + + @Test + public void testFailedRegistration() { + new JavaTestKit(getSystem()) {{ + ActorSystem mockActorSystem = mock(ActorSystem.class); - //Check if it was received by the remote actor - ActorContext - testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)),new MockClusterWrapper(), new MockConfiguration()); - Object messages = testContext - .executeOperation(actorRef, "messages"); + ActorRef mockActor = getSystem().actorOf(Props.create(DoNothingActor.class), + "testFailedRegistration"); + doReturn(mockActor).when(mockActorSystem).actorOf(any(Props.class)); + ExecutionContextExecutor executor = ExecutionContexts.fromExecutor( + MoreExecutors.sameThreadExecutor()); + doReturn(executor).when(mockActorSystem).dispatcher(); - assertNotNull(messages); + ActorContext actorContext = mock(ActorContext.class); - assertTrue(messages instanceof List); + String shardName = "shard-1"; + final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy( + shardName, actorContext, mockListener); - List listMessages = (List) messages; + doReturn(mockActorSystem).when(actorContext).getActorSystem(); + doReturn(duration("5 seconds")).when(actorContext).getOperationDuration(); + doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName)); + doReturn(Futures.failed(new RuntimeException("mock"))). + when(actorContext).executeOperationAsync(any(ActorRef.class), + any(Object.class), any(Timeout.class)); - assertEquals(1, listMessages.size()); + proxy.init(YangInstanceIdentifier.of(TestModel.TEST_QNAME), + AsyncDataBroker.DataChangeScope.ONE); - assertTrue(listMessages.get(0).getClass() - .equals(CloseDataChangeListenerRegistration.SERIALIZABLE_CLASS)); + Assert.assertEquals("getListenerRegistrationActor", null, + proxy.getListenerRegistrationActor()); + }}; } + @SuppressWarnings("unchecked") @Test - public void testCloseWhenRegistrationIsNull() throws Exception { - final Props props = Props.create(MessageCollectorActor.class); - final ActorRef actorRef = getSystem().actorOf(props); + public void testCloseBeforeRegistration() { + new JavaTestKit(getSystem()) {{ + ActorContext actorContext = mock(ActorContext.class); - DataChangeListenerRegistrationProxy proxy = - new DataChangeListenerRegistrationProxy( - new MockDataChangeListener(), dataChangeListenerActor); + String shardName = "shard-1"; + final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy( + shardName, actorContext, mockListener); - proxy.close(); + doReturn(DatastoreContext.newBuilder().build()).when(actorContext).getDatastoreContext(); + doReturn(getSystem()).when(actorContext).getActorSystem(); + doReturn(getSystem().actorSelection(getRef().path())). + when(actorContext).actorSelection(getRef().path()); + doReturn(duration("5 seconds")).when(actorContext).getOperationDuration(); + doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName)); - //Check if it was received by the remote actor - ActorContext - testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)),new MockClusterWrapper(), new MockConfiguration()); - Object messages = testContext - .executeOperation(actorRef, "messages"); + Answer> answer = new Answer>() { + @Override + public Future answer(InvocationOnMock invocation) { + proxy.close(); + return Futures.successful((Object)new RegisterChangeListenerReply(getRef().path())); + } + }; - assertNotNull(messages); + doAnswer(answer).when(actorContext).executeOperationAsync(any(ActorRef.class), + any(Object.class), any(Timeout.class)); - assertTrue(messages instanceof List); + proxy.init(YangInstanceIdentifier.of(TestModel.TEST_QNAME), + AsyncDataBroker.DataChangeScope.ONE); - List listMessages = (List) messages; + expectMsgClass(duration("5 seconds"), CloseDataChangeListenerRegistration.SERIALIZABLE_CLASS); - assertEquals(0, listMessages.size()); + Assert.assertEquals("getListenerRegistrationActor", null, + proxy.getListenerRegistrationActor()); + }}; } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerTest.java index 101a73782b..d5a12c73c5 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerTest.java @@ -4,6 +4,7 @@ import akka.actor.ActorRef; import akka.actor.DeadLetter; import akka.actor.Props; import akka.testkit.JavaTestKit; +import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.opendaylight.controller.cluster.datastore.messages.DataChanged; @@ -70,19 +71,25 @@ public class DataChangeListenerTest extends AbstractActorTest { final Props props = DataChangeListener.props(mockListener); final ActorRef subject = getSystem().actorOf(props, "testDataChangedWithNoSender"); - // Let the DataChangeListener know that notifications should be enabled - subject.tell(new EnableNotification(true), ActorRef.noSender()); + getSystem().eventStream().subscribe(getRef(), DeadLetter.class); subject.tell(new DataChanged(CompositeModel.createTestContext(), mockChangeEvent), ActorRef.noSender()); - getSystem().eventStream().subscribe(getRef(), DeadLetter.class); - new Within(duration("1 seconds")) { - @Override - protected void run() { - expectNoMsg(); + // Make sure no DataChangedReply is sent to DeadLetters. + while(true) { + DeadLetter deadLetter; + try { + deadLetter = expectMsgClass(duration("1 seconds"), DeadLetter.class); + } catch (AssertionError e) { + // Timed out - got no DeadLetter - this is good + break; } - }; + + // We may get DeadLetters for other messages we don't care about. + Assert.assertFalse("Unexpected DataChangedReply", + deadLetter.message() instanceof DataChangedReply); + } }}; } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java index 395021d361..9f5aded352 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java @@ -1,35 +1,54 @@ package org.opendaylight.controller.cluster.datastore; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import com.google.common.base.Optional; +import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Uninterruptibles; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; +import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException; +import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException; import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory; +import org.opendaylight.controller.cluster.datastore.utils.InMemoryJournal; import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper; +import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener; import org.opendaylight.controller.md.cluster.datastore.model.CarsModel; import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel; import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper; import org.opendaylight.controller.md.cluster.datastore.model.TestModel; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; +import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; +import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException; import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction; import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction; import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort; import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain; import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction; +import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.MapNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import java.util.concurrent.TimeUnit; public class DistributedDataStoreIntegrationTest extends AbstractActorTest { + private final DatastoreContext.Builder datastoreContextBuilder = + DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100); + @Test public void testWriteTransactionWithSingleShard() throws Exception{ - System.setProperty("shard.persistent", "true"); new IntegrationTestKit(getSystem()) {{ DistributedDataStore dataStore = setupDistributedDataStore("transactionIntegrationTest", "test-1"); @@ -46,7 +65,6 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { @Test public void testWriteTransactionWithMultipleShards() throws Exception{ - System.setProperty("shard.persistent", "true"); new IntegrationTestKit(getSystem()) {{ DistributedDataStore dataStore = setupDistributedDataStore("testWriteTransactionWithMultipleShards", "cars-1", "people-1"); @@ -64,12 +82,9 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { DOMStoreThreePhaseCommitCohort cohort = writeTx.ready(); - Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS); - assertEquals("canCommit", true, canCommit); - cohort.preCommit().get(5, TimeUnit.SECONDS); - cohort.commit().get(5, TimeUnit.SECONDS); + doCommit(cohort); - // 5. Verify the data in the store + // Verify the data in the store DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction(); @@ -92,7 +107,7 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { DistributedDataStore dataStore = setupDistributedDataStore("testReadWriteTransaction", "test-1"); - // 1. Create a read-write Tx + // 1. Create a read-write Tx DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction(); assertNotNull("newReadWriteTransaction returned null", readWriteTx); @@ -118,10 +133,7 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { // 5. Commit the Tx - Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS); - assertEquals("canCommit", true, canCommit); - cohort.preCommit().get(5, TimeUnit.SECONDS); - cohort.commit().get(5, TimeUnit.SECONDS); + doCommit(cohort); // 6. Verify the data in the store @@ -135,6 +147,381 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { }}; } + @Test + public void testTransactionWritesWithShardNotInitiallyReady() throws Exception{ + new IntegrationTestKit(getSystem()) {{ + String testName = "testTransactionWritesWithShardNotInitiallyReady"; + String shardName = "test-1"; + + // Setup the InMemoryJournal to block shard recovery to ensure the shard isn't + // initialized until we create and submit the write the Tx. + String persistentID = String.format("member-1-shard-%s-%s", shardName, testName); + CountDownLatch blockRecoveryLatch = new CountDownLatch(1); + InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch); + + DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName); + + // Create the write Tx + + final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction(); + assertNotNull("newReadWriteTransaction returned null", writeTx); + + // Do some modification operations and ready the Tx on a separate thread. + + final YangInstanceIdentifier listEntryPath = YangInstanceIdentifier.builder( + TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, + TestModel.ID_QNAME, 1).build(); + + final AtomicReference txCohort = new AtomicReference<>(); + final AtomicReference caughtEx = new AtomicReference<>(); + final CountDownLatch txReady = new CountDownLatch(1); + Thread txThread = new Thread() { + @Override + public void run() { + try { + writeTx.write(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + writeTx.merge(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder( + TestModel.OUTER_LIST_QNAME).build()); + + writeTx.write(listEntryPath, ImmutableNodes.mapEntry( + TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)); + + writeTx.delete(listEntryPath); + + txCohort.set(writeTx.ready()); + } catch(Exception e) { + caughtEx.set(e); + return; + } finally { + txReady.countDown(); + } + } + }; + + txThread.start(); + + // Wait for the Tx operations to complete. + + boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS); + if(caughtEx.get() != null) { + throw caughtEx.get(); + } + + assertEquals("Tx ready", true, done); + + // At this point the Tx operations should be waiting for the shard to initialize so + // trigger the latch to let the shard recovery to continue. + + blockRecoveryLatch.countDown(); + + // Wait for the Tx commit to complete. + + doCommit(txCohort.get()); + + // Verify the data in the store + + DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction(); + + Optional> optional = readTx.read(TestModel.TEST_PATH). + get(5, TimeUnit.SECONDS); + assertEquals("isPresent", true, optional.isPresent()); + + optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS); + assertEquals("isPresent", true, optional.isPresent()); + + optional = readTx.read(listEntryPath).get(5, TimeUnit.SECONDS); + assertEquals("isPresent", false, optional.isPresent()); + + cleanup(dataStore); + }}; + } + + @Test + public void testTransactionReadsWithShardNotInitiallyReady() throws Exception{ + new IntegrationTestKit(getSystem()) {{ + String testName = "testTransactionReadsWithShardNotInitiallyReady"; + String shardName = "test-1"; + + // Setup the InMemoryJournal to block shard recovery to ensure the shard isn't + // initialized until we create the Tx. + String persistentID = String.format("member-1-shard-%s-%s", shardName, testName); + CountDownLatch blockRecoveryLatch = new CountDownLatch(1); + InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch); + + DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName); + + // Create the read-write Tx + + final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction(); + assertNotNull("newReadWriteTransaction returned null", readWriteTx); + + // Do some reads on the Tx on a separate thread. + + final AtomicReference> txExistsFuture = + new AtomicReference<>(); + final AtomicReference>, ReadFailedException>> + txReadFuture = new AtomicReference<>(); + final AtomicReference caughtEx = new AtomicReference<>(); + final CountDownLatch txReadsDone = new CountDownLatch(1); + Thread txThread = new Thread() { + @Override + public void run() { + try { + readWriteTx.write(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + txExistsFuture.set(readWriteTx.exists(TestModel.TEST_PATH)); + + txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH)); + } catch(Exception e) { + caughtEx.set(e); + return; + } finally { + txReadsDone.countDown(); + } + } + }; + + txThread.start(); + + // Wait for the Tx operations to complete. + + boolean done = Uninterruptibles.awaitUninterruptibly(txReadsDone, 5, TimeUnit.SECONDS); + if(caughtEx.get() != null) { + throw caughtEx.get(); + } + + assertEquals("Tx reads done", true, done); + + // At this point the Tx operations should be waiting for the shard to initialize so + // trigger the latch to let the shard recovery to continue. + + blockRecoveryLatch.countDown(); + + // Wait for the reads to complete and verify. + + assertEquals("exists", true, txExistsFuture.get().checkedGet(5, TimeUnit.SECONDS)); + assertEquals("read", true, txReadFuture.get().checkedGet(5, TimeUnit.SECONDS).isPresent()); + + readWriteTx.close(); + + cleanup(dataStore); + }}; + } + + @Test(expected=NotInitializedException.class) + public void testTransactionCommitFailureWithShardNotInitialized() throws Throwable{ + new IntegrationTestKit(getSystem()) {{ + String testName = "testTransactionCommitFailureWithShardNotInitialized"; + String shardName = "test-1"; + + // Set the shard initialization timeout low for the test. + + datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS); + + // Setup the InMemoryJournal to block shard recovery indefinitely. + + String persistentID = String.format("member-1-shard-%s-%s", shardName, testName); + CountDownLatch blockRecoveryLatch = new CountDownLatch(1); + InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch); + + DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName); + + // Create the write Tx + + final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction(); + assertNotNull("newReadWriteTransaction returned null", writeTx); + + // Do some modifications and ready the Tx on a separate thread. + + final AtomicReference txCohort = new AtomicReference<>(); + final AtomicReference caughtEx = new AtomicReference<>(); + final CountDownLatch txReady = new CountDownLatch(1); + Thread txThread = new Thread() { + @Override + public void run() { + try { + writeTx.write(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + txCohort.set(writeTx.ready()); + } catch(Exception e) { + caughtEx.set(e); + return; + } finally { + txReady.countDown(); + } + } + }; + + txThread.start(); + + // Wait for the Tx operations to complete. + + boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS); + if(caughtEx.get() != null) { + throw caughtEx.get(); + } + + assertEquals("Tx ready", true, done); + + // Wait for the commit to complete. Since the shard never initialized, the Tx should + // have timed out and throw an appropriate exception cause. + + try { + txCohort.get().canCommit().get(5, TimeUnit.SECONDS); + } catch(ExecutionException e) { + throw e.getCause(); + } finally { + blockRecoveryLatch.countDown(); + cleanup(dataStore); + } + }}; + } + + @Test(expected=NotInitializedException.class) + public void testTransactionReadFailureWithShardNotInitialized() throws Throwable{ + new IntegrationTestKit(getSystem()) {{ + String testName = "testTransactionReadFailureWithShardNotInitialized"; + String shardName = "test-1"; + + // Set the shard initialization timeout low for the test. + + datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS); + + // Setup the InMemoryJournal to block shard recovery indefinitely. + + String persistentID = String.format("member-1-shard-%s-%s", shardName, testName); + CountDownLatch blockRecoveryLatch = new CountDownLatch(1); + InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch); + + DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName); + + // Create the read-write Tx + + final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction(); + assertNotNull("newReadWriteTransaction returned null", readWriteTx); + + // Do a read on the Tx on a separate thread. + + final AtomicReference>, ReadFailedException>> + txReadFuture = new AtomicReference<>(); + final AtomicReference caughtEx = new AtomicReference<>(); + final CountDownLatch txReadDone = new CountDownLatch(1); + Thread txThread = new Thread() { + @Override + public void run() { + try { + readWriteTx.write(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH)); + + readWriteTx.close(); + } catch(Exception e) { + caughtEx.set(e); + return; + } finally { + txReadDone.countDown(); + } + } + }; + + txThread.start(); + + // Wait for the Tx operations to complete. + + boolean done = Uninterruptibles.awaitUninterruptibly(txReadDone, 5, TimeUnit.SECONDS); + if(caughtEx.get() != null) { + throw caughtEx.get(); + } + + assertEquals("Tx read done", true, done); + + // Wait for the read to complete. Since the shard never initialized, the Tx should + // have timed out and throw an appropriate exception cause. + + try { + txReadFuture.get().checkedGet(5, TimeUnit.SECONDS); + } catch(ReadFailedException e) { + throw e.getCause(); + } finally { + blockRecoveryLatch.countDown(); + cleanup(dataStore); + } + }}; + } + + @Test(expected=NoShardLeaderException.class) + public void testTransactionCommitFailureWithNoShardLeader() throws Throwable{ + new IntegrationTestKit(getSystem()) {{ + String testName = "testTransactionCommitFailureWithNoShardLeader"; + String shardName = "test-1"; + + // We don't want the shard to become the leader so prevent shard election from completing + // by setting the election timeout, which is based on the heartbeat interval, really high. + + datastoreContextBuilder.shardHeartbeatIntervalInMillis(30000); + + // Set the leader election timeout low for the test. + + datastoreContextBuilder.shardLeaderElectionTimeout(1, TimeUnit.MILLISECONDS); + + DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName); + + // Create the write Tx. + + final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction(); + assertNotNull("newReadWriteTransaction returned null", writeTx); + + // Do some modifications and ready the Tx on a separate thread. + + final AtomicReference txCohort = new AtomicReference<>(); + final AtomicReference caughtEx = new AtomicReference<>(); + final CountDownLatch txReady = new CountDownLatch(1); + Thread txThread = new Thread() { + @Override + public void run() { + try { + writeTx.write(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + txCohort.set(writeTx.ready()); + } catch(Exception e) { + caughtEx.set(e); + return; + } finally { + txReady.countDown(); + } + } + }; + + txThread.start(); + + // Wait for the Tx operations to complete. + + boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS); + if(caughtEx.get() != null) { + throw caughtEx.get(); + } + + assertEquals("Tx ready", true, done); + + // Wait for the commit to complete. Since no shard leader was elected in time, the Tx + // should have timed out and throw an appropriate exception cause. + + try { + txCohort.get().canCommit().get(5, TimeUnit.SECONDS); + } catch(ExecutionException e) { + throw e.getCause(); + } finally { + cleanup(dataStore); + } + }}; + } + @Test public void testTransactionAbort() throws Exception{ System.setProperty("shard.persistent", "true"); @@ -162,10 +549,8 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { @Test public void testTransactionChain() throws Exception{ - System.setProperty("shard.persistent", "true"); new IntegrationTestKit(getSystem()) {{ - DistributedDataStore dataStore = - setupDistributedDataStore("transactionChainIntegrationTest", "test-1"); + DistributedDataStore dataStore = setupDistributedDataStore("testTransactionChain", "test-1"); // 1. Create a Tx chain and write-only Tx @@ -176,27 +561,127 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { // 2. Write some data - NormalizedNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - writeTx.write(TestModel.TEST_PATH, containerNode); + NormalizedNode testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME); + writeTx.write(TestModel.TEST_PATH, testNode); // 3. Ready the Tx for commit - DOMStoreThreePhaseCommitCohort cohort = writeTx.ready(); + final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready(); + + // 4. Commit the Tx on another thread that first waits for the second read Tx. + + final CountDownLatch continueCommit1 = new CountDownLatch(1); + final CountDownLatch commit1Done = new CountDownLatch(1); + final AtomicReference commit1Error = new AtomicReference<>(); + new Thread() { + @Override + public void run() { + try { + continueCommit1.await(); + doCommit(cohort1); + } catch (Exception e) { + commit1Error.set(e); + } finally { + commit1Done.countDown(); + } + } + }.start(); - // 4. Commit the Tx + // 5. Create a new read Tx from the chain to read and verify the data from the first + // Tx is visible after being readied. - Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS); - assertEquals("canCommit", true, canCommit); - cohort.preCommit().get(5, TimeUnit.SECONDS); - cohort.commit().get(5, TimeUnit.SECONDS); + DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction(); + Optional> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS); + assertEquals("isPresent", true, optional.isPresent()); + assertEquals("Data node", testNode, optional.get()); - // 5. Verify the data in the store + // 6. Create a new RW Tx from the chain, write more data, and ready it - DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction(); + DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction(); + MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(); + rwTx.write(TestModel.OUTER_LIST_PATH, outerNode); - Optional> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS); + DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready(); + + // 7. Create a new read Tx from the chain to read the data from the last RW Tx to + // verify it is visible. + + readTx = txChain.newReadWriteTransaction(); + optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS); + assertEquals("isPresent", true, optional.isPresent()); + assertEquals("Data node", outerNode, optional.get()); + + // 8. Wait for the 2 commits to complete and close the chain. + + continueCommit1.countDown(); + Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS); + + if(commit1Error.get() != null) { + throw commit1Error.get(); + } + + doCommit(cohort2); + + txChain.close(); + + // 9. Create a new read Tx from the data store and verify committed data. + + readTx = dataStore.newReadOnlyTransaction(); + optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS); assertEquals("isPresent", true, optional.isPresent()); - assertEquals("Data node", containerNode, optional.get()); + assertEquals("Data node", outerNode, optional.get()); + + cleanup(dataStore); + }}; + } + + @Test + public void testCreateChainedTransactionsInQuickSuccession() throws Exception{ + new IntegrationTestKit(getSystem()) {{ + DistributedDataStore dataStore = setupDistributedDataStore( + "testCreateChainedTransactionsInQuickSuccession", "test-1"); + + DOMStoreTransactionChain txChain = dataStore.createTransactionChain(); + + NormalizedNode testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME); + + int nTxs = 20; + List cohorts = new ArrayList<>(nTxs); + for(int i = 0; i < nTxs; i++) { + DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction(); + + rwTx.merge(TestModel.TEST_PATH, testNode); + + cohorts.add(rwTx.ready()); + + } + + for(DOMStoreThreePhaseCommitCohort cohort: cohorts) { + doCommit(cohort); + } + + txChain.close(); + + cleanup(dataStore); + }}; + } + + @Test + public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception{ + new IntegrationTestKit(getSystem()) {{ + DistributedDataStore dataStore = setupDistributedDataStore( + "testCreateChainedTransactionAfterEmptyTxReadied", "test-1"); + + DOMStoreTransactionChain txChain = dataStore.createTransactionChain(); + + DOMStoreReadWriteTransaction rwTx1 = txChain.newReadWriteTransaction(); + + rwTx1.ready(); + + DOMStoreReadWriteTransaction rwTx2 = txChain.newReadWriteTransaction(); + + Optional> optional = rwTx2.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS); + assertEquals("isPresent", false, optional.isPresent()); txChain.close(); @@ -204,6 +689,91 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { }}; } + @Test + public void testCreateChainedTransactionWhenPreviousNotReady() throws Throwable { + new IntegrationTestKit(getSystem()) {{ + DistributedDataStore dataStore = setupDistributedDataStore( + "testCreateChainedTransactionWhenPreviousNotReady", "test-1"); + + final DOMStoreTransactionChain txChain = dataStore.createTransactionChain(); + + DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction(); + assertNotNull("newWriteOnlyTransaction returned null", writeTx); + + writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + // Try to create another Tx of each type - each should fail b/c the previous Tx wasn't + // readied. + + assertExceptionOnTxChainCreates(txChain, IllegalStateException.class); + }}; + } + + @Test + public void testCreateChainedTransactionAfterClose() throws Throwable { + new IntegrationTestKit(getSystem()) {{ + DistributedDataStore dataStore = setupDistributedDataStore( + "testCreateChainedTransactionAfterClose", "test-1"); + + DOMStoreTransactionChain txChain = dataStore.createTransactionChain(); + + txChain.close(); + + // Try to create another Tx of each type - should fail b/c the previous Tx was closed. + + assertExceptionOnTxChainCreates(txChain, TransactionChainClosedException.class); + }}; + } + + @Test + public void testChangeListenerRegistration() throws Exception{ + new IntegrationTestKit(getSystem()) {{ + DistributedDataStore dataStore = + setupDistributedDataStore("testChangeListenerRegistration", "test-1"); + + testWriteTransaction(dataStore, TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + MockDataChangeListener listener = new MockDataChangeListener(1); + + ListenerRegistration + listenerReg = dataStore.registerChangeListener(TestModel.TEST_PATH, listener, + DataChangeScope.SUBTREE); + + assertNotNull("registerChangeListener returned null", listenerReg); + + // Wait for the initial notification + + listener.waitForChangeEvents(TestModel.TEST_PATH); + + listener.reset(2); + + // Write 2 updates. + + testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH, + ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build()); + + YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH). + nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(); + testWriteTransaction(dataStore, listPath, + ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)); + + // Wait for the 2 updates. + + listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath); + + listenerReg.close(); + + testWriteTransaction(dataStore, YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH). + nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build(), + ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2)); + + listener.expectNoMoreChanges("Received unexpected change after close"); + + cleanup(dataStore); + }}; + } + class IntegrationTestKit extends ShardTestKit { IntegrationTestKit(ActorSystem actorSystem) { @@ -211,31 +781,37 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { } DistributedDataStore setupDistributedDataStore(String typeName, String... shardNames) { + return setupDistributedDataStore(typeName, true, shardNames); + } + + DistributedDataStore setupDistributedDataStore(String typeName, boolean waitUntilLeader, + String... shardNames) { MockClusterWrapper cluster = new MockClusterWrapper(); Configuration config = new ConfigurationImpl("module-shards.conf", "modules.conf"); ShardStrategyFactory.setConfiguration(config); - DatastoreContext datastoreContext = DatastoreContext.newBuilder().build(); + DatastoreContext datastoreContext = datastoreContextBuilder.build(); DistributedDataStore dataStore = new DistributedDataStore(getSystem(), typeName, cluster, config, datastoreContext); SchemaContext schemaContext = SchemaContextHelper.full(); dataStore.onGlobalContextUpdated(schemaContext); - for(String shardName: shardNames) { - ActorRef shard = null; - for(int i = 0; i < 20 * 5 && shard == null; i++) { - Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS); - Optional shardReply = dataStore.getActorContext().findLocalShard(shardName); - if(shardReply.isPresent()) { - shard = shardReply.get(); + if(waitUntilLeader) { + for(String shardName: shardNames) { + ActorRef shard = null; + for(int i = 0; i < 20 * 5 && shard == null; i++) { + Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS); + Optional shardReply = dataStore.getActorContext().findLocalShard(shardName); + if(shardReply.isPresent()) { + shard = shardReply.get(); + } } - } - assertNotNull("Shard was not created", shard); + assertNotNull("Shard was not created", shard); - System.out.println("!!!!!!shard: "+shard.path().toString()); - waitUntilLeader(shard); + waitUntilLeader(shard); + } } return dataStore; @@ -259,10 +835,7 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { // 4. Commit the Tx - Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS); - assertEquals("canCommit", true, canCommit); - cohort.preCommit().get(5, TimeUnit.SECONDS); - cohort.commit().get(5, TimeUnit.SECONDS); + doCommit(cohort); // 5. Verify the data in the store @@ -273,9 +846,53 @@ public class DistributedDataStoreIntegrationTest extends AbstractActorTest { assertEquals("Data node", nodeToWrite, optional.get()); } + void doCommit(final DOMStoreThreePhaseCommitCohort cohort) throws Exception { + Boolean canCommit = cohort.canCommit().get(5, TimeUnit.SECONDS); + assertEquals("canCommit", true, canCommit); + cohort.preCommit().get(5, TimeUnit.SECONDS); + cohort.commit().get(5, TimeUnit.SECONDS); + } + void cleanup(DistributedDataStore dataStore) { dataStore.getActorContext().getShardManager().tell(PoisonPill.getInstance(), null); } + + void assertExceptionOnCall(Callable callable, Class expType) + throws Exception { + try { + callable.call(); + fail("Expected " + expType.getSimpleName()); + } catch(Exception e) { + assertEquals("Exception type", expType, e.getClass()); + } + } + + void assertExceptionOnTxChainCreates(final DOMStoreTransactionChain txChain, + Class expType) throws Exception { + assertExceptionOnCall(new Callable() { + @Override + public Void call() throws Exception { + txChain.newWriteOnlyTransaction(); + return null; + } + }, expType); + + assertExceptionOnCall(new Callable() { + @Override + public Void call() throws Exception { + txChain.newReadWriteTransaction(); + return null; + } + }, expType); + + assertExceptionOnCall(new Callable() { + @Override + public Void call() throws Exception { + txChain.newReadOnlyTransaction(); + return null; + } + }, expType); + } } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreTest.java deleted file mode 100644 index 00243ea5d1..0000000000 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreTest.java +++ /dev/null @@ -1,244 +0,0 @@ -package org.opendaylight.controller.cluster.datastore; - -import akka.actor.ActorPath; -import akka.actor.ActorRef; -import akka.actor.ActorSelection; -import akka.actor.ActorSystem; -import akka.actor.Props; -import akka.dispatch.ExecutionContexts; -import akka.dispatch.Futures; -import akka.util.Timeout; -import com.google.common.base.Optional; -import com.google.common.util.concurrent.MoreExecutors; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply; -import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory; -import org.opendaylight.controller.cluster.datastore.utils.ActorContext; -import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor; -import org.opendaylight.controller.cluster.datastore.utils.MockActorContext; -import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration; -import org.opendaylight.controller.md.cluster.datastore.model.TestModel; -import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker; -import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; -import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener; -import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply; -import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction; -import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction; -import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain; -import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import scala.concurrent.ExecutionContextExecutor; -import scala.concurrent.Future; -import scala.concurrent.duration.FiniteDuration; -import java.util.concurrent.TimeUnit; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertNull; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class DistributedDataStoreTest extends AbstractActorTest{ - - private DistributedDataStore distributedDataStore; - private MockActorContext mockActorContext; - private ActorRef doNothingActorRef; - - @Before - public void setUp() throws Exception { - ShardStrategyFactory.setConfiguration(new MockConfiguration()); - final Props props = Props.create(DoNothingActor.class); - - doNothingActorRef = getSystem().actorOf(props); - - mockActorContext = new MockActorContext(getSystem(), doNothingActorRef); - distributedDataStore = new DistributedDataStore(mockActorContext); - distributedDataStore.onGlobalContextUpdated( - TestModel.createTestContext()); - - // Make CreateTransactionReply as the default response. Will need to be - // tuned if a specific test requires some other response - mockActorContext.setExecuteShardOperationResponse( - CreateTransactionReply.newBuilder() - .setTransactionActorPath(doNothingActorRef.path().toString()) - .setTransactionId("txn-1 ") - .build()); - } - - @After - public void tearDown() throws Exception { - - } - - @SuppressWarnings("resource") - @Test - public void testConstructor(){ - ActorSystem actorSystem = mock(ActorSystem.class); - - new DistributedDataStore(actorSystem, "config", - mock(ClusterWrapper.class), mock(Configuration.class), - DatastoreContext.newBuilder().build()); - - verify(actorSystem).actorOf(any(Props.class), eq("shardmanager-config")); - } - - @Test - public void testRegisterChangeListenerWhenShardIsNotLocal() throws Exception { - - ListenerRegistration registration = - distributedDataStore.registerChangeListener(TestModel.TEST_PATH, new AsyncDataChangeListener>() { - @Override - public void onDataChanged(AsyncDataChangeEvent> change) { - throw new UnsupportedOperationException("onDataChanged"); - } - }, AsyncDataBroker.DataChangeScope.BASE); - - // Since we do not expect the shard to be local registration will return a NoOpRegistration - assertTrue(registration instanceof NoOpDataChangeListenerRegistration); - - assertNotNull(registration); - } - - @Test - public void testRegisterChangeListenerWhenShardIsLocal() throws Exception { - ActorContext actorContext = mock(ActorContext.class); - - distributedDataStore = new DistributedDataStore(actorContext); - distributedDataStore.onGlobalContextUpdated(TestModel.createTestContext()); - - Future future = mock(Future.class); - when(actorContext.getOperationDuration()).thenReturn(FiniteDuration.apply(5, TimeUnit.SECONDS)); - when(actorContext.getActorSystem()).thenReturn(getSystem()); - when(actorContext.findLocalShard(anyString())).thenReturn(Optional.of(doNothingActorRef)); - when(actorContext - .executeOperationAsync(eq(doNothingActorRef), anyObject(), any(Timeout.class))).thenReturn(future); - - ListenerRegistration registration = - distributedDataStore.registerChangeListener(TestModel.TEST_PATH, - mock(AsyncDataChangeListener.class), - AsyncDataBroker.DataChangeScope.BASE); - - assertNotNull(registration); - - assertEquals(DataChangeListenerRegistrationProxy.class, registration.getClass()); - } - - @Test - public void testRegisterChangeListenerWhenSuccessfulReplyReceived() throws Exception { - ActorContext actorContext = mock(ActorContext.class); - - distributedDataStore = new DistributedDataStore(actorContext); - distributedDataStore.onGlobalContextUpdated( - TestModel.createTestContext()); - - ExecutionContextExecutor executor = ExecutionContexts.fromExecutor(MoreExecutors.sameThreadExecutor()); - - // Make Future successful - Future f = Futures.successful(new RegisterChangeListenerReply(doNothingActorRef.path())); - - // Setup the mocks - ActorSystem actorSystem = mock(ActorSystem.class); - ActorSelection actorSelection = mock(ActorSelection.class); - - when(actorContext.getOperationDuration()).thenReturn(FiniteDuration.apply(5, TimeUnit.SECONDS)); - when(actorSystem.dispatcher()).thenReturn(executor); - when(actorSystem.actorOf(any(Props.class))).thenReturn(doNothingActorRef); - when(actorContext.getActorSystem()).thenReturn(actorSystem); - when(actorContext.findLocalShard(anyString())).thenReturn(Optional.of(doNothingActorRef)); - when(actorContext - .executeOperationAsync(eq(doNothingActorRef), anyObject(), any(Timeout.class))).thenReturn(f); - when(actorContext.actorSelection(any(ActorPath.class))).thenReturn(actorSelection); - - ListenerRegistration registration = - distributedDataStore.registerChangeListener(TestModel.TEST_PATH, - mock(AsyncDataChangeListener.class), - AsyncDataBroker.DataChangeScope.BASE); - - assertNotNull(registration); - - assertEquals(DataChangeListenerRegistrationProxy.class, registration.getClass()); - - ActorSelection listenerRegistrationActor = - ((DataChangeListenerRegistrationProxy) registration).getListenerRegistrationActor(); - - assertNotNull(listenerRegistrationActor); - - assertEquals(actorSelection, listenerRegistrationActor); - } - - @Test - public void testRegisterChangeListenerWhenSuccessfulReplyFailed() throws Exception { - ActorContext actorContext = mock(ActorContext.class); - - distributedDataStore = new DistributedDataStore(actorContext); - distributedDataStore.onGlobalContextUpdated( - TestModel.createTestContext()); - - ExecutionContextExecutor executor = ExecutionContexts.fromExecutor(MoreExecutors.sameThreadExecutor()); - - // Make Future fail - Future f = Futures.failed(new IllegalArgumentException()); - - // Setup the mocks - ActorSystem actorSystem = mock(ActorSystem.class); - ActorSelection actorSelection = mock(ActorSelection.class); - - when(actorContext.getOperationDuration()).thenReturn(FiniteDuration.apply(5, TimeUnit.SECONDS)); - when(actorSystem.dispatcher()).thenReturn(executor); - when(actorSystem.actorOf(any(Props.class))).thenReturn(doNothingActorRef); - when(actorContext.getActorSystem()).thenReturn(actorSystem); - when(actorContext.findLocalShard(anyString())).thenReturn(Optional.of(doNothingActorRef)); - when(actorContext - .executeOperationAsync(eq(doNothingActorRef), anyObject(), any(Timeout.class))).thenReturn(f); - when(actorContext.actorSelection(any(ActorPath.class))).thenReturn(actorSelection); - - ListenerRegistration registration = - distributedDataStore.registerChangeListener(TestModel.TEST_PATH, - mock(AsyncDataChangeListener.class), - AsyncDataBroker.DataChangeScope.BASE); - - assertNotNull(registration); - - assertEquals(DataChangeListenerRegistrationProxy.class, registration.getClass()); - - ActorSelection listenerRegistrationActor = - ((DataChangeListenerRegistrationProxy) registration).getListenerRegistrationActor(); - - assertNull(listenerRegistrationActor); - - } - - - @Test - public void testCreateTransactionChain() throws Exception { - final DOMStoreTransactionChain transactionChain = distributedDataStore.createTransactionChain(); - assertNotNull(transactionChain); - } - - @Test - public void testNewReadOnlyTransaction() throws Exception { - final DOMStoreReadTransaction transaction = distributedDataStore.newReadOnlyTransaction(); - assertNotNull(transaction); - } - - @Test - public void testNewWriteOnlyTransaction() throws Exception { - final DOMStoreWriteTransaction transaction = distributedDataStore.newWriteOnlyTransaction(); - assertNotNull(transaction); - } - - @Test - public void testNewReadWriteTransaction() throws Exception { - final DOMStoreReadWriteTransaction transaction = distributedDataStore.newReadWriteTransaction(); - assertNotNull(transaction); - } -} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardManagerTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardManagerTest.java index 5022d97997..e70d79c61a 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardManagerTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardManagerTest.java @@ -2,16 +2,19 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorRef; import akka.actor.Props; +import akka.japi.Creator; +import akka.pattern.Patterns; import akka.persistence.RecoveryCompleted; import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; -import akka.japi.Creator; +import akka.util.Timeout; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Uninterruptibles; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier; import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized; import org.opendaylight.controller.cluster.datastore.messages.ActorNotInitialized; @@ -29,6 +32,9 @@ import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration; import org.opendaylight.controller.md.cluster.datastore.model.TestModel; import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier; import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import scala.concurrent.Await; +import scala.concurrent.Future; + import java.net.URI; import java.util.Collection; import java.util.HashSet; @@ -36,7 +42,9 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; + import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -76,7 +84,7 @@ public class ShardManagerTest extends AbstractActorTest { shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); - shardManager.tell(new FindPrimary("non-existent").toSerializable(), getRef()); + shardManager.tell(new FindPrimary("non-existent", false).toSerializable(), getRef()); expectMsgEquals(duration("5 seconds"), new PrimaryNotFound("non-existent").toSerializable()); @@ -91,25 +99,44 @@ public class ShardManagerTest extends AbstractActorTest { shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); shardManager.tell(new ActorInitialized(), mockShardActor); - shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME).toSerializable(), getRef()); + shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false).toSerializable(), getRef()); expectMsgClass(duration("5 seconds"), PrimaryFound.SERIALIZABLE_CLASS); }}; } @Test - public void testOnReceiveFindPrimaryForNotInitialzedShard() throws Exception { + public void testOnReceiveFindPrimaryForNotInitializedShard() throws Exception { new JavaTestKit(getSystem()) {{ final ActorRef shardManager = getSystem().actorOf(newShardMgrProps()); shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); - shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME).toSerializable(), getRef()); + shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false).toSerializable(), getRef()); expectMsgClass(duration("5 seconds"), ActorNotInitialized.class); }}; } + @Test + public void testOnReceiveFindPrimaryWaitForShardInitialized() throws Exception { + new JavaTestKit(getSystem()) {{ + final ActorRef shardManager = getSystem().actorOf(newShardMgrProps()); + + shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); + + // We're passing waitUntilInitialized = true to FindPrimary so the response should be + // delayed until we send ActorInitialized. + Future future = Patterns.ask(shardManager, new FindPrimary(Shard.DEFAULT_NAME, true), + new Timeout(5, TimeUnit.SECONDS)); + + shardManager.tell(new ActorInitialized(), mockShardActor); + + Object resp = Await.result(future, duration("5 seconds")); + assertTrue("Expected: PrimaryFound, Actual: " + resp, resp instanceof PrimaryFound); + }}; + } + @Test public void testOnReceiveFindLocalShardForNonExistentShard() throws Exception { new JavaTestKit(getSystem()) {{ @@ -117,7 +144,7 @@ public class ShardManagerTest extends AbstractActorTest { shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); - shardManager.tell(new FindLocalShard("non-existent"), getRef()); + shardManager.tell(new FindLocalShard("non-existent", false), getRef()); LocalShardNotFound notFound = expectMsgClass(duration("5 seconds"), LocalShardNotFound.class); @@ -133,7 +160,7 @@ public class ShardManagerTest extends AbstractActorTest { shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); shardManager.tell(new ActorInitialized(), mockShardActor); - shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME), getRef()); + shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef()); LocalShardFound found = expectMsgClass(duration("5 seconds"), LocalShardFound.class); @@ -148,14 +175,32 @@ public class ShardManagerTest extends AbstractActorTest { final ActorRef shardManager = getSystem().actorOf(newShardMgrProps()); shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); - //shardManager.tell(new ActorInitialized(), mockShardActor); - shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME), getRef()); + shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef()); expectMsgClass(duration("5 seconds"), ActorNotInitialized.class); }}; } + @Test + public void testOnReceiveFindLocalShardWaitForShardInitialized() throws Exception { + new JavaTestKit(getSystem()) {{ + final ActorRef shardManager = getSystem().actorOf(newShardMgrProps()); + + shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); + + // We're passing waitUntilInitialized = true to FindLocalShard so the response should be + // delayed until we send ActorInitialized. + Future future = Patterns.ask(shardManager, new FindLocalShard(Shard.DEFAULT_NAME, true), + new Timeout(5, TimeUnit.SECONDS)); + + shardManager.tell(new ActorInitialized(), mockShardActor); + + Object resp = Await.result(future, duration("5 seconds")); + assertTrue("Expected: LocalShardFound, Actual: " + resp, resp instanceof LocalShardFound); + }}; + } + @Test public void testOnReceiveMemberUp() throws Exception { new JavaTestKit(getSystem()) {{ @@ -163,7 +208,7 @@ public class ShardManagerTest extends AbstractActorTest { MockClusterWrapper.sendMemberUp(shardManager, "member-2", getRef().path().toString()); - shardManager.tell(new FindPrimary("astronauts").toSerializable(), getRef()); + shardManager.tell(new FindPrimary("astronauts", false).toSerializable(), getRef()); PrimaryFound found = PrimaryFound.fromSerializable(expectMsgClass(duration("5 seconds"), PrimaryFound.SERIALIZABLE_CLASS)); @@ -180,13 +225,13 @@ public class ShardManagerTest extends AbstractActorTest { MockClusterWrapper.sendMemberUp(shardManager, "member-2", getRef().path().toString()); - shardManager.tell(new FindPrimary("astronauts").toSerializable(), getRef()); + shardManager.tell(new FindPrimary("astronauts", false).toSerializable(), getRef()); expectMsgClass(duration("5 seconds"), PrimaryFound.SERIALIZABLE_CLASS); MockClusterWrapper.sendMemberRemoved(shardManager, "member-2", getRef().path().toString()); - shardManager.tell(new FindPrimary("astronauts").toSerializable(), getRef()); + shardManager.tell(new FindPrimary("astronauts", false).toSerializable(), getRef()); expectMsgClass(duration("5 seconds"), PrimaryNotFound.SERIALIZABLE_CLASS); }}; @@ -306,6 +351,80 @@ public class ShardManagerTest extends AbstractActorTest { }}; } + @Test + public void testRecoveryApplicable(){ + new JavaTestKit(getSystem()) { + { + final Props persistentProps = ShardManager.props(shardMrgIDSuffix, + new MockClusterWrapper(), + new MockConfiguration(), + DatastoreContext.newBuilder().persistent(true).build()); + final TestActorRef persistentShardManager = + TestActorRef.create(getSystem(), persistentProps); + + DataPersistenceProvider dataPersistenceProvider1 = persistentShardManager.underlyingActor().getDataPersistenceProvider(); + + assertTrue("Recovery Applicable", dataPersistenceProvider1.isRecoveryApplicable()); + + final Props nonPersistentProps = ShardManager.props(shardMrgIDSuffix, + new MockClusterWrapper(), + new MockConfiguration(), + DatastoreContext.newBuilder().persistent(false).build()); + final TestActorRef nonPersistentShardManager = + TestActorRef.create(getSystem(), nonPersistentProps); + + DataPersistenceProvider dataPersistenceProvider2 = nonPersistentShardManager.underlyingActor().getDataPersistenceProvider(); + + assertFalse("Recovery Not Applicable", dataPersistenceProvider2.isRecoveryApplicable()); + + + }}; + + } + + @Test + public void testOnUpdateSchemaContextUpdateKnownModulesCallsDataPersistenceProvider() + throws Exception { + final CountDownLatch persistLatch = new CountDownLatch(1); + final Creator creator = new Creator() { + private static final long serialVersionUID = 1L; + @Override + public ShardManager create() throws Exception { + return new ShardManager(shardMrgIDSuffix, new MockClusterWrapper(), new MockConfiguration(), DatastoreContext.newBuilder().build()) { + @Override + protected DataPersistenceProvider createDataPersistenceProvider(boolean persistent) { + DataPersistenceProviderMonitor dataPersistenceProviderMonitor + = new DataPersistenceProviderMonitor(); + dataPersistenceProviderMonitor.setPersistLatch(persistLatch); + return dataPersistenceProviderMonitor; + } + }; + } + }; + + new JavaTestKit(getSystem()) {{ + + final TestActorRef shardManager = + TestActorRef.create(getSystem(), Props.create(new DelegatingShardManagerCreator(creator))); + + ModuleIdentifier foo = mock(ModuleIdentifier.class); + when(foo.getNamespace()).thenReturn(new URI("foo")); + + Set moduleIdentifierSet = new HashSet<>(); + moduleIdentifierSet.add(foo); + + SchemaContext schemaContext = mock(SchemaContext.class); + when(schemaContext.getAllModuleIdentifiers()).thenReturn(moduleIdentifierSet); + + shardManager.underlyingActor().onReceiveCommand(new UpdateSchemaContext(schemaContext)); + + assertEquals("Persisted", true, + Uninterruptibles.awaitUninterruptibly(persistLatch, 5, TimeUnit.SECONDS)); + + }}; + } + + private static class TestShardManager extends ShardManager { private final CountDownLatch recoveryComplete = new CountDownLatch(1); @@ -346,4 +465,18 @@ public class ShardManagerTest extends AbstractActorTest { } } + + private static class DelegatingShardManagerCreator implements Creator { + private static final long serialVersionUID = 1L; + private Creator delegate; + + public DelegatingShardManagerCreator(Creator delegate) { + this.delegate = delegate; + } + + @Override + public ShardManager create() throws Exception { + return delegate.create(); + } + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java index 9b4f77b7c4..e5b5643297 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java @@ -1,12 +1,23 @@ package org.opendaylight.controller.cluster.datastore; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.opendaylight.controller.cluster.datastore.messages.CreateTransaction.CURRENT_VERSION; import akka.actor.ActorRef; +import akka.actor.PoisonPill; import akka.actor.Props; import akka.dispatch.Dispatchers; import akka.dispatch.OnComplete; import akka.japi.Creator; import akka.pattern.Patterns; -import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import akka.util.Timeout; import com.google.common.base.Function; @@ -15,6 +26,17 @@ import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; +import com.google.common.util.concurrent.Uninterruptibles; +import java.io.IOException; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -29,7 +51,6 @@ import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransacti import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction; import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply; import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction; -import org.opendaylight.controller.cluster.datastore.messages.EnableNotification; import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction; import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved; import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply; @@ -43,6 +64,7 @@ import org.opendaylight.controller.cluster.datastore.modification.WriteModificat import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec; import org.opendaylight.controller.cluster.datastore.utils.InMemoryJournal; import org.opendaylight.controller.cluster.datastore.utils.InMemorySnapshotStore; +import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener; import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry; import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry; import org.opendaylight.controller.cluster.raft.Snapshot; @@ -50,6 +72,9 @@ import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries; import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot; import org.opendaylight.controller.cluster.raft.base.messages.ApplyState; import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot; +import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout; +import org.opendaylight.controller.cluster.raft.client.messages.FindLeader; +import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload; import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload; import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper; @@ -75,44 +100,23 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.FiniteDuration; -import java.io.IOException; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.inOrder; + public class ShardTest extends AbstractActorTest { private static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext(); - private static final ShardIdentifier IDENTIFIER = ShardIdentifier.builder().memberName("member-1") - .shardName("inventory").type("config").build(); - private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger(); - private static String shardName() { - return "shard" + NEXT_SHARD_NUM.getAndIncrement(); - } + private final ShardIdentifier shardID = ShardIdentifier.builder().memberName("member-1") + .shardName("inventory").type("config" + NEXT_SHARD_NUM.getAndIncrement()).build(); private DatastoreContext dataStoreContext = DatastoreContext.newBuilder(). - shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).build(); + shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000). + shardHeartbeatIntervalInMillis(100).build(); @Before public void setUp() { - System.setProperty("shard.persistent", "false"); - InMemorySnapshotStore.clear(); InMemoryJournal.clear(); } @@ -124,40 +128,149 @@ public class ShardTest extends AbstractActorTest { } private Props newShardProps() { - return Shard.props(IDENTIFIER, Collections.emptyMap(), + return Shard.props(shardID, Collections.emptyMap(), dataStoreContext, SCHEMA_CONTEXT); } @Test - public void testOnReceiveRegisterListener() throws Exception { - new JavaTestKit(getSystem()) {{ - ActorRef subject = getSystem().actorOf(newShardProps(), "testRegisterChangeListener"); + public void testRegisterChangeListener() throws Exception { + new ShardTestKit(getSystem()) {{ + TestActorRef shard = TestActorRef.create(getSystem(), + newShardProps(), "testRegisterChangeListener"); + + waitUntilLeader(shard); - subject.tell(new UpdateSchemaContext(SchemaContextHelper.full()), getRef()); + shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender()); - subject.tell(new RegisterChangeListener(TestModel.TEST_PATH, - getRef().path(), AsyncDataBroker.DataChangeScope.BASE), getRef()); + MockDataChangeListener listener = new MockDataChangeListener(1); + ActorRef dclActor = getSystem().actorOf(DataChangeListener.props(listener), + "testRegisterChangeListener-DataChangeListener"); - EnableNotification enable = expectMsgClass(duration("3 seconds"), EnableNotification.class); - assertEquals("isEnabled", false, enable.isEnabled()); + shard.tell(new RegisterChangeListener(TestModel.TEST_PATH, + dclActor.path(), AsyncDataBroker.DataChangeScope.BASE), getRef()); RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"), RegisterChangeListenerReply.class); - assertTrue(reply.getListenerRegistrationPath().toString().matches( + String replyPath = reply.getListenerRegistrationPath().toString(); + assertTrue("Incorrect reply path: " + replyPath, replyPath.matches( "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*")); + + YangInstanceIdentifier path = TestModel.TEST_PATH; + writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + listener.waitForChangeEvents(path); + + dclActor.tell(PoisonPill.getInstance(), ActorRef.noSender()); + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); + }}; + } + + @SuppressWarnings("serial") + @Test + public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception { + // This test tests the timing window in which a change listener is registered before the + // shard becomes the leader. We verify that the listener is registered and notified of the + // existing data when the shard becomes the leader. + new ShardTestKit(getSystem()) {{ + // For this test, we want to send the RegisterChangeListener message after the shard + // has recovered from persistence and before it becomes the leader. So we subclass + // Shard to override onReceiveCommand and, when the first ElectionTimeout is received, + // we know that the shard has been initialized to a follower and has started the + // election process. The following 2 CountDownLatches are used to coordinate the + // ElectionTimeout with the sending of the RegisterChangeListener message. + final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1); + final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1); + Creator creator = new Creator() { + boolean firstElectionTimeout = true; + + @Override + public Shard create() throws Exception { + return new Shard(shardID, Collections.emptyMap(), + dataStoreContext, SCHEMA_CONTEXT) { + @Override + public void onReceiveCommand(final Object message) throws Exception { + if(message instanceof ElectionTimeout && firstElectionTimeout) { + // Got the first ElectionTimeout. We don't forward it to the + // base Shard yet until we've sent the RegisterChangeListener + // message. So we signal the onFirstElectionTimeout latch to tell + // the main thread to send the RegisterChangeListener message and + // start a thread to wait on the onChangeListenerRegistered latch, + // which the main thread signals after it has sent the message. + // After the onChangeListenerRegistered is triggered, we send the + // original ElectionTimeout message to proceed with the election. + firstElectionTimeout = false; + final ActorRef self = getSelf(); + new Thread() { + @Override + public void run() { + Uninterruptibles.awaitUninterruptibly( + onChangeListenerRegistered, 5, TimeUnit.SECONDS); + self.tell(message, self); + } + }.start(); + + onFirstElectionTimeout.countDown(); + } else { + super.onReceiveCommand(message); + } + } + }; + } + }; + + MockDataChangeListener listener = new MockDataChangeListener(1); + ActorRef dclActor = getSystem().actorOf(DataChangeListener.props(listener), + "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener"); + + TestActorRef shard = TestActorRef.create(getSystem(), + Props.create(new DelegatingShardCreator(creator)), + "testRegisterChangeListenerWhenNotLeaderInitially"); + + // Write initial data into the in-memory store. + YangInstanceIdentifier path = TestModel.TEST_PATH; + writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + + // Wait until the shard receives the first ElectionTimeout message. + assertEquals("Got first ElectionTimeout", true, + onFirstElectionTimeout.await(5, TimeUnit.SECONDS)); + + // Now send the RegisterChangeListener and wait for the reply. + shard.tell(new RegisterChangeListener(path, dclActor.path(), + AsyncDataBroker.DataChangeScope.SUBTREE), getRef()); + + RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"), + RegisterChangeListenerReply.class); + assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath()); + + // Sanity check - verify the shard is not the leader yet. + shard.tell(new FindLeader(), getRef()); + FindLeaderReply findLeadeReply = + expectMsgClass(duration("5 seconds"), FindLeaderReply.class); + assertNull("Expected the shard not to be the leader", findLeadeReply.getLeaderActor()); + + // Signal the onChangeListenerRegistered latch to tell the thread above to proceed + // with the election process. + onChangeListenerRegistered.countDown(); + + // Wait for the shard to become the leader and notify our listener with the existing + // data in the store. + listener.waitForChangeEvents(path); + + dclActor.tell(PoisonPill.getInstance(), ActorRef.noSender()); + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @Test public void testCreateTransaction(){ new ShardTestKit(getSystem()) {{ - ActorRef subject = getSystem().actorOf(newShardProps(), "testCreateTransaction"); + ActorRef shard = getSystem().actorOf(newShardProps(), "testCreateTransaction"); - waitUntilLeader(subject); + waitUntilLeader(shard); - subject.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); + shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef()); - subject.tell(new CreateTransaction("txn-1", + shard.tell(new CreateTransaction("txn-1", TransactionProxy.TransactionType.READ_ONLY.ordinal() ).toSerializable(), getRef()); CreateTransactionReply reply = expectMsgClass(duration("3 seconds"), @@ -166,18 +279,19 @@ public class ShardTest extends AbstractActorTest { String path = reply.getTransactionActorPath().toString(); assertTrue("Unexpected transaction path " + path, path.contains("akka://test/user/testCreateTransaction/shard-txn-1")); - expectNoMsg(); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @Test public void testCreateTransactionOnChain(){ new ShardTestKit(getSystem()) {{ - final ActorRef subject = getSystem().actorOf(newShardProps(), "testCreateTransactionOnChain"); + final ActorRef shard = getSystem().actorOf(newShardProps(), "testCreateTransactionOnChain"); - waitUntilLeader(subject); + waitUntilLeader(shard); - subject.tell(new CreateTransaction("txn-1", + shard.tell(new CreateTransaction("txn-1", TransactionProxy.TransactionType.READ_ONLY.ordinal() , "foobar").toSerializable(), getRef()); @@ -187,47 +301,70 @@ public class ShardTest extends AbstractActorTest { String path = reply.getTransactionActorPath().toString(); assertTrue("Unexpected transaction path " + path, path.contains("akka://test/user/testCreateTransactionOnChain/shard-txn-1")); - expectNoMsg(); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } + @SuppressWarnings("serial") @Test - public void testPeerAddressResolved(){ - new JavaTestKit(getSystem()) {{ - final ShardIdentifier identifier = - ShardIdentifier.builder().memberName("member-1") - .shardName("inventory").type("config").build(); - - Props props = Shard.props(identifier, - Collections.singletonMap(identifier, null), - dataStoreContext, SCHEMA_CONTEXT); - final ActorRef subject = getSystem().actorOf(props, "testPeerAddressResolved"); - - new Within(duration("3 seconds")) { - @Override - protected void run() { + public void testPeerAddressResolved() throws Exception { + new ShardTestKit(getSystem()) {{ + final CountDownLatch recoveryComplete = new CountDownLatch(1); + class TestShard extends Shard { + TestShard() { + super(shardID, Collections.singletonMap(shardID, null), + dataStoreContext, SCHEMA_CONTEXT); + } - subject.tell( - new PeerAddressResolved(identifier, "akka://foobar"), - getRef()); + Map getPeerAddresses() { + return getRaftActorContext().getPeerAddresses(); + } - expectNoMsg(); + @Override + protected void onRecoveryComplete() { + try { + super.onRecoveryComplete(); + } finally { + recoveryComplete.countDown(); + } } - }; + } + + final TestActorRef shard = TestActorRef.create(getSystem(), + Props.create(new DelegatingShardCreator(new Creator() { + @Override + public TestShard create() throws Exception { + return new TestShard(); + } + })), "testPeerAddressResolved"); + + //waitUntilLeader(shard); + assertEquals("Recovery complete", true, + Uninterruptibles.awaitUninterruptibly(recoveryComplete, 5, TimeUnit.SECONDS)); + + String address = "akka://foobar"; + shard.underlyingActor().onReceiveCommand(new PeerAddressResolved(shardID, address)); + + assertEquals("getPeerAddresses", address, + ((TestShard)shard.underlyingActor()).getPeerAddresses().get(shardID.toString())); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @Test - public void testApplySnapshot() throws ExecutionException, InterruptedException { - TestActorRef ref = TestActorRef.create(getSystem(), newShardProps()); + public void testApplySnapshot() throws Exception { + TestActorRef shard = TestActorRef.create(getSystem(), newShardProps(), + "testApplySnapshot"); NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(SCHEMA_CONTEXT); - writeToStore(ref, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME)); + writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME)); YangInstanceIdentifier root = YangInstanceIdentifier.builder().build(); - NormalizedNode expected = readStore(ref, root); + NormalizedNode expected = readStore(shard, root); NormalizedNodeMessages.Container encode = codec.encode(expected); @@ -235,17 +372,19 @@ public class ShardTest extends AbstractActorTest { encode.getNormalizedNode().toByteString().toByteArray(), Collections.emptyList(), 1, 2, 3, 4)); - ref.underlyingActor().onReceiveCommand(applySnapshot); + shard.underlyingActor().onReceiveCommand(applySnapshot); - NormalizedNode actual = readStore(ref, root); + NormalizedNode actual = readStore(shard, root); assertEquals(expected, actual); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); } @Test public void testApplyState() throws Exception { - TestActorRef shard = TestActorRef.create(getSystem(), newShardProps()); + TestActorRef shard = TestActorRef.create(getSystem(), newShardProps(), "testApplyState"); NormalizedNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME); @@ -259,6 +398,8 @@ public class ShardTest extends AbstractActorTest { NormalizedNode actual = readStore(shard, TestModel.TEST_PATH); assertEquals("Applied state", node, actual); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); } @SuppressWarnings("serial") @@ -279,7 +420,7 @@ public class ShardTest extends AbstractActorTest { DOMStoreReadTransaction readTx = testStore.newReadOnlyTransaction(); NormalizedNode root = readTx.read(YangInstanceIdentifier.builder().build()).get().get(); - InMemorySnapshotStore.addSnapshot(IDENTIFIER.toString(), Snapshot.create( + InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create( new NormalizedNodeToNodeCodec(SCHEMA_CONTEXT).encode( root). getNormalizedNode().toByteString().toByteArray(), @@ -287,7 +428,7 @@ public class ShardTest extends AbstractActorTest { // Set up the InMemoryJournal. - InMemoryJournal.addEntry(IDENTIFIER.toString(), 0, new ReplicatedLogImplEntry(0, 1, newPayload( + InMemoryJournal.addEntry(shardID.toString(), 0, new ReplicatedLogImplEntry(0, 1, newPayload( new WriteModification(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), SCHEMA_CONTEXT)))); @@ -301,11 +442,11 @@ public class ShardTest extends AbstractActorTest { Modification mod = new MergeModification(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i), SCHEMA_CONTEXT); - InMemoryJournal.addEntry(IDENTIFIER.toString(), i, new ReplicatedLogImplEntry(i, 1, + InMemoryJournal.addEntry(shardID.toString(), i, new ReplicatedLogImplEntry(i, 1, newPayload(mod))); } - InMemoryJournal.addEntry(IDENTIFIER.toString(), nListEntries + 1, + InMemoryJournal.addEntry(shardID.toString(), nListEntries + 1, new ApplyLogEntries(nListEntries)); // Create the actor and wait for recovery complete. @@ -315,7 +456,7 @@ public class ShardTest extends AbstractActorTest { Creator creator = new Creator() { @Override public Shard create() throws Exception { - return new Shard(IDENTIFIER, Collections.emptyMap(), + return new Shard(shardID, Collections.emptyMap(), dataStoreContext, SCHEMA_CONTEXT) { @Override protected void onRecoveryComplete() { @@ -363,9 +504,11 @@ public class ShardTest extends AbstractActorTest { shard.underlyingActor().getShardMBean().getCommitIndex()); assertEquals("Last applied", nListEntries, shard.underlyingActor().getShardMBean().getLastApplied()); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); } - private CompositeModificationPayload newPayload(Modification... mods) { + private CompositeModificationPayload newPayload(final Modification... mods) { MutableCompositeModification compMod = new MutableCompositeModification(); for(Modification mod: mods) { compMod.addModification(mod); @@ -374,15 +517,15 @@ public class ShardTest extends AbstractActorTest { return new CompositeModificationPayload(compMod.toSerializable()); } - private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(String cohortName, - InMemoryDOMDataStore dataStore, YangInstanceIdentifier path, NormalizedNode data, - MutableCompositeModification modification) { + private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(final String cohortName, + final InMemoryDOMDataStore dataStore, final YangInstanceIdentifier path, final NormalizedNode data, + final MutableCompositeModification modification) { return setupMockWriteTransaction(cohortName, dataStore, path, data, modification, null); } - private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(String cohortName, - InMemoryDOMDataStore dataStore, YangInstanceIdentifier path, NormalizedNode data, - MutableCompositeModification modification, + private DOMStoreThreePhaseCommitCohort setupMockWriteTransaction(final String cohortName, + final InMemoryDOMDataStore dataStore, final YangInstanceIdentifier path, final NormalizedNode data, + final MutableCompositeModification modification, final Function> preCommit) { DOMStoreWriteTransaction tx = dataStore.newWriteOnlyTransaction(); @@ -392,14 +535,14 @@ public class ShardTest extends AbstractActorTest { doAnswer(new Answer>() { @Override - public ListenableFuture answer(InvocationOnMock invocation) { + public ListenableFuture answer(final InvocationOnMock invocation) { return realCohort.canCommit(); } }).when(cohort).canCommit(); doAnswer(new Answer>() { @Override - public ListenableFuture answer(InvocationOnMock invocation) throws Throwable { + public ListenableFuture answer(final InvocationOnMock invocation) throws Throwable { if(preCommit != null) { return preCommit.apply(realCohort); } else { @@ -410,14 +553,14 @@ public class ShardTest extends AbstractActorTest { doAnswer(new Answer>() { @Override - public ListenableFuture answer(InvocationOnMock invocation) throws Throwable { + public ListenableFuture answer(final InvocationOnMock invocation) throws Throwable { return realCohort.commit(); } }).when(cohort).commit(); doAnswer(new Answer>() { @Override - public ListenableFuture answer(InvocationOnMock invocation) throws Throwable { + public ListenableFuture answer(final InvocationOnMock invocation) throws Throwable { return realCohort.abort(); } }).when(cohort).abort(); @@ -430,10 +573,10 @@ public class ShardTest extends AbstractActorTest { @SuppressWarnings({ "unchecked" }) @Test public void testConcurrentThreePhaseCommits() throws Throwable { - System.setProperty("shard.persistent", "true"); new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testConcurrentThreePhaseCommits"); waitUntilLeader(shard); @@ -468,7 +611,8 @@ public class ShardTest extends AbstractActorTest { // Simulate the ForwardedReadyTransaction message for the first Tx that would be sent // by the ShardTransaction. - shard.tell(new ForwardedReadyTransaction(transactionID1, cohort1, modification1), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID1, CURRENT_VERSION, + cohort1, modification1, true), getRef()); ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable( expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS)); assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath()); @@ -482,10 +626,12 @@ public class ShardTest extends AbstractActorTest { // Send the ForwardedReadyTransaction for the next 2 Tx's. - shard.tell(new ForwardedReadyTransaction(transactionID2, cohort2, modification2), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID2, CURRENT_VERSION, + cohort2, modification2, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); - shard.tell(new ForwardedReadyTransaction(transactionID3, cohort3, modification3), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID3, CURRENT_VERSION, + cohort3, modification3, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and @@ -511,14 +657,13 @@ public class ShardTest extends AbstractActorTest { class OnFutureComplete extends OnComplete { private final Class expRespType; - OnFutureComplete(Class expRespType) { + OnFutureComplete(final Class expRespType) { this.expRespType = expRespType; } @Override - public void onComplete(Throwable error, Object resp) { + public void onComplete(final Throwable error, final Object resp) { if(error != null) { - System.out.println(new java.util.Date()+": "+getClass().getSimpleName() + " failure: "+error); caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error)); } else { try { @@ -530,7 +675,7 @@ public class ShardTest extends AbstractActorTest { } } - void onSuccess(Object resp) throws Exception { + void onSuccess(final Object resp) throws Exception { } } @@ -540,7 +685,7 @@ public class ShardTest extends AbstractActorTest { } @Override - public void onComplete(Throwable error, Object resp) { + public void onComplete(final Throwable error, final Object resp) { super.onComplete(error, resp); commitLatch.countDown(); } @@ -549,13 +694,13 @@ public class ShardTest extends AbstractActorTest { class OnCanCommitFutureComplete extends OnFutureComplete { private final String transactionID; - OnCanCommitFutureComplete(String transactionID) { + OnCanCommitFutureComplete(final String transactionID) { super(CanCommitTransactionReply.SERIALIZABLE_CLASS); this.transactionID = transactionID; } @Override - void onSuccess(Object resp) throws Exception { + void onSuccess(final Object resp) throws Exception { CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(resp); assertEquals("Can commit", true, canCommitReply.getCanCommit()); @@ -606,7 +751,17 @@ public class ShardTest extends AbstractActorTest { assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent()); assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue()); + for(int i = 0; i < 20 * 5; i++) { + long lastLogIndex = shard.underlyingActor().getShardMBean().getLastLogIndex(); + if(lastLogIndex == 2) { + break; + } + Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS); + } + assertEquals("Last log index", 2, shard.underlyingActor().getShardMBean().getLastLogIndex()); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @@ -614,7 +769,8 @@ public class ShardTest extends AbstractActorTest { public void testCommitPhaseFailure() throws Throwable { new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testCommitPhaseFailure"); waitUntilLeader(shard); @@ -639,10 +795,12 @@ public class ShardTest extends AbstractActorTest { // Simulate the ForwardedReadyTransaction messages that would be sent // by the ShardTransaction. - shard.tell(new ForwardedReadyTransaction(transactionID1, cohort1, modification1), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID1, CURRENT_VERSION, + cohort1, modification1, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); - shard.tell(new ForwardedReadyTransaction(transactionID2, cohort2, modification2), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID2, CURRENT_VERSION, + cohort2, modification2, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); // Send the CanCommitTransaction message for the first Tx. @@ -669,7 +827,7 @@ public class ShardTest extends AbstractActorTest { final CountDownLatch latch = new CountDownLatch(1); canCommitFuture.onComplete(new OnComplete() { @Override - public void onComplete(Throwable t, Object resp) { + public void onComplete(final Throwable t, final Object resp) { latch.countDown(); } }, getSystem().dispatcher()); @@ -681,6 +839,8 @@ public class ShardTest extends AbstractActorTest { inOrder.verify(cohort1).preCommit(); inOrder.verify(cohort1).commit(); inOrder.verify(cohort2).canCommit(); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @@ -688,7 +848,8 @@ public class ShardTest extends AbstractActorTest { public void testPreCommitPhaseFailure() throws Throwable { new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testPreCommitPhaseFailure"); waitUntilLeader(shard); @@ -703,7 +864,8 @@ public class ShardTest extends AbstractActorTest { // Simulate the ForwardedReadyTransaction messages that would be sent // by the ShardTransaction. - shard.tell(new ForwardedReadyTransaction(transactionID, cohort, modification), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, + cohort, modification, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); // Send the CanCommitTransaction message. @@ -722,6 +884,8 @@ public class ShardTest extends AbstractActorTest { InOrder inOrder = inOrder(cohort); inOrder.verify(cohort).canCommit(); inOrder.verify(cohort).preCommit(); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @@ -729,7 +893,8 @@ public class ShardTest extends AbstractActorTest { public void testCanCommitPhaseFailure() throws Throwable { new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testCanCommitPhaseFailure"); waitUntilLeader(shard); @@ -743,22 +908,25 @@ public class ShardTest extends AbstractActorTest { // Simulate the ForwardedReadyTransaction messages that would be sent // by the ShardTransaction. - shard.tell(new ForwardedReadyTransaction(transactionID, cohort, modification), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, + cohort, modification, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); // Send the CanCommitTransaction message. shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef()); expectMsgClass(duration, akka.actor.Status.Failure.class); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @Test public void testAbortBeforeFinishCommit() throws Throwable { - System.setProperty("shard.persistent", "true"); new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testAbortBeforeFinishCommit"); waitUntilLeader(shard); @@ -779,7 +947,7 @@ public class ShardTest extends AbstractActorTest { new AbortTransaction(transactionID).toSerializable(), timeout); abortFuture.onComplete(new OnComplete() { @Override - public void onComplete(Throwable e, Object resp) { + public void onComplete(final Throwable e, final Object resp) { abortComplete.countDown(); } }, getSystem().dispatcher()); @@ -793,7 +961,8 @@ public class ShardTest extends AbstractActorTest { TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification, preCommit); - shard.tell(new ForwardedReadyTransaction(transactionID, cohort, modification), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, + cohort, modification, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); shard.tell(new CanCommitTransaction(transactionID).toSerializable(), getRef()); @@ -810,6 +979,8 @@ public class ShardTest extends AbstractActorTest { NormalizedNode node = readStore(shard, TestModel.TEST_PATH); assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @@ -819,7 +990,8 @@ public class ShardTest extends AbstractActorTest { new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testTransactionCommitTimeout"); waitUntilLeader(shard); @@ -854,10 +1026,12 @@ public class ShardTest extends AbstractActorTest { // Ready the Tx's - shard.tell(new ForwardedReadyTransaction(transactionID1, cohort1, modification1), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID1, CURRENT_VERSION, + cohort1, modification1, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); - shard.tell(new ForwardedReadyTransaction(transactionID2, cohort2, modification2), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID2, CURRENT_VERSION, + cohort2, modification2, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); // canCommit 1st Tx. We don't send the commit so it should timeout. @@ -877,6 +1051,8 @@ public class ShardTest extends AbstractActorTest { NormalizedNode node = readStore(shard, listNodePath); assertNotNull(listNodePath + " not found", node); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @@ -886,7 +1062,8 @@ public class ShardTest extends AbstractActorTest { new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testTransactionCommitQueueCapacityExceeded"); waitUntilLeader(shard); @@ -913,13 +1090,16 @@ public class ShardTest extends AbstractActorTest { // Ready the Tx's - shard.tell(new ForwardedReadyTransaction(transactionID1, cohort1, modification1), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID1, CURRENT_VERSION, + cohort1, modification1, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); - shard.tell(new ForwardedReadyTransaction(transactionID2, cohort2, modification2), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID2, CURRENT_VERSION, + cohort2, modification2, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); - shard.tell(new ForwardedReadyTransaction(transactionID3, cohort3, modification3), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID3, CURRENT_VERSION, + cohort3, modification3, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); // canCommit 1st Tx. @@ -935,6 +1115,8 @@ public class ShardTest extends AbstractActorTest { shard.tell(new CanCommitTransaction(transactionID3).toSerializable(), getRef()); expectMsgClass(duration, akka.actor.Status.Failure.class); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @@ -942,10 +1124,13 @@ public class ShardTest extends AbstractActorTest { public void testCanCommitBeforeReadyFailure() throws Throwable { new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testCanCommitBeforeReadyFailure"); shard.tell(new CanCommitTransaction("tx").toSerializable(), getRef()); expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @@ -953,7 +1138,8 @@ public class ShardTest extends AbstractActorTest { public void testAbortTransaction() throws Throwable { new ShardTestKit(getSystem()) {{ final TestActorRef shard = TestActorRef.create(getSystem(), - newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), shardName()); + newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), + "testAbortTransaction"); waitUntilLeader(shard); @@ -976,10 +1162,12 @@ public class ShardTest extends AbstractActorTest { // Simulate the ForwardedReadyTransaction messages that would be sent // by the ShardTransaction. - shard.tell(new ForwardedReadyTransaction(transactionID1, cohort1, modification1), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID1, CURRENT_VERSION, + cohort1, modification1, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); - shard.tell(new ForwardedReadyTransaction(transactionID2, cohort2, modification2), getRef()); + shard.tell(new ForwardedReadyTransaction(transactionID2, CURRENT_VERSION, + cohort2, modification2, true), getRef()); expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS); // Send the CanCommitTransaction message for the first Tx. @@ -1006,7 +1194,7 @@ public class ShardTest extends AbstractActorTest { final CountDownLatch latch = new CountDownLatch(1); canCommitFuture.onComplete(new OnComplete() { @Override - public void onComplete(Throwable t, Object resp) { + public void onComplete(final Throwable t, final Object resp) { latch.countDown(); } }, getSystem().dispatcher()); @@ -1016,21 +1204,36 @@ public class ShardTest extends AbstractActorTest { InOrder inOrder = inOrder(cohort1, cohort2); inOrder.verify(cohort1).canCommit(); inOrder.verify(cohort2).canCommit(); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @Test public void testCreateSnapshot() throws IOException, InterruptedException { + testCreateSnapshot(true, "testCreateSnapshot"); + } + + @Test + public void testCreateSnapshotWithNonPersistentData() throws IOException, InterruptedException { + testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData"); + } + + @SuppressWarnings("serial") + public void testCreateSnapshot(final boolean persistent, final String shardActorName) throws IOException, InterruptedException { + final DatastoreContext dataStoreContext = DatastoreContext.newBuilder(). + shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(persistent).build(); + new ShardTestKit(getSystem()) {{ final AtomicReference latch = new AtomicReference<>(new CountDownLatch(1)); Creator creator = new Creator() { @Override public Shard create() throws Exception { - return new Shard(IDENTIFIER, Collections.emptyMap(), + return new Shard(shardID, Collections.emptyMap(), dataStoreContext, SCHEMA_CONTEXT) { @Override - public void saveSnapshot(Object snapshot) { - super.saveSnapshot(snapshot); + protected void commitSnapshot(final long sequenceNumber) { + super.commitSnapshot(sequenceNumber); latch.get().countDown(); } }; @@ -1038,7 +1241,7 @@ public class ShardTest extends AbstractActorTest { }; TestActorRef shard = TestActorRef.create(getSystem(), - Props.create(new DelegatingShardCreator(creator)), "testCreateSnapshot"); + Props.create(new DelegatingShardCreator(creator)), shardActorName); waitUntilLeader(shard); @@ -1050,6 +1253,8 @@ public class ShardTest extends AbstractActorTest { shard.tell(new CaptureSnapshot(-1,-1,-1,-1), getRef()); assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS)); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); }}; } @@ -1070,7 +1275,7 @@ public class ShardTest extends AbstractActorTest { commitTransaction(putTransaction); - NormalizedNode expected = readStore(store); + NormalizedNode expected = readStore(store); DOMStoreWriteTransaction writeTransaction = store.newWriteOnlyTransaction(); @@ -1079,13 +1284,48 @@ public class ShardTest extends AbstractActorTest { commitTransaction(writeTransaction); - NormalizedNode actual = readStore(store); + NormalizedNode actual = readStore(store); assertEquals(expected, actual); } - private NormalizedNode readStore(InMemoryDOMDataStore store) throws ReadFailedException { + @Test + public void testRecoveryApplicable(){ + + final DatastoreContext persistentContext = DatastoreContext.newBuilder(). + shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build(); + + final Props persistentProps = Shard.props(shardID, Collections.emptyMap(), + persistentContext, SCHEMA_CONTEXT); + + final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder(). + shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build(); + + final Props nonPersistentProps = Shard.props(shardID, Collections.emptyMap(), + nonPersistentContext, SCHEMA_CONTEXT); + + new ShardTestKit(getSystem()) {{ + TestActorRef shard1 = TestActorRef.create(getSystem(), + persistentProps, "testPersistence1"); + + assertTrue("Recovery Applicable", shard1.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable()); + + shard1.tell(PoisonPill.getInstance(), ActorRef.noSender()); + + TestActorRef shard2 = TestActorRef.create(getSystem(), + nonPersistentProps, "testPersistence2"); + + assertFalse("Recovery Not Applicable", shard2.underlyingActor().getDataPersistenceProvider().isRecoveryApplicable()); + + shard2.tell(PoisonPill.getInstance(), ActorRef.noSender()); + + }}; + + } + + + private NormalizedNode readStore(final InMemoryDOMDataStore store) throws ReadFailedException { DOMStoreReadTransaction transaction = store.newReadOnlyTransaction(); CheckedFuture>, ReadFailedException> read = transaction.read(YangInstanceIdentifier.builder().build()); @@ -1099,7 +1339,7 @@ public class ShardTest extends AbstractActorTest { return normalizedNode; } - private void commitTransaction(DOMStoreWriteTransaction transaction) { + private void commitTransaction(final DOMStoreWriteTransaction transaction) { DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready(); ListenableFuture future = commitCohort.preCommit(); @@ -1115,13 +1355,13 @@ public class ShardTest extends AbstractActorTest { return new AsyncDataChangeListener>() { @Override public void onDataChanged( - AsyncDataChangeEvent> change) { + final AsyncDataChangeEvent> change) { } }; } - private NormalizedNode readStore(TestActorRef shard, YangInstanceIdentifier id) + static NormalizedNode readStore(final TestActorRef shard, final YangInstanceIdentifier id) throws ExecutionException, InterruptedException { DOMStoreReadTransaction transaction = shard.underlyingActor().getDataStore().newReadOnlyTransaction(); @@ -1136,7 +1376,7 @@ public class ShardTest extends AbstractActorTest { return node; } - private void writeToStore(TestActorRef shard, YangInstanceIdentifier id, NormalizedNode node) + private void writeToStore(final TestActorRef shard, final YangInstanceIdentifier id, final NormalizedNode node) throws ExecutionException, InterruptedException { DOMStoreWriteTransaction transaction = shard.underlyingActor().getDataStore().newWriteOnlyTransaction(); @@ -1147,10 +1387,11 @@ public class ShardTest extends AbstractActorTest { commitCohort.commit().get(); } + @SuppressWarnings("serial") private static final class DelegatingShardCreator implements Creator { private final Creator delegate; - DelegatingShardCreator(Creator delegate) { + DelegatingShardCreator(final Creator delegate) { this.delegate = delegate; } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTestKit.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTestKit.java index 9a0e8f9e18..fa15db6949 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTestKit.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTestKit.java @@ -7,19 +7,22 @@ */ package org.opendaylight.controller.cluster.datastore; -import java.util.concurrent.TimeUnit; +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.pattern.Patterns; +import akka.testkit.JavaTestKit; +import akka.util.Timeout; +import com.google.common.util.concurrent.Uninterruptibles; import org.junit.Assert; import org.opendaylight.controller.cluster.raft.client.messages.FindLeader; import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply; -import com.google.common.util.concurrent.Uninterruptibles; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; -import akka.actor.ActorRef; -import akka.actor.ActorSystem; -import akka.pattern.Patterns; -import akka.testkit.JavaTestKit; -import akka.util.Timeout; +import scala.concurrent.duration.FiniteDuration; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; class ShardTestKit extends JavaTestKit { @@ -27,7 +30,7 @@ class ShardTestKit extends JavaTestKit { super(actorSystem); } - protected void waitForLogMessage(final Class logLevel, ActorRef subject, String logMessage){ + protected void waitForLogMessage(final Class logLevel, ActorRef subject, String logMessage){ // Wait for a specific log message to show up final boolean result = new JavaTestKit.EventFilter(logLevel @@ -45,20 +48,25 @@ class ShardTestKit extends JavaTestKit { } protected void waitUntilLeader(ActorRef shard) { + FiniteDuration duration = Duration.create(100, TimeUnit.MILLISECONDS); for(int i = 0; i < 20 * 5; i++) { - Future future = Patterns.ask(shard, new FindLeader(), new Timeout(5, TimeUnit.SECONDS)); + Future future = Patterns.ask(shard, new FindLeader(), new Timeout(duration)); try { - FindLeaderReply resp = (FindLeaderReply)Await.result(future, Duration.create(5, TimeUnit.SECONDS)); + FindLeaderReply resp = (FindLeaderReply)Await.result(future, duration); if(resp.getLeaderActor() != null) { return; } - } catch (Exception e) { + } catch(TimeoutException e) { + } catch(Exception e) { + System.err.println("FindLeader threw ex"); e.printStackTrace(); } + Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS); } Assert.fail("Leader not found for shard " + shard.path()); } + } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionFailureTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionFailureTest.java index 17731de5cd..5781c19b25 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionFailureTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionFailureTest.java @@ -12,13 +12,17 @@ package org.opendaylight.controller.cluster.datastore; import akka.actor.ActorRef; import akka.actor.Props; +import akka.pattern.AskTimeoutException; import akka.testkit.TestActorRef; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import java.util.Collections; +import java.util.concurrent.TimeUnit; import org.junit.BeforeClass; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier; import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats; +import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction; import org.opendaylight.controller.cluster.datastore.node.utils.serialization.NormalizedNodeSerializer; import org.opendaylight.controller.md.cluster.datastore.model.TestModel; import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; @@ -31,8 +35,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; -import java.util.Collections; -import java.util.concurrent.TimeUnit; /** * Covers negative test cases @@ -64,7 +66,7 @@ public class ShardTransactionFailureTest extends AbstractActorTest { } private ActorRef createShard(){ - return getSystem().actorOf(Shard.props(SHARD_IDENTIFIER, Collections.EMPTY_MAP, datastoreContext, + return getSystem().actorOf(Shard.props(SHARD_IDENTIFIER, Collections.emptyMap(), datastoreContext, TestModel.createTestContext())); } @@ -74,7 +76,8 @@ public class ShardTransactionFailureTest extends AbstractActorTest { final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); final TestActorRef subject = TestActorRef .create(getSystem(), props, @@ -103,7 +106,8 @@ public class ShardTransactionFailureTest extends AbstractActorTest { final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); final TestActorRef subject = TestActorRef .create(getSystem(), props, @@ -132,7 +136,8 @@ public class ShardTransactionFailureTest extends AbstractActorTest { final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); final TestActorRef subject = TestActorRef .create(getSystem(), props, @@ -155,13 +160,14 @@ public class ShardTransactionFailureTest extends AbstractActorTest { Await.result(future, Duration.create(3, TimeUnit.SECONDS)); } - @Test(expected = IllegalStateException.class) + @Test(expected = AskTimeoutException.class) public void testNegativeWriteWithTransactionReady() throws Exception { final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newWriteOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); final TestActorRef subject = TestActorRef .create(getSystem(), props, @@ -187,13 +193,14 @@ public class ShardTransactionFailureTest extends AbstractActorTest { Await.result(future, Duration.create(3, TimeUnit.SECONDS)); } - @Test(expected = IllegalStateException.class) + @Test(expected = AskTimeoutException.class) public void testNegativeReadWriteWithTransactionReady() throws Exception { final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); final TestActorRef subject = TestActorRef .create(getSystem(), props, @@ -224,13 +231,14 @@ public class ShardTransactionFailureTest extends AbstractActorTest { .serialize(Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).build()); } - @Test(expected = IllegalStateException.class) + @Test(expected = AskTimeoutException.class) public void testNegativeMergeTransactionReady() throws Exception { final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); final TestActorRef subject = TestActorRef .create(getSystem(), props, "testNegativeMergeTransactionReady"); @@ -256,13 +264,14 @@ public class ShardTransactionFailureTest extends AbstractActorTest { } - @Test(expected = IllegalStateException.class) + @Test(expected = AskTimeoutException.class) public void testNegativeDeleteDataWhenTransactionReady() throws Exception { final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); final TestActorRef subject = TestActorRef .create(getSystem(), props, diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionHeliumBackwardsCompatibilityTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionHeliumBackwardsCompatibilityTest.java new file mode 100644 index 0000000000..af07aeebcf --- /dev/null +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionHeliumBackwardsCompatibilityTest.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.datastore; + +import java.util.Collections; +import org.junit.Assert; +import org.junit.Test; +import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier; +import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply; +import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply; +import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply; +import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransactionReply; +import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction; +import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply; +import org.opendaylight.controller.cluster.datastore.messages.WriteData; +import org.opendaylight.controller.cluster.datastore.messages.WriteDataReply; +import org.opendaylight.controller.md.cluster.datastore.model.TestModel; +import org.opendaylight.controller.protobuff.messages.cohort3pc.ThreePhaseCommitCohortMessages; +import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; +import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; +import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import scala.concurrent.duration.FiniteDuration; +import akka.actor.ActorRef; +import akka.actor.ActorSelection; +import akka.actor.PoisonPill; +import akka.actor.Props; +import akka.dispatch.Dispatchers; +import akka.testkit.TestActorRef; + +/** + * Tests backwards compatibility support from Helium-1 to Helium. + * + * In Helium-1, the 3-phase commit support was moved from the ThreePhaseCommitCohort actor to the + * Shard. As a consequence, a new transactionId field was added to the CanCommitTransaction, + * CommitTransaction and AbortTransaction messages. With a base Helium version node, these messages + * would be sans transactionId so this test verifies the Shard handles that properly. + * + * @author Thomas Pantelis + */ +public class ShardTransactionHeliumBackwardsCompatibilityTest extends AbstractActorTest { + + @Test + public void testTransactionCommit() throws Exception { + new ShardTestKit(getSystem()) {{ + SchemaContext schemaContext = TestModel.createTestContext(); + Props shardProps = Shard.props(ShardIdentifier.builder().memberName("member-1"). + shardName("inventory").type("config").build(), + Collections.emptyMap(), + DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).build(), + schemaContext).withDispatcher(Dispatchers.DefaultDispatcherId()); + + final TestActorRef shard = TestActorRef.create(getSystem(), shardProps, + "testTransactionCommit"); + + waitUntilLeader(shard); + + // Send CreateTransaction message with no messages version + + String transactionID = "txn-1"; + shard.tell(ShardTransactionMessages.CreateTransaction.newBuilder() + .setTransactionId(transactionID) + .setTransactionType(TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) + .setTransactionChainId("").build(), getRef()); + + final FiniteDuration duration = duration("5 seconds"); + + CreateTransactionReply reply = expectMsgClass(duration, CreateTransactionReply.class); + + ActorSelection txActor = getSystem().actorSelection(reply.getTransactionActorPath()); + + // Write data to the Tx + + txActor.tell(new WriteData(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME), schemaContext), getRef()); + + expectMsgClass(duration, WriteDataReply.class); + + // Ready the Tx + + txActor.tell(new ReadyTransaction().toSerializable(), getRef()); + + ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(expectMsgClass( + duration, ReadyTransactionReply.SERIALIZABLE_CLASS)); + + ActorSelection cohortActor = getSystem().actorSelection(readyReply.getCohortPath()); + + // Send the CanCommitTransaction message with no transactionId. + + cohortActor.tell(ThreePhaseCommitCohortMessages.CanCommitTransaction.newBuilder().build(), + getRef()); + + expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS); + + // Send the PreCommitTransaction message with no transactionId. + + cohortActor.tell(ThreePhaseCommitCohortMessages.PreCommitTransaction.newBuilder().build(), + getRef()); + + expectMsgClass(duration, PreCommitTransactionReply.SERIALIZABLE_CLASS); + + // Send the CommitTransaction message with no transactionId. + + cohortActor.tell(ThreePhaseCommitCohortMessages.CommitTransaction.newBuilder().build(), + getRef()); + + expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS); + + NormalizedNode node = ShardTest.readStore(shard, TestModel.TEST_PATH); + Assert.assertNotNull("Data not found in store", node); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); + }}; + } + + @Test + public void testTransactionAbort() throws Exception { + new ShardTestKit(getSystem()) {{ + SchemaContext schemaContext = TestModel.createTestContext(); + Props shardProps = Shard.props(ShardIdentifier.builder().memberName("member-1"). + shardName("inventory").type("config").build(), + Collections.emptyMap(), + DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).build(), + schemaContext).withDispatcher(Dispatchers.DefaultDispatcherId()); + + final TestActorRef shard = TestActorRef.create(getSystem(), shardProps, + "testTransactionAbort"); + + waitUntilLeader(shard); + + // Send CreateTransaction message with no messages version + + String transactionID = "txn-1"; + shard.tell(ShardTransactionMessages.CreateTransaction.newBuilder() + .setTransactionId(transactionID) + .setTransactionType(TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) + .setTransactionChainId("").build(), getRef()); + + final FiniteDuration duration = duration("5 seconds"); + + CreateTransactionReply reply = expectMsgClass(duration, CreateTransactionReply.class); + + ActorSelection txActor = getSystem().actorSelection(reply.getTransactionActorPath()); + + // Write data to the Tx + + txActor.tell(new WriteData(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME), schemaContext), getRef()); + + expectMsgClass(duration, WriteDataReply.class); + + // Ready the Tx + + txActor.tell(new ReadyTransaction().toSerializable(), getRef()); + + ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(expectMsgClass( + duration, ReadyTransactionReply.SERIALIZABLE_CLASS)); + + ActorSelection cohortActor = getSystem().actorSelection(readyReply.getCohortPath()); + + // Send the CanCommitTransaction message with no transactionId. + + cohortActor.tell(ThreePhaseCommitCohortMessages.CanCommitTransaction.newBuilder().build(), + getRef()); + + expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS); + + // Send the AbortTransaction message with no transactionId. + + cohortActor.tell(ThreePhaseCommitCohortMessages.AbortTransaction.newBuilder().build(), + getRef()); + + expectMsgClass(duration, AbortTransactionReply.SERIALIZABLE_CLASS); + + shard.tell(PoisonPill.getInstance(), ActorRef.noSender()); + }}; + } +} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java index 8ce8f4d4b5..4ccc9430ac 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java @@ -1,5 +1,9 @@ package org.opendaylight.controller.cluster.datastore; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.Terminated; @@ -7,13 +11,17 @@ import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import java.util.Collections; +import java.util.concurrent.TimeUnit; import org.junit.BeforeClass; import org.junit.Test; +import org.opendaylight.controller.cluster.datastore.ShardWriteTransaction.GetCompositeModificationReply; import org.opendaylight.controller.cluster.datastore.exceptions.UnknownMessageException; import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier; import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats; import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction; import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionReply; +import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction; import org.opendaylight.controller.cluster.datastore.messages.DataExists; import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply; import org.opendaylight.controller.cluster.datastore.messages.DeleteData; @@ -33,14 +41,11 @@ import org.opendaylight.controller.cluster.datastore.modification.Modification; import org.opendaylight.controller.cluster.datastore.modification.WriteModification; import org.opendaylight.controller.md.cluster.datastore.model.TestModel; import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore; +import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import scala.concurrent.duration.Duration; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; public class ShardTransactionTest extends AbstractActorTest { private static ListeningExecutorService storeExecutor = @@ -66,48 +71,44 @@ public class ShardTransactionTest extends AbstractActorTest { private ActorRef createShard(){ return getSystem().actorOf(Shard.props(SHARD_IDENTIFIER, - Collections.EMPTY_MAP, datastoreContext, TestModel.createTestContext())); + Collections.emptyMap(), datastoreContext, TestModel.createTestContext())); } @Test public void testOnReceiveReadData() throws Exception { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); - final Props props = ShardTransaction.props(store.newReadOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = getSystem().actorOf(props, "testReadData"); - - new Within(duration("1 seconds")) { - @Override - protected void run() { - - subject.tell( - new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), - getRef()); - - final String out = new ExpectMsg(duration("1 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) { - if (ReadDataReply.fromSerializable(testSchemaContext,YangInstanceIdentifier.builder().build(), in) - .getNormalizedNode()!= null) { - return "match"; - } - return null; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message - - assertEquals("match", out); - - expectNoMsg(); - } - - - }; + Props props = ShardTransaction.props(store.newReadOnlyTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + + testOnReceiveReadData(getSystem().actorOf(props, "testReadDataRO")); + + props = ShardTransaction.props(store.newReadWriteTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + + testOnReceiveReadData(getSystem().actorOf(props, "testReadDataRW")); + } + + private void testOnReceiveReadData(final ActorRef transaction) { + //serialized read + transaction.tell(new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), + getRef()); + + ShardTransactionMessages.ReadDataReply replySerialized = + expectMsgClass(duration("5 seconds"), ReadDataReply.SERIALIZABLE_CLASS); + + assertNotNull(ReadDataReply.fromSerializable( + testSchemaContext,YangInstanceIdentifier.builder().build(), replySerialized) + .getNormalizedNode()); + + // unserialized read + transaction.tell(new ReadData(YangInstanceIdentifier.builder().build()),getRef()); + + ReadDataReply reply = expectMsgClass(duration("5 seconds"), ReadDataReply.class); + + assertNotNull(reply.getNormalizedNode()); }}; } @@ -115,42 +116,37 @@ public class ShardTransactionTest extends AbstractActorTest { public void testOnReceiveReadDataWhenDataNotFound() throws Exception { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); - final Props props = ShardTransaction.props( store.newReadOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = getSystem().actorOf(props, "testReadDataWhenDataNotFound"); - - new Within(duration("1 seconds")) { - @Override - protected void run() { - - subject.tell( - new ReadData(TestModel.TEST_PATH).toSerializable(), - getRef()); - - final String out = new ExpectMsg(duration("1 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) { - if (ReadDataReply.fromSerializable(testSchemaContext,TestModel.TEST_PATH, in) - .getNormalizedNode() - == null) { - return "match"; - } - return null; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message - - assertEquals("match", out); - - expectNoMsg(); - } - - - }; + Props props = ShardTransaction.props( store.newReadOnlyTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + + testOnReceiveReadDataWhenDataNotFound(getSystem().actorOf( + props, "testReadDataWhenDataNotFoundRO")); + + props = ShardTransaction.props( store.newReadWriteTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + + testOnReceiveReadDataWhenDataNotFound(getSystem().actorOf( + props, "testReadDataWhenDataNotFoundRW")); + } + + private void testOnReceiveReadDataWhenDataNotFound(final ActorRef transaction) { + // serialized read + transaction.tell(new ReadData(TestModel.TEST_PATH).toSerializable(), getRef()); + + ShardTransactionMessages.ReadDataReply replySerialized = + expectMsgClass(duration("5 seconds"), ReadDataReply.SERIALIZABLE_CLASS); + + assertTrue(ReadDataReply.fromSerializable( + testSchemaContext, TestModel.TEST_PATH, replySerialized).getNormalizedNode() == null); + + // unserialized read + transaction.tell(new ReadData(TestModel.TEST_PATH),getRef()); + + ReadDataReply reply = expectMsgClass(duration("5 seconds"), ReadDataReply.class); + + assertTrue(reply.getNormalizedNode() == null); }}; } @@ -158,41 +154,34 @@ public class ShardTransactionTest extends AbstractActorTest { public void testOnReceiveDataExistsPositive() throws Exception { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); - final Props props = ShardTransaction.props(store.newReadOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = getSystem().actorOf(props, "testDataExistsPositive"); - - new Within(duration("1 seconds")) { - @Override - protected void run() { - - subject.tell( - new DataExists(YangInstanceIdentifier.builder().build()).toSerializable(), - getRef()); - - final String out = new ExpectMsg(duration("1 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) { - if (DataExistsReply.fromSerializable(in) - .exists()) { - return "match"; - } - return null; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message - - assertEquals("match", out); - - expectNoMsg(); - } - - - }; + Props props = ShardTransaction.props(store.newReadOnlyTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + + testOnReceiveDataExistsPositive(getSystem().actorOf(props, "testDataExistsPositiveRO")); + + props = ShardTransaction.props(store.newReadWriteTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + + testOnReceiveDataExistsPositive(getSystem().actorOf(props, "testDataExistsPositiveRW")); + } + + private void testOnReceiveDataExistsPositive(final ActorRef transaction) { + transaction.tell(new DataExists(YangInstanceIdentifier.builder().build()).toSerializable(), + getRef()); + + ShardTransactionMessages.DataExistsReply replySerialized = + expectMsgClass(duration("5 seconds"), ShardTransactionMessages.DataExistsReply.class); + + assertTrue(DataExistsReply.fromSerializable(replySerialized).exists()); + + // unserialized read + transaction.tell(new DataExists(YangInstanceIdentifier.builder().build()),getRef()); + + DataExistsReply reply = expectMsgClass(duration("5 seconds"), DataExistsReply.class); + + assertTrue(reply.exists()); }}; } @@ -200,76 +189,46 @@ public class ShardTransactionTest extends AbstractActorTest { public void testOnReceiveDataExistsNegative() throws Exception { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); - final Props props = ShardTransaction.props(store.newReadOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = getSystem().actorOf(props, "testDataExistsNegative"); - - new Within(duration("1 seconds")) { - @Override - protected void run() { - - subject.tell( - new DataExists(TestModel.TEST_PATH).toSerializable(), - getRef()); - - final String out = new ExpectMsg(duration("1 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in.getClass().equals(DataExistsReply.SERIALIZABLE_CLASS)) { - if (!DataExistsReply.fromSerializable(in) - .exists()) { - return "match"; - } - return null; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message - - assertEquals("match", out); - - expectNoMsg(); - } - - - }; + Props props = ShardTransaction.props(store.newReadOnlyTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + + testOnReceiveDataExistsNegative(getSystem().actorOf(props, "testDataExistsNegativeRO")); + + props = ShardTransaction.props(store.newReadWriteTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + + testOnReceiveDataExistsNegative(getSystem().actorOf(props, "testDataExistsNegativeRW")); + } + + private void testOnReceiveDataExistsNegative(final ActorRef transaction) { + transaction.tell(new DataExists(TestModel.TEST_PATH).toSerializable(), getRef()); + + ShardTransactionMessages.DataExistsReply replySerialized = + expectMsgClass(duration("5 seconds"), ShardTransactionMessages.DataExistsReply.class); + + assertFalse(DataExistsReply.fromSerializable(replySerialized).exists()); + + // unserialized read + transaction.tell(new DataExists(TestModel.TEST_PATH),getRef()); + + DataExistsReply reply = expectMsgClass(duration("5 seconds"), DataExistsReply.class); + + assertFalse(reply.exists()); }}; } private void assertModification(final ActorRef subject, final Class modificationType) { new JavaTestKit(getSystem()) {{ - new Within(duration("3 seconds")) { - @Override - protected void run() { - subject - .tell(new ShardWriteTransaction.GetCompositedModification(), - getRef()); - - final CompositeModification compositeModification = - new ExpectMsg(duration("3 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected CompositeModification match(Object in) { - if (in instanceof ShardWriteTransaction.GetCompositeModificationReply) { - return ((ShardWriteTransaction.GetCompositeModificationReply) in) - .getModification(); - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message - - assertTrue( - compositeModification.getModifications().size() == 1); - assertEquals(modificationType, - compositeModification.getModifications().get(0) - .getClass()); - - } - }; + subject.tell(new ShardWriteTransaction.GetCompositedModification(), getRef()); + + CompositeModification compositeModification = expectMsgClass(duration("3 seconds"), + GetCompositeModificationReply.class).getModification(); + + assertTrue(compositeModification.getModifications().size() == 1); + assertEquals(modificationType, compositeModification.getModifications().get(0).getClass()); }}; } @@ -278,38 +237,25 @@ public class ShardTransactionTest extends AbstractActorTest { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newWriteOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = - getSystem().actorOf(props, "testWriteData"); - - new Within(duration("1 seconds")) { - @Override - protected void run() { - - subject.tell(new WriteData(TestModel.TEST_PATH, - ImmutableNodes.containerNode(TestModel.TEST_QNAME), TestModel.createTestContext()).toSerializable(), - getRef()); - - final String out = new ExpectMsg(duration("1 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in.getClass().equals(WriteDataReply.SERIALIZABLE_CLASS)) { - return "match"; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message - - assertEquals("match", out); - - assertModification(subject, WriteModification.class); - expectNoMsg(); - } - - - }; + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + final ActorRef transaction = getSystem().actorOf(props, "testWriteData"); + + transaction.tell(new WriteData(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME), TestModel.createTestContext()).toSerializable(), + getRef()); + + expectMsgClass(duration("5 seconds"), ShardTransactionMessages.WriteDataReply.class); + + assertModification(transaction, WriteModification.class); + + //unserialized write + transaction.tell(new WriteData(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME), + TestModel.createTestContext()), + getRef()); + + expectMsgClass(duration("5 seconds"), WriteDataReply.class); }}; } @@ -318,39 +264,24 @@ public class ShardTransactionTest extends AbstractActorTest { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = - getSystem().actorOf(props, "testMergeData"); - - new Within(duration("1 seconds")) { - @Override - protected void run() { - - subject.tell(new MergeData(TestModel.TEST_PATH, - ImmutableNodes.containerNode(TestModel.TEST_QNAME), testSchemaContext).toSerializable(), - getRef()); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + final ActorRef transaction = getSystem().actorOf(props, "testMergeData"); - final String out = new ExpectMsg(duration("500 milliseconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in.getClass().equals(MergeDataReply.SERIALIZABLE_CLASS)) { - return "match"; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message + transaction.tell(new MergeData(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME), testSchemaContext).toSerializable(), + getRef()); - assertEquals("match", out); + expectMsgClass(duration("5 seconds"), ShardTransactionMessages.MergeDataReply.class); - assertModification(subject, MergeModification.class); + assertModification(transaction, MergeModification.class); - expectNoMsg(); - } + //unserialized merge + transaction.tell(new MergeData(TestModel.TEST_PATH, + ImmutableNodes.containerNode(TestModel.TEST_QNAME), testSchemaContext), + getRef()); - - }; + expectMsgClass(duration("5 seconds"), MergeDataReply.class); }}; } @@ -359,36 +290,20 @@ public class ShardTransactionTest extends AbstractActorTest { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); final Props props = ShardTransaction.props( store.newWriteOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = - getSystem().actorOf(props, "testDeleteData"); - - new Within(duration("1 seconds")) { - @Override - protected void run() { + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + final ActorRef transaction = getSystem().actorOf(props, "testDeleteData"); - subject.tell(new DeleteData(TestModel.TEST_PATH).toSerializable(), getRef()); + transaction.tell(new DeleteData(TestModel.TEST_PATH).toSerializable(), getRef()); - final String out = new ExpectMsg(duration("1 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in.getClass().equals(DeleteDataReply.SERIALIZABLE_CLASS)) { - return "match"; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message + expectMsgClass(duration("5 seconds"), ShardTransactionMessages.DeleteDataReply.class); - assertEquals("match", out); + assertModification(transaction, DeleteModification.class); - assertModification(subject, DeleteModification.class); - expectNoMsg(); - } + //unserialized merge + transaction.tell(new DeleteData(TestModel.TEST_PATH), getRef()); - - }; + expectMsgClass(duration("5 seconds"), DeleteDataReply.class); }}; } @@ -398,87 +313,56 @@ public class ShardTransactionTest extends AbstractActorTest { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); final Props props = ShardTransaction.props( store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = - getSystem().actorOf(props, "testReadyTransaction"); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + final ActorRef transaction = getSystem().actorOf(props, "testReadyTransaction"); - new Within(duration("1 seconds")) { - @Override - protected void run() { + watch(transaction); - subject.tell(new ReadyTransaction().toSerializable(), getRef()); + transaction.tell(new ReadyTransaction().toSerializable(), getRef()); - final String out = new ExpectMsg(duration("1 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)) { - return "match"; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message + expectMsgAnyClassOf(duration("5 seconds"), ReadyTransactionReply.SERIALIZABLE_CLASS, + Terminated.class); + expectMsgAnyClassOf(duration("5 seconds"), ReadyTransactionReply.SERIALIZABLE_CLASS, + Terminated.class); + }}; - assertEquals("match", out); + // test + new JavaTestKit(getSystem()) {{ + final ActorRef shard = createShard(); + final Props props = ShardTransaction.props( store.newReadWriteTransaction(), shard, + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + final ActorRef transaction = getSystem().actorOf(props, "testReadyTransaction2"); - expectNoMsg(); - } + watch(transaction); + transaction.tell(new ReadyTransaction(), getRef()); - }; + expectMsgAnyClassOf(duration("5 seconds"), ReadyTransactionReply.class, + Terminated.class); + expectMsgAnyClassOf(duration("5 seconds"), ReadyTransactionReply.class, + Terminated.class); }}; } + @SuppressWarnings("unchecked") @Test public void testOnReceiveCloseTransaction() throws Exception { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = - getSystem().actorOf(props, "testCloseTransaction"); - - watch(subject); - - new Within(duration("6 seconds")) { - @Override - protected void run() { - - subject.tell(new CloseTransaction().toSerializable(), getRef()); - - final String out = new ExpectMsg(duration("3 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - System.out.println("!!!IN match 1: "+(in!=null?in.getClass():"NULL")); - if (in.getClass().equals(CloseTransactionReply.SERIALIZABLE_CLASS)) { - return "match"; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message - - assertEquals("match", out); - - final String termination = new ExpectMsg(duration("3 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - System.out.println("!!!IN match 2: "+(in!=null?in.getClass():"NULL")); - if (in instanceof Terminated) { - return "match"; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message - - assertEquals("match", termination); - } - }; + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + final ActorRef transaction = getSystem().actorOf(props, "testCloseTransaction"); + + watch(transaction); + + transaction.tell(new CloseTransaction().toSerializable(), getRef()); + + expectMsgClass(duration("3 seconds"), CloseTransactionReply.SERIALIZABLE_CLASS); + expectTerminated(duration("3 seconds"), transaction); }}; } @@ -486,10 +370,11 @@ public class ShardTransactionTest extends AbstractActorTest { public void testNegativePerformingWriteOperationOnReadTransaction() throws Exception { final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadOnlyTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final TestActorRef subject = TestActorRef.apply(props,getSystem()); + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + final TestActorRef transaction = TestActorRef.apply(props,getSystem()); - subject.receive(new DeleteData(TestModel.TEST_PATH).toSerializable(), ActorRef.noSender()); + transaction.receive(new DeleteData(TestModel.TEST_PATH).toSerializable(), ActorRef.noSender()); } @Test @@ -501,27 +386,14 @@ public class ShardTransactionTest extends AbstractActorTest { new JavaTestKit(getSystem()) {{ final ActorRef shard = createShard(); final Props props = ShardTransaction.props(store.newReadWriteTransaction(), shard, - testSchemaContext, datastoreContext, shardStats, "txn"); - final ActorRef subject = + testSchemaContext, datastoreContext, shardStats, "txn", + CreateTransaction.CURRENT_VERSION); + final ActorRef transaction = getSystem().actorOf(props, "testShardTransactionInactivity"); - watch(subject); - - // The shard Tx actor should receive a ReceiveTimeout message and self-destruct. - - final String termination = new ExpectMsg(duration("3 seconds"), "match hint") { - // do not put code outside this method, will run afterwards - @Override - protected String match(Object in) { - if (in instanceof Terminated) { - return "match"; - } else { - throw noMatch(); - } - } - }.get(); // this extracts the received message + watch(transaction); - assertEquals("match", termination); + expectMsgClass(duration("3 seconds"), Terminated.class); }}; } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxyTest.java index 4cca1bf9ad..ce0547c388 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxyTest.java @@ -10,6 +10,11 @@ package org.opendaylight.controller.cluster.datastore; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -20,12 +25,6 @@ import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransaction; import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - public class TransactionChainProxyTest { ActorContext actorContext = mock(ActorContext.class); SchemaContext schemaContext = mock(SchemaContext.class); @@ -68,4 +67,12 @@ public class TransactionChainProxyTest { verify(context, times(1)).broadcast(anyObject()); } + + @Test + public void testTransactionChainsHaveUniqueId(){ + TransactionChainProxy one = new TransactionChainProxy(mock(ActorContext.class)); + TransactionChainProxy two = new TransactionChainProxy(mock(ActorContext.class)); + + Assert.assertNotEquals(one.getTransactionChainId(), two.getTransactionChainId()); + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java index 592337f93f..cdf085e2ff 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java @@ -1,13 +1,19 @@ package org.opendaylight.controller.cluster.datastore; -import com.google.common.util.concurrent.CheckedFuture; - import akka.actor.ActorRef; import akka.actor.ActorSelection; +import akka.actor.ActorSystem; import akka.actor.Props; import akka.dispatch.Futures; +import akka.testkit.JavaTestKit; import com.google.common.base.Optional; +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.CheckedFuture; +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; @@ -44,10 +50,9 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; - +import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -56,7 +61,6 @@ import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.argThat; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.isA; import static org.mockito.Mockito.times; @@ -66,7 +70,7 @@ import static org.opendaylight.controller.cluster.datastore.TransactionProxy.Tra import static org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType.WRITE_ONLY; @SuppressWarnings("resource") -public class TransactionProxyTest extends AbstractActorTest { +public class TransactionProxyTest { @SuppressWarnings("serial") static class TestException extends RuntimeException { @@ -76,6 +80,8 @@ public class TransactionProxyTest extends AbstractActorTest { CheckedFuture invoke(TransactionProxy proxy) throws Exception; } + private static ActorSystem system; + private final Configuration configuration = new MockConfiguration(); @Mock @@ -83,21 +89,49 @@ public class TransactionProxyTest extends AbstractActorTest { private SchemaContext schemaContext; + @Mock + private ClusterWrapper mockClusterWrapper; + String memberName = "mock-member"; + @BeforeClass + public static void setUpClass() throws IOException { + + Config config = ConfigFactory.parseMap(ImmutableMap.builder(). + put("akka.actor.default-dispatcher.type", + "akka.testkit.CallingThreadDispatcherConfigurator").build()). + withFallback(ConfigFactory.load()); + system = ActorSystem.create("test", config); + } + + @AfterClass + public static void tearDownClass() throws IOException { + JavaTestKit.shutdownActorSystem(system); + system = null; + } + @Before public void setUp(){ MockitoAnnotations.initMocks(this); schemaContext = TestModel.createTestContext(); + DatastoreContext dataStoreContext = DatastoreContext.newBuilder().build(); + doReturn(getSystem()).when(mockActorContext).getActorSystem(); doReturn(memberName).when(mockActorContext).getCurrentMemberName(); doReturn(schemaContext).when(mockActorContext).getSchemaContext(); + doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper(); + doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper(); + doReturn(dataStoreContext).when(mockActorContext).getDatastoreContext(); ShardStrategyFactory.setConfiguration(configuration); } + private ActorSystem getSystem() { + return system; + } + private CreateTransaction eqCreateTransaction(final String memberName, final TransactionType type) { ArgumentMatcher matcher = new ArgumentMatcher() { @@ -112,7 +146,7 @@ public class TransactionProxyTest extends AbstractActorTest { return argThat(matcher); } - private DataExists eqDataExists() { + private DataExists eqSerializedDataExists() { ArgumentMatcher matcher = new ArgumentMatcher() { @Override public boolean matches(Object argument) { @@ -124,7 +158,19 @@ public class TransactionProxyTest extends AbstractActorTest { return argThat(matcher); } - private ReadData eqReadData() { + private DataExists eqDataExists() { + ArgumentMatcher matcher = new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + return (argument instanceof DataExists) && + ((DataExists)argument).getPath().equals(TestModel.TEST_PATH); + } + }; + + return argThat(matcher); + } + + private ReadData eqSerializedReadData() { ArgumentMatcher matcher = new ArgumentMatcher() { @Override public boolean matches(Object argument) { @@ -136,7 +182,19 @@ public class TransactionProxyTest extends AbstractActorTest { return argThat(matcher); } - private WriteData eqWriteData(final NormalizedNode nodeToWrite) { + private ReadData eqReadData() { + ArgumentMatcher matcher = new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + return (argument instanceof ReadData) && + ((ReadData)argument).getPath().equals(TestModel.TEST_PATH); + } + }; + + return argThat(matcher); + } + + private WriteData eqSerializedWriteData(final NormalizedNode nodeToWrite) { ArgumentMatcher matcher = new ArgumentMatcher() { @Override public boolean matches(Object argument) { @@ -153,7 +211,23 @@ public class TransactionProxyTest extends AbstractActorTest { return argThat(matcher); } - private MergeData eqMergeData(final NormalizedNode nodeToWrite) { + private WriteData eqWriteData(final NormalizedNode nodeToWrite) { + ArgumentMatcher matcher = new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + if(argument instanceof WriteData) { + WriteData obj = (WriteData) argument; + return obj.getPath().equals(TestModel.TEST_PATH) && + obj.getData().equals(nodeToWrite); + } + return false; + } + }; + + return argThat(matcher); + } + + private MergeData eqSerializedMergeData(final NormalizedNode nodeToWrite) { ArgumentMatcher matcher = new ArgumentMatcher() { @Override public boolean matches(Object argument) { @@ -170,7 +244,24 @@ public class TransactionProxyTest extends AbstractActorTest { return argThat(matcher); } - private DeleteData eqDeleteData() { + private MergeData eqMergeData(final NormalizedNode nodeToWrite) { + ArgumentMatcher matcher = new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + if(argument instanceof MergeData) { + MergeData obj = ((MergeData) argument); + return obj.getPath().equals(TestModel.TEST_PATH) && + obj.getData().equals(nodeToWrite); + } + + return false; + } + }; + + return argThat(matcher); + } + + private DeleteData eqSerializedDeleteData() { ArgumentMatcher matcher = new ArgumentMatcher() { @Override public boolean matches(Object argument) { @@ -182,54 +273,101 @@ public class TransactionProxyTest extends AbstractActorTest { return argThat(matcher); } - private Future readyTxReply(String path) { + private DeleteData eqDeleteData() { + ArgumentMatcher matcher = new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + return argument instanceof DeleteData && + ((DeleteData)argument).getPath().equals(TestModel.TEST_PATH); + } + }; + + return argThat(matcher); + } + + private Future readySerializedTxReply(String path) { return Futures.successful((Object)new ReadyTransactionReply(path).toSerializable()); } - private Future readDataReply(NormalizedNode data) { + private Future readyTxReply(String path) { + return Futures.successful((Object)new ReadyTransactionReply(path)); + } + + + private Future readSerializedDataReply(NormalizedNode data) { return Futures.successful(new ReadDataReply(schemaContext, data).toSerializable()); } - private Future dataExistsReply(boolean exists) { + private Future readDataReply(NormalizedNode data) { + return Futures.successful(new ReadDataReply(schemaContext, data)); + } + + private Future dataExistsSerializedReply(boolean exists) { return Futures.successful(new DataExistsReply(exists).toSerializable()); } - private Future writeDataReply() { + private Future dataExistsReply(boolean exists) { + return Futures.successful(new DataExistsReply(exists)); + } + + private Future writeSerializedDataReply() { return Futures.successful(new WriteDataReply().toSerializable()); } - private Future mergeDataReply() { + private Future writeDataReply() { + return Futures.successful(new WriteDataReply()); + } + + private Future mergeSerializedDataReply() { return Futures.successful(new MergeDataReply().toSerializable()); } - private Future deleteDataReply() { + private Future mergeDataReply() { + return Futures.successful(new MergeDataReply()); + } + + private Future deleteSerializedDataReply() { return Futures.successful(new DeleteDataReply().toSerializable()); } + private Future deleteDataReply() { + return Futures.successful(new DeleteDataReply()); + } + private ActorSelection actorSelection(ActorRef actorRef) { return getSystem().actorSelection(actorRef.path()); } - private CreateTransactionReply createTransactionReply(ActorRef actorRef){ + private CreateTransactionReply createTransactionReply(ActorRef actorRef, int transactionVersion){ return CreateTransactionReply.newBuilder() .setTransactionActorPath(actorRef.path().toString()) - .setTransactionId("txn-1").build(); + .setTransactionId("txn-1") + .setMessageVersion(transactionVersion) + .build(); } - private ActorRef setupActorContextWithInitialCreateTransaction(TransactionType type) { - ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class)); - doReturn(getSystem().actorSelection(actorRef.path())). + private ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type, int transactionVersion) { + ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class)); + doReturn(actorSystem.actorSelection(actorRef.path())). when(mockActorContext).actorSelection(actorRef.path().toString()); - doReturn(Optional.of(getSystem().actorSelection(actorRef.path()))). - when(mockActorContext).findPrimaryShard(eq(DefaultShardStrategy.DEFAULT_SHARD)); + doReturn(Futures.successful(actorSystem.actorSelection(actorRef.path()))). + when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD)); - doReturn(createTransactionReply(actorRef)).when(mockActorContext). - executeOperation(eq(getSystem().actorSelection(actorRef.path())), + doReturn(Futures.successful(createTransactionReply(actorRef, transactionVersion))).when(mockActorContext). + executeOperationAsync(eq(actorSystem.actorSelection(actorRef.path())), eqCreateTransaction(memberName, type)); + + doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString()); + return actorRef; } + private ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) { + return setupActorContextWithInitialCreateTransaction(actorSystem, type, CreateTransaction.CURRENT_VERSION); + } + + private void propagateReadFailedExceptionCause(CheckedFuture future) throws Throwable { @@ -243,13 +381,13 @@ public class TransactionProxyTest extends AbstractActorTest { @Test public void testRead() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(READ_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_ONLY); - doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqReadData()); + doReturn(readSerializedDataReply(null)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedReadData()); Optional> readOptional = transactionProxy.read( TestModel.TEST_PATH).get(5, TimeUnit.SECONDS); @@ -258,8 +396,8 @@ public class TransactionProxyTest extends AbstractActorTest { NormalizedNode expectedNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqReadData()); + doReturn(readSerializedDataReply(expectedNode)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedReadData()); readOptional = transactionProxy.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS); @@ -270,10 +408,10 @@ public class TransactionProxyTest extends AbstractActorTest { @Test(expected = ReadFailedException.class) public void testReadWithInvalidReplyMessageType() throws Exception { - setupActorContextWithInitialCreateTransaction(READ_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY); doReturn(Futures.successful(new Object())).when(mockActorContext). - executeOperationAsync(any(ActorSelection.class), any()); + executeOperationAsync(eq(actorSelection(actorRef)), eqSerializedReadData()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_ONLY); @@ -283,10 +421,10 @@ public class TransactionProxyTest extends AbstractActorTest { @Test(expected = TestException.class) public void testReadWithAsyncRemoteOperatonFailure() throws Throwable { - setupActorContextWithInitialCreateTransaction(READ_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY); doReturn(Futures.failed(new TestException())).when(mockActorContext). - executeOperationAsync(any(ActorSelection.class), any()); + executeOperationAsync(eq(actorSelection(actorRef)), eqSerializedReadData()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_ONLY); @@ -299,12 +437,14 @@ public class TransactionProxyTest extends AbstractActorTest { ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class)); if (exToThrow instanceof PrimaryNotFoundException) { - doReturn(Optional.absent()).when(mockActorContext).findPrimaryShard(anyString()); + doReturn(Futures.failed(exToThrow)).when(mockActorContext).findPrimaryShardAsync(anyString()); } else { - doReturn(Optional.of(getSystem().actorSelection(actorRef.path()))). - when(mockActorContext).findPrimaryShard(anyString()); + doReturn(Futures.successful(getSystem().actorSelection(actorRef.path()))). + when(mockActorContext).findPrimaryShardAsync(anyString()); } - doThrow(exToThrow).when(mockActorContext).executeOperation(any(ActorSelection.class), any()); + + doReturn(Futures.failed(exToThrow)).when(mockActorContext).executeOperationAsync( + any(ActorSelection.class), any()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_ONLY); @@ -338,18 +478,18 @@ public class TransactionProxyTest extends AbstractActorTest { @Test(expected = TestException.class) public void testReadWithPriorRecordingOperationFailure() throws Throwable { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(READ_WRITE); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(writeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqWriteData(nodeToWrite)); + doReturn(writeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); doReturn(Futures.failed(new TestException())).when(mockActorContext). - executeOperationAsync(eq(actorSelection(actorRef)), eqDeleteData()); + executeOperationAsync(eq(actorSelection(actorRef)), eqSerializedDeleteData()); - doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqReadData()); + doReturn(readSerializedDataReply(null)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedReadData()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_WRITE); @@ -362,21 +502,21 @@ public class TransactionProxyTest extends AbstractActorTest { propagateReadFailedExceptionCause(transactionProxy.read(TestModel.TEST_PATH)); } finally { verify(mockActorContext, times(0)).executeOperationAsync( - eq(actorSelection(actorRef)), eqReadData()); + eq(actorSelection(actorRef)), eqSerializedReadData()); } } @Test public void testReadWithPriorRecordingOperationSuccessful() throws Throwable { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(READ_WRITE); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE); NormalizedNode expectedNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(writeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqWriteData(expectedNode)); + doReturn(writeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedWriteData(expectedNode)); - doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqReadData()); + doReturn(readSerializedDataReply(expectedNode)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedReadData()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_WRITE); @@ -400,22 +540,40 @@ public class TransactionProxyTest extends AbstractActorTest { transactionProxy.read(TestModel.TEST_PATH); } + @Test(expected=IllegalArgumentException.class) + public void testInvalidCreateTransactionReply() throws Throwable { + ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class)); + + doReturn(getSystem().actorSelection(actorRef.path())).when(mockActorContext). + actorSelection(actorRef.path().toString()); + + doReturn(Futures.successful(getSystem().actorSelection(actorRef.path()))). + when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD)); + + doReturn(Futures.successful(new Object())).when(mockActorContext).executeOperationAsync( + eq(getSystem().actorSelection(actorRef.path())), eqCreateTransaction(memberName, READ_ONLY)); + + TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_ONLY); + + propagateReadFailedExceptionCause(transactionProxy.read(TestModel.TEST_PATH)); + } + @Test public void testExists() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(READ_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_ONLY); - doReturn(dataExistsReply(false)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqDataExists()); + doReturn(dataExistsSerializedReply(false)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedDataExists()); Boolean exists = transactionProxy.exists(TestModel.TEST_PATH).checkedGet(); assertEquals("Exists response", false, exists); - doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqDataExists()); + doReturn(dataExistsSerializedReply(true)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedDataExists()); exists = transactionProxy.exists(TestModel.TEST_PATH).checkedGet(); @@ -434,10 +592,10 @@ public class TransactionProxyTest extends AbstractActorTest { @Test(expected = ReadFailedException.class) public void testExistsWithInvalidReplyMessageType() throws Exception { - setupActorContextWithInitialCreateTransaction(READ_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY); doReturn(Futures.successful(new Object())).when(mockActorContext). - executeOperationAsync(any(ActorSelection.class), any()); + executeOperationAsync(eq(actorSelection(actorRef)), eqSerializedDataExists()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_ONLY); @@ -447,10 +605,10 @@ public class TransactionProxyTest extends AbstractActorTest { @Test(expected = TestException.class) public void testExistsWithAsyncRemoteOperatonFailure() throws Throwable { - setupActorContextWithInitialCreateTransaction(READ_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY); doReturn(Futures.failed(new TestException())).when(mockActorContext). - executeOperationAsync(any(ActorSelection.class), any()); + executeOperationAsync(eq(actorSelection(actorRef)), eqSerializedDataExists()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_ONLY); @@ -460,18 +618,18 @@ public class TransactionProxyTest extends AbstractActorTest { @Test(expected = TestException.class) public void testExistsWithPriorRecordingOperationFailure() throws Throwable { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(READ_WRITE); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(writeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqWriteData(nodeToWrite)); + doReturn(writeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); doReturn(Futures.failed(new TestException())).when(mockActorContext). - executeOperationAsync(eq(actorSelection(actorRef)), eqDeleteData()); + executeOperationAsync(eq(actorSelection(actorRef)), eqSerializedDeleteData()); - doReturn(dataExistsReply(false)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqDataExists()); + doReturn(dataExistsSerializedReply(false)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedDataExists()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_WRITE); @@ -484,21 +642,21 @@ public class TransactionProxyTest extends AbstractActorTest { propagateReadFailedExceptionCause(transactionProxy.exists(TestModel.TEST_PATH)); } finally { verify(mockActorContext, times(0)).executeOperationAsync( - eq(actorSelection(actorRef)), eqDataExists()); + eq(actorSelection(actorRef)), eqSerializedDataExists()); } } @Test public void testExistsWithPriorRecordingOperationSuccessful() throws Throwable { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(READ_WRITE); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(writeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqWriteData(nodeToWrite)); + doReturn(writeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); - doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqDataExists()); + doReturn(dataExistsSerializedReply(true)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedDataExists()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_WRITE); @@ -544,12 +702,12 @@ public class TransactionProxyTest extends AbstractActorTest { @Test public void testWrite() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(WRITE_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(writeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqWriteData(nodeToWrite)); + doReturn(writeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, WRITE_ONLY); @@ -557,7 +715,7 @@ public class TransactionProxyTest extends AbstractActorTest { transactionProxy.write(TestModel.TEST_PATH, nodeToWrite); verify(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqWriteData(nodeToWrite)); + eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); verifyRecordingOperationFutures(transactionProxy.getRecordedOperationFutures(), WriteDataReply.SERIALIZABLE_CLASS); @@ -587,20 +745,19 @@ public class TransactionProxyTest extends AbstractActorTest { @Test public void testMerge() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(WRITE_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(mergeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqMergeData(nodeToWrite)); + doReturn(mergeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedMergeData(nodeToWrite)); - TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, - WRITE_ONLY); + TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, WRITE_ONLY); transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite); verify(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqMergeData(nodeToWrite)); + eq(actorSelection(actorRef)), eqSerializedMergeData(nodeToWrite)); verifyRecordingOperationFutures(transactionProxy.getRecordedOperationFutures(), MergeDataReply.SERIALIZABLE_CLASS); @@ -608,10 +765,10 @@ public class TransactionProxyTest extends AbstractActorTest { @Test public void testDelete() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(WRITE_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY); - doReturn(deleteDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqDeleteData()); + doReturn(deleteSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedDeleteData()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, WRITE_ONLY); @@ -619,7 +776,7 @@ public class TransactionProxyTest extends AbstractActorTest { transactionProxy.delete(TestModel.TEST_PATH); verify(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqDeleteData()); + eq(actorSelection(actorRef)), eqSerializedDeleteData()); verifyRecordingOperationFutures(transactionProxy.getRecordedOperationFutures(), DeleteDataReply.SERIALIZABLE_CLASS); @@ -637,7 +794,7 @@ public class TransactionProxyTest extends AbstractActorTest { Object expReply = expReplies[i++]; if(expReply instanceof ActorSelection) { ActorSelection actual = Await.result(future, Duration.create(5, TimeUnit.SECONDS)); - assertEquals("Cohort actor path", (ActorSelection) expReply, actual); + assertEquals("Cohort actor path", expReply, actual); } else { // Expecting exception. try { @@ -653,17 +810,17 @@ public class TransactionProxyTest extends AbstractActorTest { @SuppressWarnings("unchecked") @Test public void testReady() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(READ_WRITE); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqReadData()); + doReturn(readSerializedDataReply(null)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedReadData()); - doReturn(writeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqWriteData(nodeToWrite)); + doReturn(writeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); - doReturn(readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync( + doReturn(readySerializedTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync( eq(actorSelection(actorRef)), isA(ReadyTransaction.SERIALIZABLE_CLASS)); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, @@ -685,22 +842,65 @@ public class TransactionProxyTest extends AbstractActorTest { verifyCohortFutures(proxy, getSystem().actorSelection(actorRef.path())); } + @SuppressWarnings("unchecked") + @Test + public void testReadyForwardCompatibility() throws Exception { + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE, 0); + + NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); + + doReturn(readSerializedDataReply(null)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedReadData()); + + doReturn(writeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); + + doReturn(readySerializedTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), isA(ReadyTransaction.SERIALIZABLE_CLASS)); + + doReturn(actorRef.path().toString()).when(mockActorContext).resolvePath(eq(actorRef.path().toString()), + eq(actorRef.path().toString())); + + TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, + READ_WRITE); + + transactionProxy.read(TestModel.TEST_PATH); + + transactionProxy.write(TestModel.TEST_PATH, nodeToWrite); + + DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready(); + + assertTrue(ready instanceof ThreePhaseCommitCohortProxy); + + ThreePhaseCommitCohortProxy proxy = (ThreePhaseCommitCohortProxy) ready; + + verifyRecordingOperationFutures(transactionProxy.getRecordedOperationFutures(), + WriteDataReply.SERIALIZABLE_CLASS); + + verifyCohortFutures(proxy, getSystem().actorSelection(actorRef.path())); + + verify(mockActorContext).resolvePath(eq(actorRef.path().toString()), + eq(actorRef.path().toString())); + } + @SuppressWarnings("unchecked") @Test public void testReadyWithRecordingOperationFailure() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(WRITE_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(mergeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqMergeData(nodeToWrite)); + doReturn(mergeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedMergeData(nodeToWrite)); doReturn(Futures.failed(new TestException())).when(mockActorContext). - executeOperationAsync(eq(actorSelection(actorRef)), eqWriteData(nodeToWrite)); + executeOperationAsync(eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); - doReturn(readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync( + doReturn(readySerializedTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync( eq(actorSelection(actorRef)), isA(ReadyTransaction.SERIALIZABLE_CLASS)); + doReturn(false).when(mockActorContext).isPathLocal(actorRef.path().toString()); + TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, WRITE_ONLY); @@ -714,21 +914,21 @@ public class TransactionProxyTest extends AbstractActorTest { ThreePhaseCommitCohortProxy proxy = (ThreePhaseCommitCohortProxy) ready; + verifyCohortFutures(proxy, TestException.class); + verifyRecordingOperationFutures(transactionProxy.getRecordedOperationFutures(), MergeDataReply.SERIALIZABLE_CLASS, TestException.class); - - verifyCohortFutures(proxy, TestException.class); } @SuppressWarnings("unchecked") @Test public void testReadyWithReplyFailure() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(WRITE_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(mergeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqMergeData(nodeToWrite)); + doReturn(mergeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedMergeData(nodeToWrite)); doReturn(Futures.failed(new TestException())).when(mockActorContext). executeOperationAsync(eq(actorSelection(actorRef)), @@ -754,9 +954,8 @@ public class TransactionProxyTest extends AbstractActorTest { @Test public void testReadyWithInitialCreateTransactionFailure() throws Exception { - doReturn(Optional.absent()).when(mockActorContext).findPrimaryShard(anyString()); -// doThrow(new PrimaryNotFoundException("mock")).when(mockActorContext).executeShardOperation( -// anyString(), any()); + doReturn(Futures.failed(new PrimaryNotFoundException("mock"))).when( + mockActorContext).findPrimaryShardAsync(anyString()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, WRITE_ONLY); @@ -781,12 +980,12 @@ public class TransactionProxyTest extends AbstractActorTest { @SuppressWarnings("unchecked") @Test public void testReadyWithInvalidReplyMessageType() throws Exception { - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(WRITE_ONLY); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY); NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); - doReturn(writeDataReply()).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqWriteData(nodeToWrite)); + doReturn(writeSerializedDataReply()).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedWriteData(nodeToWrite)); doReturn(Futures.successful(new Object())).when(mockActorContext). executeOperationAsync(eq(actorSelection(actorRef)), @@ -808,7 +1007,7 @@ public class TransactionProxyTest extends AbstractActorTest { @Test public void testGetIdentifier() { - setupActorContextWithInitialCreateTransaction(READ_ONLY); + setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, TransactionProxy.TransactionType.READ_ONLY); @@ -820,10 +1019,10 @@ public class TransactionProxyTest extends AbstractActorTest { @SuppressWarnings("unchecked") @Test public void testClose() throws Exception{ - ActorRef actorRef = setupActorContextWithInitialCreateTransaction(READ_WRITE); + ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE); - doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync( - eq(actorSelection(actorRef)), eqReadData()); + doReturn(readSerializedDataReply(null)).when(mockActorContext).executeOperationAsync( + eq(actorSelection(actorRef)), eqSerializedReadData()); TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, READ_WRITE); @@ -835,4 +1034,140 @@ public class TransactionProxyTest extends AbstractActorTest { verify(mockActorContext).sendOperationAsync( eq(actorSelection(actorRef)), isA(CloseTransaction.SERIALIZABLE_CLASS)); } + + + /** + * Method to test a local Tx actor. The Tx paths are matched to decide if the + * Tx actor is local or not. This is done by mocking the Tx actor path + * and the caller paths and ensuring that the paths have the remote-address format + * + * Note: Since the default akka provider for test is not a RemoteActorRefProvider, + * the paths returned for the actors for all the tests are not qualified remote paths. + * Hence are treated as non-local/remote actors. In short, all tests except + * few below run for remote actors + * + * @throws Exception + */ + @Test + public void testLocalTxActorRead() throws Exception { + ActorSystem actorSystem = getSystem(); + ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class)); + + doReturn(actorSystem.actorSelection(shardActorRef.path())). + when(mockActorContext).actorSelection(shardActorRef.path().toString()); + + doReturn(Futures.successful(actorSystem.actorSelection(shardActorRef.path()))). + when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD)); + + String actorPath = "akka.tcp://system@127.0.0.1:2550/user/tx-actor"; + CreateTransactionReply createTransactionReply = CreateTransactionReply.newBuilder() + .setTransactionId("txn-1") + .setTransactionActorPath(actorPath) + .build(); + + doReturn(Futures.successful(createTransactionReply)).when(mockActorContext). + executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())), + eqCreateTransaction(memberName, READ_ONLY)); + + doReturn(true).when(mockActorContext).isPathLocal(actorPath); + + TransactionProxy transactionProxy = new TransactionProxy(mockActorContext,READ_ONLY); + + // negative test case with null as the reply + doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync( + any(ActorSelection.class), eqReadData()); + + Optional> readOptional = transactionProxy.read( + TestModel.TEST_PATH).get(5, TimeUnit.SECONDS); + + assertEquals("NormalizedNode isPresent", false, readOptional.isPresent()); + + // test case with node as read data reply + NormalizedNode expectedNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME); + + doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync( + any(ActorSelection.class), eqReadData()); + + readOptional = transactionProxy.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS); + + assertEquals("NormalizedNode isPresent", true, readOptional.isPresent()); + + assertEquals("Response NormalizedNode", expectedNode, readOptional.get()); + + // test for local data exists + doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync( + any(ActorSelection.class), eqDataExists()); + + boolean exists = transactionProxy.exists(TestModel.TEST_PATH).checkedGet(); + + assertEquals("Exists response", true, exists); + } + + @Test + public void testLocalTxActorWrite() throws Exception { + ActorSystem actorSystem = getSystem(); + ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class)); + + doReturn(actorSystem.actorSelection(shardActorRef.path())). + when(mockActorContext).actorSelection(shardActorRef.path().toString()); + + doReturn(Futures.successful(actorSystem.actorSelection(shardActorRef.path()))). + when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD)); + + String actorPath = "akka.tcp://system@127.0.0.1:2550/user/tx-actor"; + CreateTransactionReply createTransactionReply = CreateTransactionReply.newBuilder() + .setTransactionId("txn-1") + .setTransactionActorPath(actorPath) + .build(); + + doReturn(Futures.successful(createTransactionReply)).when(mockActorContext). + executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())), + eqCreateTransaction(memberName, WRITE_ONLY)); + + doReturn(true).when(mockActorContext).isPathLocal(actorPath); + + NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME); + + doReturn(writeDataReply()).when(mockActorContext).executeOperationAsync( + any(ActorSelection.class), eqWriteData(nodeToWrite)); + + TransactionProxy transactionProxy = new TransactionProxy(mockActorContext, WRITE_ONLY); + transactionProxy.write(TestModel.TEST_PATH, nodeToWrite); + + verify(mockActorContext).executeOperationAsync( + any(ActorSelection.class), eqWriteData(nodeToWrite)); + + //testing local merge + doReturn(mergeDataReply()).when(mockActorContext).executeOperationAsync( + any(ActorSelection.class), eqMergeData(nodeToWrite)); + + transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite); + + verify(mockActorContext).executeOperationAsync( + any(ActorSelection.class), eqMergeData(nodeToWrite)); + + + //testing local delete + doReturn(deleteDataReply()).when(mockActorContext).executeOperationAsync( + any(ActorSelection.class), eqDeleteData()); + + transactionProxy.delete(TestModel.TEST_PATH); + + verify(mockActorContext).executeOperationAsync(any(ActorSelection.class), eqDeleteData()); + + verifyRecordingOperationFutures(transactionProxy.getRecordedOperationFutures(), + WriteDataReply.class, MergeDataReply.class, DeleteDataReply.class); + + // testing ready + doReturn(readyTxReply(shardActorRef.path().toString())).when(mockActorContext).executeOperationAsync( + any(ActorSelection.class), isA(ReadyTransaction.class)); + + DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready(); + + assertTrue(ready instanceof ThreePhaseCommitCohortProxy); + + ThreePhaseCommitCohortProxy proxy = (ThreePhaseCommitCohortProxy) ready; + + verifyCohortFutures(proxy, getSystem().actorSelection(shardActorRef.path())); + } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/DefaultShardStrategyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/DefaultShardStrategyTest.java index d3ba9b1c15..c065782af5 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/DefaultShardStrategyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/DefaultShardStrategyTest.java @@ -1,6 +1,6 @@ package org.opendaylight.controller.cluster.datastore.shardstrategy; -import junit.framework.Assert; +import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.md.cluster.datastore.model.TestModel; diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ModuleShardStrategyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ModuleShardStrategyTest.java index 3394cdc959..b895b75fcd 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ModuleShardStrategyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ModuleShardStrategyTest.java @@ -1,5 +1,6 @@ package org.opendaylight.controller.cluster.datastore.shardstrategy; +import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -10,8 +11,6 @@ import org.opendaylight.controller.md.cluster.datastore.model.CarsModel; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import static junit.framework.Assert.assertEquals; - public class ModuleShardStrategyTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ShardStrategyFactoryTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ShardStrategyFactoryTest.java index ab74ba811a..10e832780d 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ShardStrategyFactoryTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/shardstrategy/ShardStrategyFactoryTest.java @@ -1,5 +1,7 @@ package org.opendaylight.controller.cluster.datastore.shardstrategy; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -9,9 +11,6 @@ import org.opendaylight.controller.md.cluster.datastore.model.CarsModel; import org.opendaylight.controller.md.cluster.datastore.model.TestModel; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import static junit.framework.Assert.assertNotNull; -import static junit.framework.Assert.assertTrue; - public class ShardStrategyFactoryTest { @Rule diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/ActorContextTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/ActorContextTest.java index 8426b03a37..fcb0324bea 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/ActorContextTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/ActorContextTest.java @@ -2,12 +2,14 @@ package org.opendaylight.controller.cluster.datastore.utils; import akka.actor.ActorRef; import akka.actor.ActorSelection; +import akka.actor.ActorSystem; +import akka.actor.Address; import akka.actor.Props; import akka.actor.UntypedActor; import akka.japi.Creator; import akka.testkit.JavaTestKit; import com.google.common.base.Optional; - +import java.util.concurrent.TimeUnit; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.AbstractActorTest; import org.opendaylight.controller.cluster.datastore.ClusterWrapper; @@ -19,8 +21,6 @@ import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; -import java.util.concurrent.TimeUnit; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -99,23 +99,15 @@ public class ActorContextTest extends AbstractActorTest{ @Test public void testFindLocalShardWithShardNotFound(){ new JavaTestKit(getSystem()) {{ + ActorRef shardManagerActorRef = getSystem() + .actorOf(MockShardManager.props(false, null)); - new Within(duration("1 seconds")) { - @Override - protected void run() { - - ActorRef shardManagerActorRef = getSystem() - .actorOf(MockShardManager.props(false, null)); - - ActorContext actorContext = - new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class), + ActorContext actorContext = + new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class), mock(Configuration.class)); - Optional out = actorContext.findLocalShard("default"); - assertTrue(!out.isPresent()); - expectNoMsg(); - } - }; + Optional out = actorContext.findLocalShard("default"); + assertTrue(!out.isPresent()); }}; } @@ -123,63 +115,156 @@ public class ActorContextTest extends AbstractActorTest{ @Test public void testExecuteRemoteOperation() { new JavaTestKit(getSystem()) {{ + ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class)); - new Within(duration("3 seconds")) { - @Override - protected void run() { - - ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class)); + ActorRef shardManagerActorRef = getSystem() + .actorOf(MockShardManager.props(true, shardActorRef)); - ActorRef shardManagerActorRef = getSystem() - .actorOf(MockShardManager.props(true, shardActorRef)); - - ActorContext actorContext = - new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class), + ActorContext actorContext = + new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class), mock(Configuration.class)); - ActorSelection actor = actorContext.actorSelection(shardActorRef.path()); - - Object out = actorContext.executeOperation(actor, "hello"); + ActorSelection actor = actorContext.actorSelection(shardActorRef.path()); - assertEquals("hello", out); + Object out = actorContext.executeOperation(actor, "hello"); - expectNoMsg(); - } - }; + assertEquals("hello", out); }}; } @Test public void testExecuteRemoteOperationAsync() { new JavaTestKit(getSystem()) {{ + ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class)); - new Within(duration("3 seconds")) { - @Override - protected void run() { + ActorRef shardManagerActorRef = getSystem() + .actorOf(MockShardManager.props(true, shardActorRef)); - ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class)); + ActorContext actorContext = + new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class), + mock(Configuration.class)); - ActorRef shardManagerActorRef = getSystem() - .actorOf(MockShardManager.props(true, shardActorRef)); + ActorSelection actor = actorContext.actorSelection(shardActorRef.path()); - ActorContext actorContext = - new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class), - mock(Configuration.class)); + Future future = actorContext.executeOperationAsync(actor, "hello"); - ActorSelection actor = actorContext.actorSelection(shardActorRef.path()); + try { + Object result = Await.result(future, Duration.create(3, TimeUnit.SECONDS)); + assertEquals("Result", "hello", result); + } catch(Exception e) { + throw new AssertionError(e); + } + }}; + } - Future future = actorContext.executeOperationAsync(actor, "hello"); + @Test + public void testIsPathLocal() { + MockClusterWrapper clusterWrapper = new MockClusterWrapper(); + ActorContext actorContext = null; + + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(false, actorContext.isPathLocal(null)); + assertEquals(false, actorContext.isPathLocal("")); + + clusterWrapper.setSelfAddress(null); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(false, actorContext.isPathLocal("")); + + // even if the path is in local format, match the primary path (first 3 elements) and return true + clusterWrapper.setSelfAddress(new Address("akka", "test")); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(true, actorContext.isPathLocal("akka://test/user/$a")); + + clusterWrapper.setSelfAddress(new Address("akka", "test")); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(true, actorContext.isPathLocal("akka://test/user/$a")); + + clusterWrapper.setSelfAddress(new Address("akka", "test")); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(true, actorContext.isPathLocal("akka://test/user/token2/token3/$a")); + + // self address of remote format,but Tx path local format. + clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550)); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(true, actorContext.isPathLocal( + "akka://system/user/shardmanager/shard/transaction")); + + // self address of local format,but Tx path remote format. + clusterWrapper.setSelfAddress(new Address("akka.tcp", "system")); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(false, actorContext.isPathLocal( + "akka://system@127.0.0.1:2550/user/shardmanager/shard/transaction")); + + //local path but not same + clusterWrapper.setSelfAddress(new Address("akka", "test")); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(true, actorContext.isPathLocal("akka://test1/user/$a")); + + //ip and port same + clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550)); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(true, actorContext.isPathLocal("akka.tcp://system@127.0.0.1:2550/")); + + // forward-slash missing in address + clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550)); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(false, actorContext.isPathLocal("akka.tcp://system@127.0.0.1:2550")); + + //ips differ + clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550)); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(false, actorContext.isPathLocal("akka.tcp://system@127.1.0.1:2550/")); + + //ports differ + clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550)); + actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class)); + assertEquals(false, actorContext.isPathLocal("akka.tcp://system@127.0.0.1:2551/")); + } - try { - Object result = Await.result(future, Duration.create(3, TimeUnit.SECONDS)); - assertEquals("Result", "hello", result); - } catch(Exception e) { - throw new AssertionError(e); - } + @Test + public void testResolvePathForRemoteActor() { + ActorContext actorContext = + new ActorContext(mock(ActorSystem.class), mock(ActorRef.class), mock( + ClusterWrapper.class), + mock(Configuration.class)); - expectNoMsg(); - } - }; - }}; + String actual = actorContext.resolvePath( + "akka.tcp://system@127.0.0.1:2550/user/shardmanager/shard", + "akka://system/user/shardmanager/shard/transaction"); + + String expected = "akka.tcp://system@127.0.0.1:2550/user/shardmanager/shard/transaction"; + + assertEquals(expected, actual); + } + + @Test + public void testResolvePathForLocalActor() { + ActorContext actorContext = + new ActorContext(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class), + mock(Configuration.class)); + + String actual = actorContext.resolvePath( + "akka://system/user/shardmanager/shard", + "akka://system/user/shardmanager/shard/transaction"); + + String expected = "akka://system/user/shardmanager/shard/transaction"; + + assertEquals(expected, actual); } + + @Test + public void testResolvePathForRemoteActorWithProperRemoteAddress() { + ActorContext actorContext = + new ActorContext(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class), + mock(Configuration.class)); + + String actual = actorContext.resolvePath( + "akka.tcp://system@7.0.0.1:2550/user/shardmanager/shard", + "akka.tcp://system@7.0.0.1:2550/user/shardmanager/shard/transaction"); + + String expected = "akka.tcp://system@7.0.0.1:2550/user/shardmanager/shard/transaction"; + + assertEquals(expected, actual); + } + } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/InMemoryJournal.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/InMemoryJournal.java index 3486753082..f340d1c305 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/InMemoryJournal.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/InMemoryJournal.java @@ -32,6 +32,8 @@ public class InMemoryJournal extends AsyncWriteJournal { private static final Map deleteMessagesCompleteLatches = new ConcurrentHashMap<>(); + private static final Map blockReadMessagesLatches = new ConcurrentHashMap<>(); + public static void addEntry(String persistenceId, long sequenceNr, Object data) { Map journal = journals.get(persistenceId); if(journal == null) { @@ -62,12 +64,21 @@ public class InMemoryJournal extends AsyncWriteJournal { deleteMessagesCompleteLatches.put(persistenceId, new CountDownLatch(1)); } + public static void addBlockReadMessagesLatch(String persistenceId, CountDownLatch latch) { + blockReadMessagesLatches.put(persistenceId, latch); + } + @Override public Future doAsyncReplayMessages(final String persistenceId, long fromSequenceNr, long toSequenceNr, long max, final Procedure replayCallback) { return Futures.future(new Callable() { @Override public Void call() throws Exception { + CountDownLatch blockLatch = blockReadMessagesLatches.remove(persistenceId); + if(blockLatch != null) { + Uninterruptibles.awaitUninterruptibly(blockLatch); + } + Map journal = journals.get(persistenceId); if(journal == null) { return null; diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockClusterWrapper.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockClusterWrapper.java index 803aa03b7c..fe40aa0fd4 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockClusterWrapper.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockClusterWrapper.java @@ -9,25 +9,38 @@ package org.opendaylight.controller.cluster.datastore.utils; import akka.actor.ActorRef; +import akka.actor.Address; import akka.actor.AddressFromURIString; import akka.cluster.ClusterEvent; import akka.cluster.MemberStatus; import akka.cluster.UniqueAddress; import org.opendaylight.controller.cluster.datastore.ClusterWrapper; import scala.collection.JavaConversions; - import java.util.HashSet; import java.util.Set; public class MockClusterWrapper implements ClusterWrapper{ - @Override public void subscribeToMemberEvents(ActorRef actorRef) { + private Address selfAddress = new Address("akka.tcp", "test", "127.0.0.1", 2550); + + @Override + public void subscribeToMemberEvents(ActorRef actorRef) { } - @Override public String getCurrentMemberName() { + @Override + public String getCurrentMemberName() { return "member-1"; } + @Override + public Address getSelfAddress() { + return selfAddress; + } + + public void setSelfAddress(Address selfAddress) { + this.selfAddress = selfAddress; + } + public static void sendMemberUp(ActorRef to, String memberName, String address){ to.tell(createMemberUp(memberName, address), null); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockConfiguration.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockConfiguration.java index 06c5767bd0..4ef7d65857 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockConfiguration.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockConfiguration.java @@ -9,43 +9,42 @@ package org.opendaylight.controller.cluster.datastore.utils; import com.google.common.base.Optional; -import org.opendaylight.controller.cluster.datastore.Configuration; -import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy; - import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; +import org.opendaylight.controller.cluster.datastore.Configuration; +import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy; public class MockConfiguration implements Configuration{ - @Override public List getMemberShardNames(String memberName) { + @Override public List getMemberShardNames(final String memberName) { return Arrays.asList("default"); } @Override public Optional getModuleNameFromNameSpace( - String nameSpace) { + final String nameSpace) { return Optional.absent(); } @Override public Map getModuleNameToShardStrategyMap() { - return Collections.EMPTY_MAP; + return Collections.emptyMap(); } @Override public List getShardNamesFromModuleName( - String moduleName) { - return Collections.EMPTY_LIST; + final String moduleName) { + return Collections.emptyList(); } - @Override public List getMembersFromShardName(String shardName) { + @Override public List getMembersFromShardName(final String shardName) { if("default".equals(shardName)) { return Arrays.asList("member-1", "member-2"); } else if("astronauts".equals(shardName)){ return Arrays.asList("member-2", "member-3"); } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } @Override public Set getAllShardNames() { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockDataChangeListener.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockDataChangeListener.java new file mode 100644 index 0000000000..efd58620a2 --- /dev/null +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockDataChangeListener.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.cluster.datastore.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import com.google.common.collect.Lists; +import com.google.common.util.concurrent.Uninterruptibles; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; +import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; + +/** + * A mock DataChangeListener implementation. + * + * @author Thomas Pantelis + */ +public class MockDataChangeListener implements + AsyncDataChangeListener> { + + private final List>> changeList = + Collections.synchronizedList(Lists.>>newArrayList()); + + private volatile CountDownLatch changeLatch; + private int expChangeEventCount; + + public MockDataChangeListener(int expChangeEventCount) { + reset(expChangeEventCount); + } + + public void reset(int expChangeEventCount) { + changeLatch = new CountDownLatch(expChangeEventCount); + this.expChangeEventCount = expChangeEventCount; + changeList.clear(); + } + + @Override + public void onDataChanged(AsyncDataChangeEvent> change) { + changeList.add(change); + changeLatch.countDown(); + } + + public void waitForChangeEvents(YangInstanceIdentifier... expPaths) { + boolean done = Uninterruptibles.awaitUninterruptibly(changeLatch, 5, TimeUnit.SECONDS); + if(!done) { + fail(String.format("Missing change notifications. Expected: %d. Actual: %d", + expChangeEventCount, (expChangeEventCount - changeLatch.getCount()))); + } + + for(int i = 0; i < expPaths.length; i++) { + assertTrue(String.format("Change %d does not contain %s", (i+1), expPaths[i]), + changeList.get(i).getCreatedData().containsKey(expPaths[i])); + } + } + + public void expectNoMoreChanges(String assertMsg) { + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); + assertEquals(assertMsg, expChangeEventCount, changeList.size()); + } +} diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/TestUtils.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/TestUtils.java index 3bad468950..a2c44b0630 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/TestUtils.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/TestUtils.java @@ -11,13 +11,12 @@ package org.opendaylight.controller.cluster.datastore.utils; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; -import junit.framework.Assert; - import java.util.List; +import org.junit.Assert; public class TestUtils { - public static void assertFirstSentMessage(ActorSystem actorSystem, ActorRef actorRef, Class clazz){ + public static void assertFirstSentMessage(final ActorSystem actorSystem, final ActorRef actorRef, final Class clazz){ ActorContext testContext = new ActorContext(actorSystem, actorSystem.actorOf( Props.create(DoNothingActor.class)), new MockClusterWrapper(), new MockConfiguration()); Object messages = testContext @@ -27,7 +26,7 @@ public class TestUtils { Assert.assertTrue(messages instanceof List); - List listMessages = (List) messages; + List listMessages = (List) messages; Assert.assertEquals(1, listMessages.size()); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/CarsModel.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/CarsModel.java index 6860872b75..93b552a6da 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/CarsModel.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/CarsModel.java @@ -31,7 +31,7 @@ public class CarsModel { public static final QName CAR_PRICE_QNAME = QName.create(CAR_QNAME, "price"); - public static NormalizedNode create(){ + public static NormalizedNode create(){ // Create a list builder CollectionNodeBuilder cars = @@ -63,7 +63,7 @@ public class CarsModel { } - public static NormalizedNode emptyContainer(){ + public static NormalizedNode emptyContainer(){ return ImmutableContainerNodeBuilder.create() .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(BASE_QNAME)) .build(); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/PeopleModel.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/PeopleModel.java index e637920e78..a7cb14f0b3 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/PeopleModel.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/PeopleModel.java @@ -30,7 +30,7 @@ public class PeopleModel { - public static NormalizedNode create(){ + public static NormalizedNode create(){ // Create a list builder CollectionNodeBuilder cars = @@ -62,7 +62,7 @@ public class PeopleModel { } - public static NormalizedNode emptyContainer(){ + public static NormalizedNode emptyContainer(){ return ImmutableContainerNodeBuilder.create() .withNodeIdentifier( new YangInstanceIdentifier.NodeIdentifier(BASE_QNAME)) diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java index 2300f9d130..b814bc392e 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java @@ -8,7 +8,7 @@ package org.opendaylight.controller.md.cluster.datastore.model; -import junit.framework.Assert; +import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec; import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; diff --git a/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java index fdb864059f..4632ed8a6f 100644 --- a/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java +++ b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java @@ -14,7 +14,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; /** - * Data Broker which provides data transaction and data change listener fuctionality + * Data Broker which provides data transaction and data change listener functionality * using {@link NormalizedNode} data format. * * This interface is type capture of generic interfaces and returns type captures diff --git a/opendaylight/md-sal/sal-dom-broker/pom.xml b/opendaylight/md-sal/sal-dom-broker/pom.xml index dc20296ff5..60581f99cb 100644 --- a/opendaylight/md-sal/sal-dom-broker/pom.xml +++ b/opendaylight/md-sal/sal-dom-broker/pom.xml @@ -10,10 +10,6 @@ bundle - - com.github.romix - java-concurrent-hash-trie-map - com.google.guava guava @@ -45,8 +41,6 @@ org.opendaylight.controller sal-inmemory-datastore - 1.2.0-SNAPSHOT - org.opendaylight.yangtools @@ -74,7 +68,6 @@ org.slf4j slf4j-simple - ${slf4j.version} test @@ -106,7 +99,6 @@ org.opendaylight.yangtools.yang.util, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.dom.impl.rev131028.* * - java-concurrent-hash-trie-map;inline=true diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMConcurrentDataCommitCoordinator.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMConcurrentDataCommitCoordinator.java index 605d71d81e..d8a7a0084c 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMConcurrentDataCommitCoordinator.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMConcurrentDataCommitCoordinator.java @@ -7,6 +7,14 @@ */ package org.opendaylight.controller.md.sal.dom.broker.impl; +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import com.google.common.util.concurrent.AbstractFuture; +import com.google.common.util.concurrent.AbstractListeningExecutorService; +import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; @@ -19,14 +27,6 @@ import org.opendaylight.yangtools.util.DurationStatisticsTracker; import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; -import com.google.common.util.concurrent.AbstractFuture; -import com.google.common.util.concurrent.AbstractListeningExecutorService; -import com.google.common.util.concurrent.CheckedFuture; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; /** * Implementation of DOMDataCommitExecutor that coordinates transaction commits concurrently. The 3 @@ -95,7 +95,8 @@ public class DOMConcurrentDataCommitCoordinator implements DOMDataCommitExecutor public void onSuccess(Boolean result) { if (result == null || !result) { handleException(clientSubmitFuture, transaction, cohorts, cohortSize, - CAN_COMMIT, new TransactionCommitFailedException( + CAN_COMMIT, TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, + new TransactionCommitFailedException( "Can Commit failed, no detailed cause available.")); } else { if(remaining.decrementAndGet() == 0) { @@ -107,7 +108,8 @@ public class DOMConcurrentDataCommitCoordinator implements DOMDataCommitExecutor @Override public void onFailure(Throwable t) { - handleException(clientSubmitFuture, transaction, cohorts, cohortSize, CAN_COMMIT, t); + handleException(clientSubmitFuture, transaction, cohorts, cohortSize, CAN_COMMIT, + TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER, t); } }; @@ -134,7 +136,8 @@ public class DOMConcurrentDataCommitCoordinator implements DOMDataCommitExecutor @Override public void onFailure(Throwable t) { - handleException(clientSubmitFuture, transaction, cohorts, cohortSize, CAN_COMMIT, t); + handleException(clientSubmitFuture, transaction, cohorts, cohortSize, PRE_COMMIT, + TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER, t); } }; @@ -163,7 +166,8 @@ public class DOMConcurrentDataCommitCoordinator implements DOMDataCommitExecutor @Override public void onFailure(Throwable t) { - handleException(clientSubmitFuture, transaction, cohorts, cohortSize, CAN_COMMIT, t); + handleException(clientSubmitFuture, transaction, cohorts, cohortSize, COMMIT, + TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER, t); } }; @@ -176,7 +180,8 @@ public class DOMConcurrentDataCommitCoordinator implements DOMDataCommitExecutor private void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture, final DOMDataWriteTransaction transaction, final Iterable cohorts, int cohortSize, - final String phase, final Throwable t) { + final String phase, final TransactionCommitFailedExceptionMapper exMapper, + final Throwable t) { if(clientSubmitFuture.isDone()) { // We must have had failures from multiple cohorts. @@ -191,8 +196,7 @@ public class DOMConcurrentDataCommitCoordinator implements DOMDataCommitExecutor e = new RuntimeException("Unexpected error occurred", t); } - final TransactionCommitFailedException clientException = - TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER.apply(e); + final TransactionCommitFailedException clientException = exMapper.apply(e); // Transaction failed - tell all cohorts to abort. diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/TransactionCommitFailedExceptionMapper.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/TransactionCommitFailedExceptionMapper.java index 799a8a09ed..3b5c353202 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/TransactionCommitFailedExceptionMapper.java +++ b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/TransactionCommitFailedExceptionMapper.java @@ -18,9 +18,9 @@ import org.opendaylight.yangtools.util.concurrent.ExceptionMapper; final class TransactionCommitFailedExceptionMapper extends ExceptionMapper { - static final TransactionCommitFailedExceptionMapper PRE_COMMIT_MAPPER = create("canCommit"); + static final TransactionCommitFailedExceptionMapper PRE_COMMIT_MAPPER = create("preCommit"); - static final TransactionCommitFailedExceptionMapper CAN_COMMIT_ERROR_MAPPER = create("preCommit"); + static final TransactionCommitFailedExceptionMapper CAN_COMMIT_ERROR_MAPPER = create("canCommit"); static final TransactionCommitFailedExceptionMapper COMMIT_ERROR_MAPPER = create("commit"); diff --git a/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPointManagerTest.java b/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPointManagerTest.java index 05c4793218..e876ccb306 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPointManagerTest.java +++ b/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPointManagerTest.java @@ -8,14 +8,14 @@ package org.opendaylight.controller.sal.dom.broker; -import static junit.framework.Assert.fail; +import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - +import com.google.common.base.Optional; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; @@ -36,8 +36,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Optional; - public class BackwardsCompatibleMountPointManagerTest { private static final Logger log = LoggerFactory.getLogger(BackwardsCompatibleMountPointManagerTest.class); @@ -106,7 +104,7 @@ public class BackwardsCompatibleMountPointManagerTest { private DOMMountPoint mockMountPoint() { final DOMMountPoint mock = mock(DOMMountPoint.class); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { return Optional.of(mock(((Class) invocation.getArguments()[0]))); diff --git a/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPointTest.java b/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPointTest.java index 91ae0c24dd..f1b7261bcb 100644 --- a/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPointTest.java +++ b/opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPointTest.java @@ -8,15 +8,14 @@ package org.opendaylight.controller.sal.dom.broker; -import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - import com.google.common.base.Optional; import com.google.common.util.concurrent.ListenableFuture; import java.util.AbstractMap; @@ -38,6 +37,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@Deprecated public class BackwardsCompatibleMountPointTest { private static final Logger log = LoggerFactory.getLogger(BackwardsCompatibleMountPointManagerTest.class); @@ -139,7 +139,7 @@ public class BackwardsCompatibleMountPointTest { private DataNormalizer mockNormalizer() throws DataNormalizationException { final DataNormalizer mock = mock(DataNormalizer.class); - doReturn(new AbstractMap.SimpleEntry>(id, normalizedNode) {}) + doReturn(new AbstractMap.SimpleEntry>(id, normalizedNode)) .when(mock).toNormalized(any(YangInstanceIdentifier.class), any(CompositeNode.class)); doReturn(compositeNode).when(mock).toLegacy(any(YangInstanceIdentifier.class), any(NormalizedNode.class)); doReturn(id).when(mock).toLegacy(any(YangInstanceIdentifier.class)); @@ -147,7 +147,7 @@ public class BackwardsCompatibleMountPointTest { } private NormalizedNode mockNormalizedNode() { - final NormalizedNode mock = mock(NormalizedNode.class); + final NormalizedNode mock = mock(NormalizedNode.class); doReturn("mockNormalizedNode").when(mock).toString(); return mock; } diff --git a/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/broker/spi/rpc/RpcRoutingStrategy.java b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/broker/spi/rpc/RpcRoutingStrategy.java index 81203c55fe..6c8f37b66b 100644 --- a/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/broker/spi/rpc/RpcRoutingStrategy.java +++ b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/broker/spi/rpc/RpcRoutingStrategy.java @@ -7,6 +7,8 @@ */ package org.opendaylight.controller.md.sal.dom.broker.spi.rpc; +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; import org.opendaylight.yangtools.concepts.Identifiable; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; @@ -14,17 +16,14 @@ import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; -import com.google.common.base.Optional; - public abstract class RpcRoutingStrategy implements Identifiable { + private static final QName CONTEXT_REFERENCE = QName.cachedReference(QName.create("urn:opendaylight:yang:extension:yang-ext", + "2013-07-09", "context-reference")); private final QName identifier; - private static final QName CONTEXT_REFERENCE = QName.create("urn:opendaylight:yang:extension:yang-ext", - "2013-07-09", "context-reference"); private RpcRoutingStrategy(final QName identifier) { - super(); - this.identifier = identifier; + this.identifier = Preconditions.checkNotNull(identifier); } /** @@ -47,7 +46,7 @@ public abstract class RpcRoutingStrategy implements Identifiable { public abstract QName getContext(); @Override - public QName getIdentifier() { + public final QName getIdentifier() { return identifier; } @@ -64,14 +63,14 @@ public abstract class RpcRoutingStrategy implements Identifiable { for (DataSchemaNode schemaNode : input.getChildNodes()) { Optional context = getRoutingContext(schemaNode); if (context.isPresent()) { - return createRoutedStrategy(rpc, context.get(), schemaNode.getQName()); + return new RoutedRpcStrategy(rpc.getQName(), context.get(), schemaNode.getQName()); } } } - return createGlobalStrategy(rpc); + return new GlobalRpcStrategy(rpc.getQName()); } - public static Optional getRoutingContext(final DataSchemaNode schemaNode) { + public static Optional getRoutingContext(final DataSchemaNode schemaNode) { for (UnknownSchemaNode extension : schemaNode.getUnknownSchemaNodes()) { if (CONTEXT_REFERENCE.equals(extension.getNodeType())) { return Optional.fromNullable(extension.getQName()); @@ -80,26 +79,14 @@ public abstract class RpcRoutingStrategy implements Identifiable { return Optional.absent(); } - private static RpcRoutingStrategy createRoutedStrategy(final RpcDefinition rpc, final QName context, final QName leafNode) { - return new RoutedRpcStrategy(rpc.getQName(), context, leafNode); - } - - - - private static RpcRoutingStrategy createGlobalStrategy(final RpcDefinition rpc) { - GlobalRpcStrategy ret = new GlobalRpcStrategy(rpc.getQName()); - return ret; - } - - private static class RoutedRpcStrategy extends RpcRoutingStrategy { - - final QName context; + private static final class RoutedRpcStrategy extends RpcRoutingStrategy { + private final QName context; private final QName leaf; private RoutedRpcStrategy(final QName identifier, final QName ctx, final QName leaf) { super(identifier); - this.context = ctx; - this.leaf = leaf; + this.context = Preconditions.checkNotNull(ctx); + this.leaf = Preconditions.checkNotNull(leaf); } @Override @@ -118,7 +105,7 @@ public abstract class RpcRoutingStrategy implements Identifiable { } } - private static class GlobalRpcStrategy extends RpcRoutingStrategy { + private static final class GlobalRpcStrategy extends RpcRoutingStrategy { public GlobalRpcStrategy(final QName identifier) { super(identifier); @@ -131,12 +118,12 @@ public abstract class RpcRoutingStrategy implements Identifiable { @Override public QName getContext() { - throw new UnsupportedOperationException("Not routed strategy does not have context."); + throw new UnsupportedOperationException("Non-routed strategy does not have a context"); } @Override public QName getLeaf() { - throw new UnsupportedOperationException("Not routed strategy does not have context."); + throw new UnsupportedOperationException("Non-routed strategy does not have a context"); } } } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataBroker.java b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataBroker.java new file mode 100644 index 0000000000..e42cf10f7e --- /dev/null +++ b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataBroker.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.dom.spi; + +import com.google.common.collect.ForwardingObject; +import javax.annotation.Nonnull; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener; +import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; +import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain; +import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; + +/** + * Utility {@link DOMDataBroker} implementation which forwards all interface + * method invocation to a delegate instance. + */ +public abstract class ForwardingDOMDataBroker extends ForwardingObject implements DOMDataBroker { + @Override + protected abstract @Nonnull DOMDataBroker delegate(); + + @Override + public ListenerRegistration registerDataChangeListener(final LogicalDatastoreType store, + final YangInstanceIdentifier path, final DOMDataChangeListener listener, + final DataChangeScope triggeringScope) { + return delegate().registerDataChangeListener(store, path, listener, triggeringScope); + } + + @Override + public DOMDataReadOnlyTransaction newReadOnlyTransaction() { + return delegate().newReadOnlyTransaction(); + } + + @Override + public DOMDataReadWriteTransaction newReadWriteTransaction() { + return delegate().newReadWriteTransaction(); + } + + @Override + public DOMDataWriteTransaction newWriteOnlyTransaction() { + return delegate().newWriteOnlyTransaction(); + } + + @Override + public DOMTransactionChain createTransactionChain(final TransactionChainListener listener) { + return delegate().createTransactionChain(listener); + } +} diff --git a/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataReadOnlyTransaction.java b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataReadOnlyTransaction.java new file mode 100644 index 0000000000..dcec6c3fab --- /dev/null +++ b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataReadOnlyTransaction.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.dom.spi; + +import com.google.common.base.Optional; +import com.google.common.collect.ForwardingObject; +import com.google.common.util.concurrent.CheckedFuture; +import javax.annotation.Nonnull; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; + +/** + * Utility {@link DOMDataReadOnlyTransaction} implementation which forwards all interface + * method invocation to a delegate instance. + */ +public abstract class ForwardingDOMDataReadOnlyTransaction extends ForwardingObject implements DOMDataReadOnlyTransaction { + @Override + protected abstract @Nonnull DOMDataReadOnlyTransaction delegate(); + + @Override + public CheckedFuture>, ReadFailedException> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) { + return delegate().read(store, path); + } + + @Override + public CheckedFuture exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) { + return delegate().exists(store, path); + } + + @Override + public Object getIdentifier() { + return delegate().getIdentifier(); + } + + @Override + public void close() { + delegate().close(); + } +} diff --git a/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataReadWriteTransaction.java b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataReadWriteTransaction.java new file mode 100644 index 0000000000..923bef76f3 --- /dev/null +++ b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataReadWriteTransaction.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.dom.spi; + +import com.google.common.base.Optional; +import com.google.common.collect.ForwardingObject; +import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.ListenableFuture; +import javax.annotation.Nonnull; +import org.opendaylight.controller.md.sal.common.api.TransactionStatus; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; +import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; + +/** + * Utility {@link DOMDataReadWriteTransaction} implementation which forwards all interface + * method invocation to a delegate instance. + */ +public abstract class ForwardingDOMDataReadWriteTransaction extends ForwardingObject implements DOMDataReadWriteTransaction { + @Override + protected abstract @Nonnull DOMDataReadWriteTransaction delegate(); + + @Override + public CheckedFuture>, ReadFailedException> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) { + return delegate().read(store, path); + } + + @Override + public CheckedFuture exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) { + return delegate().exists(store, path); + } + + @Override + public Object getIdentifier() { + return delegate().getIdentifier(); + } + + @Override + public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) { + delegate().put(store, path, data); + } + + @Override + public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) { + delegate().merge(store, path, data); + } + + @Override + public boolean cancel() { + return delegate().cancel(); + } + + @Override + public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) { + delegate().delete(store, path); + } + + @Override + public CheckedFuture submit() { + return delegate().submit(); + } + + @Override + @Deprecated + public ListenableFuture> commit() { + return delegate().commit(); + } +} diff --git a/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataWriteTransaction.java b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataWriteTransaction.java new file mode 100644 index 0000000000..2afb4786ce --- /dev/null +++ b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMDataWriteTransaction.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.dom.spi; + +import com.google.common.collect.ForwardingObject; +import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.ListenableFuture; +import javax.annotation.Nonnull; +import org.opendaylight.controller.md.sal.common.api.TransactionStatus; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; +import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; + +/** + * Utility {@link DOMDataWriteTransaction} implementation which forwards all interface + * method invocation to a delegate instance. + */ +public abstract class ForwardingDOMDataWriteTransaction extends ForwardingObject implements DOMDataWriteTransaction { + @Override + protected abstract @Nonnull DOMDataWriteTransaction delegate(); + + @Override + public Object getIdentifier() { + return delegate().getIdentifier(); + } + + @Override + public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) { + delegate().put(store, path, data); + } + + @Override + public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) { + delegate().merge(store, path, data); + } + + @Override + public boolean cancel() { + return delegate().cancel(); + } + + @Override + public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) { + delegate().delete(store, path); + } + + @Override + public CheckedFuture submit() { + return delegate().submit(); + } + + @Override + @Deprecated + public ListenableFuture> commit() { + return delegate().commit(); + } +} diff --git a/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMTransactionChain.java b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMTransactionChain.java new file mode 100644 index 0000000000..e709e6713a --- /dev/null +++ b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/spi/ForwardingDOMTransactionChain.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.md.sal.dom.spi; + +import com.google.common.collect.ForwardingObject; +import javax.annotation.Nonnull; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; +import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain; + +/** + * Utility {@link DOMTransactionChain} implementation which forwards all interface + * method invocation to a delegate instance. + */ +public abstract class ForwardingDOMTransactionChain extends ForwardingObject implements DOMTransactionChain { + @Override + protected abstract @Nonnull DOMTransactionChain delegate(); + + @Override + public void close() { + delegate().close(); + } + + @Override + public DOMDataReadOnlyTransaction newReadOnlyTransaction() { + return delegate().newReadOnlyTransaction(); + } + + @Override + public DOMDataReadWriteTransaction newReadWriteTransaction() { + return delegate().newReadWriteTransaction(); + } + + @Override + public DOMDataWriteTransaction newWriteOnlyTransaction() { + return delegate().newWriteOnlyTransaction(); + } +} diff --git a/opendaylight/md-sal/sal-dom-xsql-config/pom.xml b/opendaylight/md-sal/sal-dom-xsql-config/pom.xml index e8919d0ee1..d2d864cd4f 100644 --- a/opendaylight/md-sal/sal-dom-xsql-config/pom.xml +++ b/opendaylight/md-sal/sal-dom-xsql-config/pom.xml @@ -15,7 +15,6 @@ 1.2.0-SNAPSHOT sal-dom-xsql-config - org.opendaylight.controller Configuration files for md-sal jar diff --git a/opendaylight/md-sal/sal-dom-xsql/pom.xml b/opendaylight/md-sal/sal-dom-xsql/pom.xml index f5898a2bb9..c7fd20248d 100644 --- a/opendaylight/md-sal/sal-dom-xsql/pom.xml +++ b/opendaylight/md-sal/sal-dom-xsql/pom.xml @@ -35,7 +35,6 @@ org.opendaylight.controller yang-jmx-generator-plugin - ${config.version} org.opendaylight.yangtools diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLAdapter.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLAdapter.java index ecea744d14..ad4bd46d71 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLAdapter.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLAdapter.java @@ -349,7 +349,7 @@ public class XSQLAdapter extends Thread implements SchemaContextListener { JDBCResultSet rs = new JDBCResultSet(sql); try { int count = 0; - jdbcServer.execute(rs, this); + JDBCServer.execute(rs, this); boolean isFirst = true; int loc = rs.getFields().size() - 1; int totalWidth = 0; diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrint.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrint.java index 7b51d03a97..867c7a47b5 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrint.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrint.java @@ -163,23 +163,23 @@ public class XSQLBluePrint implements DatabaseMetaData, Serializable { return cacheLoadedSuccessfuly; } - private static Map> superClassMap = new HashMap>(); + private static Map, Set>> superClassMap = new HashMap<>(); - public static Set getInheritance(Class myObjectClass, - Class returnType) { + public static Set> getInheritance(Class myObjectClass, + Class returnType) { if (returnType != null && myObjectClass.equals(returnType)) { - return new HashSet(); + return new HashSet<>(); } - Set result = superClassMap.get(myObjectClass); + Set> result = superClassMap.get(myObjectClass); if (result != null) { return result; } - result = new HashSet(); + result = new HashSet<>(); superClassMap.put(myObjectClass, result); if (returnType != null) { if (!returnType.equals(myObjectClass)) { - Class mySuperClass = myObjectClass.getSuperclass(); + Class mySuperClass = myObjectClass.getSuperclass(); while (mySuperClass != null) { result.add(mySuperClass); mySuperClass = mySuperClass.getSuperclass(); @@ -190,11 +190,11 @@ public class XSQLBluePrint implements DatabaseMetaData, Serializable { return result; } - public static Set collectInterfaces(Class cls) { - Set result = new HashSet(); - Class myInterfaces[] = cls.getInterfaces(); + public static Set> collectInterfaces(Class cls) { + Set> result = new HashSet<>(); + Class myInterfaces[] = cls.getInterfaces(); if (myInterfaces != null) { - for (Class in : myInterfaces) { + for (Class in : myInterfaces) { result.add(in); result.addAll(collectInterfaces(in)); } @@ -213,20 +213,20 @@ public class XSQLBluePrint implements DatabaseMetaData, Serializable { map.put(blNode.getBluePrintNodeName(), blNode); } - public Class getGenericType(ParameterizedType type) { + public Class getGenericType(ParameterizedType type) { Type[] typeArguments = type.getActualTypeArguments(); for (Type typeArgument : typeArguments) { if (typeArgument instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) typeArgument; - return (Class) pType.getRawType(); + return (Class) pType.getRawType(); } else if (typeArgument instanceof Class) { - return (Class) typeArgument; + return (Class) typeArgument; } } return null; } - public Class getMethodReturnTypeFromGeneric(Method m) { + public Class getMethodReturnTypeFromGeneric(Method m) { Type rType = m.getGenericReturnType(); if (rType instanceof ParameterizedType) { return getGenericType((ParameterizedType) rType); diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrintNode.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrintNode.java index 8d905f2081..8e9ed3a26b 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrintNode.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrintNode.java @@ -85,7 +85,7 @@ public class XSQLBluePrintNode implements Serializable { this.children.add(ch); } - public boolean isModelChild(Class p) { + public boolean isModelChild(Class p) { if (this.relations.size() == 0) { return false; } @@ -227,7 +227,7 @@ public class XSQLBluePrintNode implements Serializable { return "Unknown"; } - public Class getInterface() { + public Class getInterface() { return this.myInterface; } diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrintRelation.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrintRelation.java index 1cb3aa5559..38a96dc457 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrintRelation.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLBluePrintRelation.java @@ -80,20 +80,20 @@ public class XSQLBluePrintRelation implements Serializable { } } - public List execute(Object o) { - List result = new LinkedList(); + public List execute(Object o) { + List result = new LinkedList<>(); if (o == null) { return null; } if (Set.class.isAssignableFrom(o.getClass())) { - Set lst = (Set) o; + Set lst = (Set) o; for (Object oo : lst) { addToResult(result, execute(oo)); } return result; } else if (List.class.isAssignableFrom(o.getClass())) { - List lst = (List) o; + List lst = (List) o; for (Object oo : lst) { addToResult(result, execute(oo)); } @@ -111,17 +111,17 @@ public class XSQLBluePrintRelation implements Serializable { return result; } - public static void addToResult(List result, Object o) { + private static void addToResult(List result, Object o) { if (o == null) { return; } if (Set.class.isAssignableFrom(o.getClass())) { - Set lst = (Set) o; + Set lst = (Set) o; for (Object oo : lst) { result.add(oo); } } else if (List.class.isAssignableFrom(o.getClass())) { - List lst = (List) o; + List lst = (List) o; for (Object oo : lst) { result.add(oo); } diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLColumn.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLColumn.java index 4c6cca7fa6..c1404d58e6 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLColumn.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLColumn.java @@ -2,11 +2,13 @@ package org.opendaylight.controller.md.sal.dom.xsql; import java.io.Serializable; -public class XSQLColumn implements Serializable, Comparable { +public class XSQLColumn implements Serializable, Comparable { + private static final long serialVersionUID = 4854919735031714751L; + private String name = null; private String tableName = null; private int charWidth = -1; - private Class type = null; + private Class type = null; private transient Object bluePrintNode = null; private String origName = null; private String origTableName = null; diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLODLUtils.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLODLUtils.java index 6a27230664..17b8ae5f29 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLODLUtils.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/XSQLODLUtils.java @@ -32,7 +32,7 @@ public class XSQLODLUtils { types.put(Status.class, Status.class); } - public static boolean isColumnType(Class cls) { + public static boolean isColumnType(Class cls) { return types.containsKey(cls); } @@ -229,7 +229,7 @@ public class XSQLODLUtils { return "NULL"; } - public static Class getTypeForODLColumn(Object odlNode){ + public static Class getTypeForODLColumn(Object odlNode){ Object type = get(odlNode,"type"); if(type instanceof Uint32 || type instanceof Uint64){ return long.class; diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCCommand.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCCommand.java index 019711157c..ba0626fdfe 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCCommand.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCCommand.java @@ -6,6 +6,8 @@ import java.util.Map; import org.opendaylight.controller.md.sal.dom.xsql.XSQLBluePrint; public class JDBCCommand implements Serializable { + private static final long serialVersionUID = 1L; + public int type = 0; public static final int TYPE_EXECUTE_QUERY = 1; public static final int TYPE_QUERY_REPLY = 2; diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCResultSet.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCResultSet.java index 021f6ee19b..5abe8a3165 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCResultSet.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCResultSet.java @@ -127,7 +127,7 @@ public class JDBCResultSet implements Serializable, ResultSet, return 1; } - public int isObjectFitCriteria(Object element, Class cls) { + public int isObjectFitCriteria(Object element, Class cls) { Map> tblCriteria = criteria.get(cls .getName()); if (tblCriteria == null) { @@ -207,7 +207,7 @@ public class JDBCResultSet implements Serializable, ResultSet, } } - public void addRecord(ArrayList hierarchy) { + public void addRecord(ArrayList hierarchy) { Map rec = new HashMap(); for (int i = hierarchy.size() - 1; i >= 0; i--) { Object element = hierarchy.get(i); diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCServer.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCServer.java index 5be701f82e..5979771d28 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCServer.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCServer.java @@ -121,7 +121,7 @@ public class JDBCServer extends Thread { while (entry.getValue().next()) { Map rec = entry.getValue().getCurrent(); Map newRec = new HashMap(); - for (Iterator iter = rec.entrySet().iterator(); iter.hasNext();) { + for (Iterator iter = rec.entrySet().iterator(); iter.hasNext();) { Map.Entry e = (Map.Entry) iter.next(); String key = (String) e.getKey(); Object value = e.getValue(); diff --git a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCStatement.java b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCStatement.java index b71b015351..27e2196970 100644 --- a/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCStatement.java +++ b/opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/controller/md/sal/dom/xsql/jdbc/JDBCStatement.java @@ -89,7 +89,7 @@ public class JDBCStatement implements PreparedStatement { return true; } - public void addRecord(ArrayList hierarchy) { + public void addRecord(ArrayList hierarchy) { rs.addRecord(hierarchy); } diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java index bca47af5c0..97e294016d 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java @@ -9,8 +9,9 @@ package org.opendaylight.controller.config.yang.md.sal.connector.netconf; import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkCondition; import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkNotNull; - import com.google.common.base.Optional; +import io.netty.util.concurrent.EventExecutor; +import java.math.BigDecimal; import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.ExecutorService; @@ -120,13 +121,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co final NetconfClientDispatcher dispatcher = getClientDispatcherDependency(); listener.initializeRemoteConnection(dispatcher, clientConfig); - return new AutoCloseable() { - @Override - public void close() throws Exception { - listener.close(); - salFacade.close(); - } - }; + return new MyAutoCloseable(listener, salFacade); } private Optional getUserCapabilities() { @@ -155,9 +150,12 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) { final InetSocketAddress socketAddress = getSocketAddress(); - final ReconnectStrategy strategy = getReconnectStrategy(); final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis(); + final ReconnectStrategyFactory sf = new MyReconnectStrategyFactory( + getEventExecutorDependency(), getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor()); + final ReconnectStrategy strategy = sf.createReconnectStrategy(); + return NetconfReconnectingClientConfigurationBuilder.create() .withAddress(socketAddress) .withConnectionTimeoutMillis(clientConnectionTimeoutMillis) @@ -167,30 +165,54 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co .withProtocol(getTcpOnly() ? NetconfClientConfiguration.NetconfClientProtocol.TCP : NetconfClientConfiguration.NetconfClientProtocol.SSH) - .withConnectStrategyFactory(new ReconnectStrategyFactory() { - @Override - public ReconnectStrategy createReconnectStrategy() { - return getReconnectStrategy(); - } - }) + .withConnectStrategyFactory(sf) .build(); } - private ReconnectStrategy getReconnectStrategy() { - final Long connectionAttempts; - if (getMaxConnectionAttempts() != null && getMaxConnectionAttempts() > 0) { - connectionAttempts = getMaxConnectionAttempts(); - } else { - logger.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this); - connectionAttempts = null; + private static final class MyAutoCloseable implements AutoCloseable { + private final RemoteDeviceHandler salFacade; + private final NetconfDeviceCommunicator listener; + + public MyAutoCloseable(final NetconfDeviceCommunicator listener, + final RemoteDeviceHandler salFacade) { + this.listener = listener; + this.salFacade = salFacade; } - final double sleepFactor = getSleepFactor().doubleValue(); - final int minSleep = getBetweenAttemptsTimeoutMillis(); - final Long maxSleep = null; - final Long deadline = null; - return new TimedReconnectStrategy(getEventExecutorDependency(), getBetweenAttemptsTimeoutMillis(), - minSleep, sleepFactor, maxSleep, connectionAttempts, deadline); + @Override + public void close() { + listener.close(); + salFacade.close(); + } + } + + private static final class MyReconnectStrategyFactory implements ReconnectStrategyFactory { + private final Long connectionAttempts; + private final EventExecutor executor; + private final double sleepFactor; + private final int minSleep; + + MyReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) { + if (maxConnectionAttempts != null && maxConnectionAttempts > 0) { + connectionAttempts = maxConnectionAttempts; + } else { + logger.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this); + connectionAttempts = null; + } + + this.sleepFactor = sleepFactor.doubleValue(); + this.executor = executor; + this.minSleep = minSleep; + } + + @Override + public ReconnectStrategy createReconnectStrategy() { + final Long maxSleep = null; + final Long deadline = null; + + return new TimedReconnectStrategy(executor, minSleep, + minSleep, sleepFactor, maxSleep, connectionAttempts, deadline); + } } private InetSocketAddress getSocketAddress() { diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/NetconfDevice.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/NetconfDevice.java index cc9eb5a851..31779a7817 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/NetconfDevice.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/NetconfDevice.java @@ -134,6 +134,14 @@ public final class NetconfDevice implements RemoteDevice sourceRegistration : sourceRegistrations) { sourceRegistration.close(); } + resetMessageTransformer(); } @Override diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java index 5e61dfb028..2971865a70 100644 --- a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java +++ b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java @@ -8,12 +8,9 @@ package org.opendaylight.controller.sal.connect.netconf.schema.mapping; import com.google.common.base.Optional; - import java.util.List; import java.util.Set; - import javax.activation.UnsupportedDataTypeException; - import org.opendaylight.controller.netconf.api.NetconfMessage; import org.opendaylight.controller.sal.connect.api.MessageTransformer; import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil; @@ -29,6 +26,7 @@ import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils; import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; +import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -69,19 +67,24 @@ public class NetconfMessageTransformer implements MessageTransformer schemaForRpc = NetconfMessageTransformUtil.findSchemaForRpc(rpc, schemaContext.get()); + if(schemaForRpc.isPresent()) { + final DataNodeContainer schemaForGetConfig = NetconfMessageTransformUtil.createSchemaForRpc(schemaForRpc.get()); + w3cPayload = XmlDocumentUtils.toDocument(rpcPayload, schemaContext.get(), schemaForGetConfig, codecProvider); + } else { + w3cPayload = toRpcRequestWithoutSchema(rpcPayload, codecProvider); + } } } else { - w3cPayload = XmlDocumentUtils.toDocument(rpcPayload, codecProvider); + w3cPayload = toRpcRequestWithoutSchema(rpcPayload, codecProvider); } } catch (final UnsupportedDataTypeException e) { throw new IllegalArgumentException("Unable to create message", e); @@ -90,6 +93,10 @@ public class NetconfMessageTransformer implements MessageTransformer toRpcResult(final NetconfMessage message, final QName rpc) { if(schemaContext.isPresent()) { @@ -124,6 +131,6 @@ public class NetconfMessageTransformer implements MessageTransformer toNode(final YangInstanceIdentifier.NodeIdentifierWithPredicates argument, final Node node) { final List> list = new ArrayList<>(); for (final Map.Entry arg : argument.getKeyValues().entrySet()) { - list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue())); + list.add(new SimpleNodeTOImpl<>(arg.getKey(), null, arg.getValue())); } if (node != null) { list.add(node); @@ -325,6 +327,20 @@ public class NetconfMessageTransformUtil { return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.newHashSet(editConfigProxy)); } + + public static Optional findSchemaForRpc(final QName rpcName, final SchemaContext schemaContext) { + Preconditions.checkNotNull(rpcName); + Preconditions.checkNotNull(schemaContext); + + for (final RpcDefinition rpcDefinition : schemaContext.getOperations()) { + if(rpcDefinition.getQName().equals(rpcName)) { + return Optional.of(rpcDefinition); + } + } + + return Optional.absent(); + } + /** * Creates artificial schema node for schema defined rpc. This artificial schema looks like: *
      @@ -340,13 +356,9 @@ public class NetconfMessageTransformUtil {
            * This makes the translation of schema defined rpc request
            * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
            */
      -    public static DataNodeContainer createSchemaForRpc(final QName rpcName, final SchemaContext schemaContext) {
      -        Preconditions.checkNotNull(rpcName);
      -        Preconditions.checkNotNull(schemaContext);
      -
      -        final NodeContainerProxy rpcBodyProxy = new NodeContainerProxy(rpcName, schemaContext.getChildNodes());
      +    public static DataNodeContainer createSchemaForRpc(final RpcDefinition rpcDefinition) {
      +        final NodeContainerProxy rpcBodyProxy = new NodeContainerProxy(rpcDefinition.getQName(), rpcDefinition.getInput().getChildNodes());
               return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.newHashSet(rpcBodyProxy));
      -
           }
       
           public static CompositeNodeTOImpl wrap(final QName name, final Node node) {
      diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfDeviceTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfDeviceTest.java
      index 218ec0be8d..80ac4d7376 100644
      --- a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfDeviceTest.java
      +++ b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfDeviceTest.java
      @@ -17,7 +17,6 @@ import static org.mockito.Mockito.mock;
       import static org.mockito.Mockito.timeout;
       import static org.mockito.Mockito.times;
       import static org.mockito.Mockito.verify;
      -
       import com.google.common.base.Optional;
       import com.google.common.collect.HashMultimap;
       import com.google.common.collect.Lists;
      @@ -134,7 +133,7 @@ public class NetconfDeviceTest {
       
               // Make fallback attempt to fail due to empty resolved sources
               final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
      -        doAnswer(new Answer() {
      +        doAnswer(new Answer() {
                   @Override
                   public Object answer(final InvocationOnMock invocation) throws Throwable {
                       if(((Collection) invocation.getArguments()[0]).size() == 2) {
      @@ -158,7 +157,7 @@ public class NetconfDeviceTest {
       
           private SchemaSourceRegistry getSchemaRegistry() {
               final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
      -        final SchemaSourceRegistration mockReg = mock(SchemaSourceRegistration.class);
      +        final SchemaSourceRegistration mockReg = mock(SchemaSourceRegistration.class);
               doNothing().when(mockReg).close();
               doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
               return mock;
      @@ -218,7 +217,7 @@ public class NetconfDeviceTest {
               device.onRemoteSessionUp(sessionCaps, listener);
       
               verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
      -        verify(messageTransformer, timeout(5000).times(2)).onGlobalContextUpdated(any(SchemaContext.class));
      +        verify(messageTransformer, timeout(5000).times(3)).onGlobalContextUpdated(any(SchemaContext.class));
               verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionCapabilities.class), any(RpcImplementation.class));
           }
       
      diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfStateSchemasTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfStateSchemasTest.java
      index 3f9c8caa0e..ccae5d4be8 100644
      --- a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfStateSchemasTest.java
      +++ b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfStateSchemasTest.java
      @@ -2,7 +2,7 @@ package org.opendaylight.controller.sal.connect.netconf;
       
       import static org.junit.Assert.assertEquals;
       import static org.junit.Assert.assertThat;
      -import static org.junit.matchers.JUnitMatchers.hasItem;
      +import static org.hamcrest.CoreMatchers.hasItem;
       
       import java.util.Set;
       import org.junit.Test;
      diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToNotificationTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToNotificationTest.java
      index 127b0cbfcd..5d19188b12 100644
      --- a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToNotificationTest.java
      +++ b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToNotificationTest.java
      @@ -1,14 +1,12 @@
       package org.opendaylight.controller.sal.connect.netconf;
       
      -import static junit.framework.Assert.assertEquals;
      -import static junit.framework.Assert.assertNotNull;
      -import static junit.framework.Assert.assertTrue;
      -
      +import static org.junit.Assert.assertEquals;
      +import static org.junit.Assert.assertNotNull;
      +import static org.junit.Assert.assertTrue;
       import java.io.InputStream;
       import java.util.Collections;
       import java.util.List;
       import java.util.Set;
      -
       import javax.xml.parsers.DocumentBuilderFactory;
       import org.junit.Before;
       import org.junit.Test;
      diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToRpcRequestTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToRpcRequestTest.java
      index e744e11bc9..3425739afd 100644
      --- a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToRpcRequestTest.java
      +++ b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToRpcRequestTest.java
      @@ -1,21 +1,23 @@
       package org.opendaylight.controller.sal.connect.netconf;
       
      -import static junit.framework.Assert.assertEquals;
      -import static junit.framework.Assert.assertNotNull;
      -import static junit.framework.Assert.assertTrue;
      +import static org.junit.Assert.assertEquals;
      +import static org.junit.Assert.assertNotNull;
      +import static org.junit.Assert.assertTrue;
       
       import java.io.InputStream;
       import java.util.Collections;
       import java.util.List;
       import java.util.Set;
      -
       import org.junit.BeforeClass;
       import org.junit.Test;
       import org.opendaylight.controller.netconf.api.NetconfMessage;
      +import org.opendaylight.controller.netconf.util.xml.XmlUtil;
       import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
       import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
       import org.opendaylight.yangtools.yang.common.QName;
      +import org.opendaylight.yangtools.yang.common.RpcResult;
       import org.opendaylight.yangtools.yang.data.api.CompositeNode;
      +import org.opendaylight.yangtools.yang.data.api.Node;
       import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
       import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
       import org.opendaylight.yangtools.yang.model.api.Module;
      @@ -251,39 +253,21 @@ public class NetconfToRpcRequestTest {
       
               final org.w3c.dom.Node streamName = subscribeName.getFirstChild();
               assertEquals(streamName.getLocalName(), "stream-name");
      +
           }
       
           @Test
      -    public void testNoSchemaContextToRpcRequest() throws Exception {
      -        final String exampleNamespace = "http://example.net/me/my-own/1.0";
      -        final String exampleRevision = "2014-07-22";
      -        final QName myOwnMethodRpcQName = QName.create(exampleNamespace, exampleRevision, "my-own-method");
      -
      -        final CompositeNodeBuilder rootBuilder = ImmutableCompositeNode.builder();
      -        rootBuilder.setQName(myOwnMethodRpcQName);
      -
      -        final CompositeNodeBuilder inputBuilder = ImmutableCompositeNode.builder();
      -        inputBuilder.setQName(QName.create(exampleNamespace, exampleRevision, "input"));
      -        inputBuilder.addLeaf(QName.create(exampleNamespace, exampleRevision, "my-first-parameter"), "14");
      -        inputBuilder.addLeaf(QName.create(exampleNamespace, exampleRevision, "another-parameter"), "fred");
      -
      -        rootBuilder.add(inputBuilder.toInstance());
      -        final ImmutableCompositeNode root = rootBuilder.toInstance();
      -
      -        final NetconfMessage message = messageTransformer.toRpcRequest(myOwnMethodRpcQName, root);
      -        assertNotNull(message);
      -
      -        final Document xmlDoc = message.getDocument();
      -        final org.w3c.dom.Node rpcChild = xmlDoc.getFirstChild();
      -        assertEquals(rpcChild.getLocalName(), "rpc");
      -
      -        final org.w3c.dom.Node myOwnMethodNode = rpcChild.getFirstChild();
      -        assertEquals(myOwnMethodNode.getLocalName(), "my-own-method");
      -
      -        final org.w3c.dom.Node firstParamNode = myOwnMethodNode.getFirstChild();
      -        assertEquals(firstParamNode.getLocalName(), "my-first-parameter");
      -
      -        final org.w3c.dom.Node secParamNode = firstParamNode.getNextSibling();
      -        assertEquals(secParamNode.getLocalName(), "another-parameter");
      +    public void testRpcResponse() throws Exception {
      +        final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
      +                "\n" +
      +                "" +
      +                "module schema" +
      +                "\n" +
      +                "\n"
      +        ));
      +        final RpcResult compositeNodeRpcResult = messageTransformer.toRpcResult(response, SUBSCRIBE_RPC_NAME);
      +        final Node dataNode = compositeNodeRpcResult.getResult().getValue().get(0);
      +        assertEquals("module schema", dataNode.getValue());
           }
      +
       }
      diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfSessionCapabilitiesTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfSessionCapabilitiesTest.java
      index 80bb08f5af..ae7d9c28ac 100644
      --- a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfSessionCapabilitiesTest.java
      +++ b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfSessionCapabilitiesTest.java
      @@ -1,12 +1,12 @@
       package org.opendaylight.controller.sal.connect.netconf.listener;
       
      +import static org.hamcrest.CoreMatchers.hasItem;
       import static org.junit.Assert.assertEquals;
       import static org.junit.Assert.assertThat;
       
       import com.google.common.collect.Lists;
       import java.util.List;
       import org.junit.Test;
      -import org.junit.matchers.JUnitMatchers;
       import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
       import org.opendaylight.yangtools.yang.common.QName;
       
      @@ -35,12 +35,12 @@ public class NetconfSessionCapabilitiesTest {
               final NetconfSessionCapabilities merged = sessionCaps1.replaceModuleCaps(sessionCaps2);
               assertCaps(merged, 2, 2 + 1 /*Preserved monitoring*/);
               for (final QName qName : sessionCaps2.getModuleBasedCaps()) {
      -            assertThat(merged.getModuleBasedCaps(), JUnitMatchers.hasItem(qName));
      +            assertThat(merged.getModuleBasedCaps(), hasItem(qName));
               }
      -        assertThat(merged.getModuleBasedCaps(), JUnitMatchers.hasItem(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING));
      +        assertThat(merged.getModuleBasedCaps(), hasItem(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING));
       
      -        assertThat(merged.getNonModuleCaps(), JUnitMatchers.hasItem("urn:ietf:params:netconf:base:1.0"));
      -        assertThat(merged.getNonModuleCaps(), JUnitMatchers.hasItem("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
      +        assertThat(merged.getNonModuleCaps(), hasItem("urn:ietf:params:netconf:base:1.0"));
      +        assertThat(merged.getNonModuleCaps(), hasItem("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
           }
       
           @Test
      diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/sal/tx/NetconfDeviceWriteOnlyTxTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/sal/tx/NetconfDeviceWriteOnlyTxTest.java
      index a65e426d59..0607e4b6da 100644
      --- a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/sal/tx/NetconfDeviceWriteOnlyTxTest.java
      +++ b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/sal/tx/NetconfDeviceWriteOnlyTxTest.java
      @@ -1,6 +1,6 @@
       package org.opendaylight.controller.sal.connect.netconf.sal.tx;
       
      -import static junit.framework.Assert.fail;
      +import static org.junit.Assert.fail;
       import static org.mockito.Matchers.any;
       import static org.mockito.Matchers.eq;
       import static org.mockito.Mockito.doReturn;
      diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformerTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformerTest.java
      new file mode 100644
      index 0000000000..5a2c97c549
      --- /dev/null
      +++ b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformerTest.java
      @@ -0,0 +1,72 @@
      +/*
      + * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
      + *
      + * This program and the accompanying materials are made available under the
      + * terms of the Eclipse Public License v1.0 which accompanies this distribution,
      + * and is available at http://www.eclipse.org/legal/epl-v10.html.
      + */
      +
      +package org.opendaylight.controller.sal.connect.netconf.schema.mapping;
      +
      +import static org.junit.Assert.assertEquals;
      +import static org.junit.Assert.assertNotNull;
      +import static org.junit.Assert.assertThat;
      +import static org.junit.Assert.assertTrue;
      +
      +import java.io.InputStream;
      +import java.util.Collections;
      +import java.util.List;
      +import java.util.Set;
      +import org.hamcrest.CoreMatchers;
      +import org.junit.Test;
      +import org.opendaylight.controller.netconf.api.NetconfMessage;
      +import org.opendaylight.controller.netconf.util.xml.XmlUtil;
      +import org.opendaylight.controller.sal.connect.netconf.NetconfToRpcRequestTest;
      +import org.opendaylight.yangtools.yang.common.QName;
      +import org.opendaylight.yangtools.yang.common.RpcResult;
      +import org.opendaylight.yangtools.yang.data.api.CompositeNode;
      +import org.opendaylight.yangtools.yang.data.api.Node;
      +import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
      +import org.opendaylight.yangtools.yang.model.api.Module;
      +import org.opendaylight.yangtools.yang.model.api.SchemaContext;
      +import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
      +
      +public class NetconfMessageTransformerTest {
      +
      +    private static final QName COMMIT_Q_NAME = QName.create("namespace", "2012-12-12", "commit");
      +
      +    @Test
      +    public void testToRpcRequestNoSchemaForRequest() throws Exception {
      +        final NetconfMessageTransformer netconfMessageTransformer = getTransformer();
      +        final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(COMMIT_Q_NAME,
      +                NodeFactory.createImmutableCompositeNode(COMMIT_Q_NAME, null, Collections.>emptyList()));
      +        assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString(""
      +        ));
      +        final RpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, COMMIT_Q_NAME);
      +        assertTrue(compositeNodeRpcResult.isSuccessful());
      +        assertEquals("ok", compositeNodeRpcResult.getResult().getValue().get(0).getKey().getLocalName());
      +    }
      +
      +    public SchemaContext getSchema() {
      +        final List modelsToParse = Collections
      +                .singletonList(NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
      +        final YangParserImpl parser = new YangParserImpl();
      +        final Set configModules = parser.parseYangModelsFromStreams(modelsToParse);
      +        final SchemaContext cfgCtx = parser.resolveSchemaContext(configModules);
      +        assertNotNull(cfgCtx);
      +        return cfgCtx;
      +    }
      +}
      diff --git a/opendaylight/md-sal/sal-remoterpc-connector/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/pom.xml
      index d16f67209f..ec5bb215bf 100644
      --- a/opendaylight/md-sal/sal-remoterpc-connector/pom.xml
      +++ b/opendaylight/md-sal/sal-remoterpc-connector/pom.xml
      @@ -136,7 +136,6 @@
             
             org.slf4j
             slf4j-simple
      -      ${slf4j.version}
             test
           
             
      diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java
      index 4ae9c2e4d0..a840712999 100644
      --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java
      +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java
      @@ -65,6 +65,7 @@ public class RpcManager extends AbstractUntypedActor {
                                   final Broker.ProviderSession brokerSession,
                                   final RpcProvisionRegistry rpcProvisionRegistry) {
           return Props.create(new Creator() {
      +      private static final long serialVersionUID = 1L;
             @Override
             public RpcManager create() throws Exception {
               return new RpcManager(schemaContext, brokerSession, rpcProvisionRegistry);
      diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/ExecuteRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/ExecuteRpc.java
      index 522dd44f5b..4bb5258b40 100644
      --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/ExecuteRpc.java
      +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/ExecuteRpc.java
      @@ -14,6 +14,7 @@ import org.opendaylight.yangtools.yang.common.QName;
       import java.io.Serializable;
       
       public class ExecuteRpc implements Serializable {
      +  private static final long serialVersionUID = 1L;
       
         private final String inputCompositeNode;
         private final QName rpc;
      diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/InvokeRpc.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/InvokeRpc.java
      index 59d09fc41b..652569b7ba 100644
      --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/InvokeRpc.java
      +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/InvokeRpc.java
      @@ -15,6 +15,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
       import java.io.Serializable;
       
       public class InvokeRpc implements Serializable {
      +  private static final long serialVersionUID = 1L;
       
         private final QName rpc;
         private final YangInstanceIdentifier identifier;
      diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RpcResponse.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RpcResponse.java
      index 17766f15b9..387cb90112 100644
      --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RpcResponse.java
      +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/messages/RpcResponse.java
      @@ -7,11 +7,10 @@
        */
       package org.opendaylight.controller.remote.rpc.messages;
       
      -
      -
       import java.io.Serializable;
       
       public class RpcResponse implements Serializable {
      +  private static final long serialVersionUID = 1L;
         private final String resultCompositeNode;
       
         public RpcResponse(final String resultCompositeNode) {
      diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RoutingTable.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RoutingTable.java
      index d21d05d7fe..fe8c463d2e 100644
      --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RoutingTable.java
      +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RoutingTable.java
      @@ -18,6 +18,7 @@ import java.util.HashMap;
       import java.util.Map;
       
       public class RoutingTable implements Copier, Serializable {
      +    private static final long serialVersionUID = 1L;
       
           private Map, Long> table = new HashMap<>();
           private ActorRef router;
      diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/BucketImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/BucketImpl.java
      index 4dac456dc4..01c77f1f08 100644
      --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/BucketImpl.java
      +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/BucketImpl.java
      @@ -10,6 +10,7 @@ package org.opendaylight.controller.remote.rpc.registry.gossip;
       import java.io.Serializable;
       
       public class BucketImpl> implements Bucket, Serializable {
      +    private static final long serialVersionUID = 1L;
       
           private Long version = System.currentTimeMillis();
       
      diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/Messages.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/Messages.java
      index bf8b20213b..4e8f2c61c9 100644
      --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/Messages.java
      +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/Messages.java
      @@ -29,9 +29,12 @@ public class Messages {
       
           public static class BucketStoreMessages{
       
      -        public static class GetLocalBucket implements Serializable{}
      +        public static class GetLocalBucket implements Serializable {
      +            private static final long serialVersionUID = 1L;
      +        }
       
               public static class ContainsBucket implements Serializable {
      +            private static final long serialVersionUID = 1L;
                   final private Bucket bucket;
       
                   public ContainsBucket(Bucket bucket){
      @@ -46,20 +49,25 @@ public class Messages {
               }
       
               public static class UpdateBucket extends ContainsBucket implements Serializable {
      +            private static final long serialVersionUID = 1L;
                   public UpdateBucket(Bucket bucket){
                       super(bucket);
                   }
               }
       
               public static class GetLocalBucketReply extends ContainsBucket implements Serializable {
      +            private static final long serialVersionUID = 1L;
                   public GetLocalBucketReply(Bucket bucket){
                       super(bucket);
                   }
               }
       
      -        public static class GetAllBuckets implements Serializable{}
      +        public static class GetAllBuckets implements Serializable {
      +            private static final long serialVersionUID = 1L;
      +        }
       
               public static class GetBucketsByMembers implements Serializable{
      +            private static final long serialVersionUID = 1L;
                   private Set
      members; public GetBucketsByMembers(Set
      members){ @@ -73,6 +81,7 @@ public class Messages { } public static class ContainsBuckets implements Serializable{ + private static final long serialVersionUID = 1L; private Map buckets; public ContainsBuckets(Map buckets){ @@ -94,20 +103,25 @@ public class Messages { } public static class GetAllBucketsReply extends ContainsBuckets implements Serializable{ + private static final long serialVersionUID = 1L; public GetAllBucketsReply(Map buckets) { super(buckets); } } public static class GetBucketsByMembersReply extends ContainsBuckets implements Serializable{ + private static final long serialVersionUID = 1L; public GetBucketsByMembersReply(Map buckets) { super(buckets); } } - public static class GetBucketVersions implements Serializable{} + public static class GetBucketVersions implements Serializable { + private static final long serialVersionUID = 1L; + } public static class ContainsBucketVersions implements Serializable{ + private static final long serialVersionUID = 1L; Map versions; public ContainsBucketVersions(Map versions) { @@ -123,12 +137,14 @@ public class Messages { } public static class GetBucketVersionsReply extends ContainsBucketVersions implements Serializable{ + private static final long serialVersionUID = 1L; public GetBucketVersionsReply(Map versions) { super(versions); } } public static class UpdateRemoteBuckets extends ContainsBuckets implements Serializable{ + private static final long serialVersionUID = 1L; public UpdateRemoteBuckets(Map buckets) { super(buckets); } @@ -136,11 +152,16 @@ public class Messages { } public static class GossiperMessages{ - public static class Tick implements Serializable {} + public static class Tick implements Serializable { + private static final long serialVersionUID = 1L; + } - public static final class GossipTick extends Tick {} + public static final class GossipTick extends Tick { + private static final long serialVersionUID = 1L; + } public static final class GossipStatus extends ContainsBucketVersions implements Serializable{ + private static final long serialVersionUID = 1L; private Address from; public GossipStatus(Address from, Map versions) { @@ -154,6 +175,7 @@ public class Messages { } public static final class GossipEnvelope extends ContainsBuckets implements Serializable { + private static final long serialVersionUID = 1L; private final Address from; private final Address to; diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/utils/ConditionalProbe.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/utils/ConditionalProbe.java index 13cec54175..dde1861a06 100644 --- a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/utils/ConditionalProbe.java +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/utils/ConditionalProbe.java @@ -15,10 +15,10 @@ import org.slf4j.LoggerFactory; public class ConditionalProbe { private final ActorRef actorRef; - private final Predicate predicate; + private final Predicate predicate; Logger log = LoggerFactory.getLogger(ConditionalProbe.class); - public ConditionalProbe(ActorRef actorRef, Predicate predicate) { + public ConditionalProbe(ActorRef actorRef, Predicate predicate) { this.actorRef = actorRef; this.predicate = predicate; } diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryTest.java index f6f720eed0..ee96cb897f 100644 --- a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryTest.java +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistryTest.java @@ -200,11 +200,11 @@ public class RpcRegistryTest { Messages.BucketStoreMessages.UpdateRemoteBuckets.class); } - private JavaTestKit createProbeForMessage(ActorSystem node, ActorPath subjectPath, final Class clazz) { + private JavaTestKit createProbeForMessage(ActorSystem node, ActorPath subjectPath, final Class clazz) { final JavaTestKit probe = new JavaTestKit(node); ConditionalProbe conditionalProbe = - new ConditionalProbe(probe.getRef(), new Predicate() { + new ConditionalProbe(probe.getRef(), new Predicate() { @Override public boolean apply(@Nullable Object input) { if (input != null) diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/gossip/GossiperTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/gossip/GossiperTest.java index e61b54f067..cf42ebf1cc 100644 --- a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/gossip/GossiperTest.java +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/registry/gossip/GossiperTest.java @@ -71,7 +71,7 @@ public class GossiperTest { @Test public void testReceiveGossipTick_WhenNoRemoteMemberShouldIgnore(){ - mockGossiper.setClusterMembers(Collections.EMPTY_LIST); + mockGossiper.setClusterMembers(Collections.
      emptyList()); doNothing().when(mockGossiper).getLocalStatusAndSendTo(any(Address.class)); mockGossiper.receiveGossipTick(); verify(mockGossiper, times(0)).getLocalStatusAndSendTo(any(Address.class)); diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogicTest.java b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogicTest.java index cd031a1d0a..f74bfc3cff 100644 --- a/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogicTest.java +++ b/opendaylight/md-sal/sal-remoterpc-connector/src/test/java/org/opendaylight/controller/remote/rpc/utils/LatestEntryRoutingLogicTest.java @@ -8,14 +8,13 @@ package org.opendaylight.controller.remote.rpc.utils; - +import static org.junit.Assert.assertTrue; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.japi.Pair; import akka.testkit.JavaTestKit; import akka.testkit.TestProbe; import com.typesafe.config.ConfigFactory; -import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -23,7 +22,6 @@ import org.junit.Test; import java.util.ArrayList; import java.util.List; - public class LatestEntryRoutingLogicTest { static ActorSystem system; @@ -52,6 +50,6 @@ public class LatestEntryRoutingLogicTest { pairList.add(new Pair(actor2, 3000L)); pairList.add(new Pair(actor3, 2000L)); RoutingLogic logic = new LatestEntryRoutingLogic(pairList); - Assert.assertTrue(logic.select().equals(actor2)); + assertTrue(logic.select().equals(actor2)); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java index 3988a495cb..95fb9a4826 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java @@ -7,9 +7,18 @@ */ package org.opendaylight.controller.sal.restconf.impl; +import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION; +import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL; + import com.google.common.base.Optional; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.ListenableFuture; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import javax.ws.rs.core.Response.Status; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; @@ -37,16 +46,6 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.ws.rs.core.Response.Status; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION; -import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL; - public class BrokerFacade { private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class); @@ -261,15 +260,13 @@ public class BrokerFacade { try { - CheckedFuture future = - rwTx.exists(store, currentPath); + CheckedFuture future = rwTx.exists(store, currentPath); exists = future.checkedGet(); } catch (ReadFailedException e) { LOG.error("Failed to read pre-existing data from store {} path {}", store, currentPath, e); throw new IllegalStateException("Failed to read pre-existing data", e); } - if (!exists && iterator.hasNext()) { rwTx.merge(store, currentPath, currentOp.createDefault(currentArg)); } diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java index 665fafacc8..ceac03e3d9 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java @@ -88,11 +88,6 @@ public class RestCodec { "Value is not instance of IdentityrefTypeDefinition but is {}. Therefore NULL is used as translation of - {}", input == null ? "null" : input.getClass(), String.valueOf(input)); return null; - } else if (type instanceof LeafrefTypeDefinition) { - if (input instanceof IdentityValuesDTO) { - return LEAFREF_DEFAULT_CODEC.deserialize(((IdentityValuesDTO) input).getOriginValue()); - } - return LEAFREF_DEFAULT_CODEC.deserialize(input); } else if (type instanceof InstanceIdentifierTypeDefinition) { if (input instanceof IdentityValuesDTO) { return instanceIdentifier.deserialize(input); @@ -232,7 +227,7 @@ public class RestCodec { IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0); Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint); if (module == null) { - logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", + logger.info("Module by namespace '{}' of first node in instance-identifier was not found.", valueWithNamespace.getNamespace()); logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(valueWithNamespace.getValue())); diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java index a95a64b2c2..ded398a33d 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java +++ b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java @@ -9,9 +9,12 @@ package org.opendaylight.controller.sal.restconf.impl; import com.google.common.base.Objects; +import com.google.common.base.Optional; import com.google.common.base.Preconditions; +import com.google.common.base.Predicates; import com.google.common.base.Splitter; import com.google.common.base.Strings; +import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; @@ -63,6 +66,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceI import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; +import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException; import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory; import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; import org.opendaylight.yangtools.yang.data.impl.NodeFactory; @@ -80,7 +84,9 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; +import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition; import org.opendaylight.yangtools.yang.model.util.EmptyType; +import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder; import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder; import org.slf4j.Logger; @@ -976,9 +982,13 @@ public class RestconfImpl implements RestconfService { broker.commitConfigurationDataDelete(normalizedII).get(); } } catch (Exception e) { - throw new RestconfDocumentedException("Error creating data", e); + final Optional searchedException = Iterables.tryFind(Throwables.getCausalChain(e), + Predicates.instanceOf(ModifiedNodeDoesNotExistException.class)); + if (searchedException.isPresent()) { + throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING); + } + throw new RestconfDocumentedException("Error while deleting data", e); } - return Response.status(Status.OK).build(); } @@ -1233,7 +1243,9 @@ public class RestconfImpl implements RestconfService { try { this.normalizeNode(nodeWrap, schema, null, mountPoint); } catch (IllegalArgumentException e) { - throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); + RestconfDocumentedException restconfDocumentedException = new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); + restconfDocumentedException.addSuppressed(e); + throw restconfDocumentedException; } if (nodeWrap instanceof CompositeNodeWrapper) { return ((CompositeNodeWrapper) nodeWrap).unwrap(); @@ -1311,11 +1323,14 @@ public class RestconfImpl implements RestconfService { final Object value = simpleNode.getValue(); Object inputValue = value; TypeDefinition typeDefinition = this.typeDefinition(schema); - if ((typeDefinition instanceof IdentityrefTypeDefinition)) { - if ((value instanceof String)) { - inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null, - (String) value); - } // else value is already instance of IdentityValuesDTO + + // For leafrefs, extract the type it is pointing to + if(typeDefinition instanceof LeafrefTypeDefinition) { + typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? this.controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), schema); + } + + if (typeDefinition instanceof IdentityrefTypeDefinition) { + inputValue = parseToIdentityValuesDTO(simpleNode, value, inputValue); } Object outputValue = inputValue; @@ -1328,6 +1343,14 @@ public class RestconfImpl implements RestconfService { simpleNode.setValue(outputValue); } + private Object parseToIdentityValuesDTO(final SimpleNodeWrapper simpleNode, final Object value, Object inputValue) { + if ((value instanceof String)) { + inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null, + (String) value); + } // else value is already instance of IdentityValuesDTO + return inputValue; + } + private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder, final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) { final List> children = compositeNodeBuilder.getValues(); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java index b5d3528e95..fa79fb7677 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java @@ -63,7 +63,7 @@ public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader { @Test public void leafrefToNotLeafTest() { String json = toJson("/cnsn-to-json/leafref/xml/data_ref_to_not_leaf.xml"); - validateJson(".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lf6\":\\p{Blank}*\"44.33\".*", json); + validateJson(".*\"cont-augment-module\\p{Blank}*:\\p{Blank}*lf6\":\\p{Blank}*\"44\".*", json); } /** diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java index 59696bc534..bdd74e8f96 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java @@ -51,9 +51,7 @@ public class JsonLeafrefToCnSnTest extends YangAndXmlAndDataSchemaLoader { } assertNotNull(lf2); - assertTrue(lf2.getValue() instanceof String); - assertEquals("121", lf2.getValue()); - + assertEquals(121, lf2.getValue()); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java index 6b25830240..f533a6360a 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java @@ -8,9 +8,21 @@ package org.opendaylight.controller.sal.restconf.impl.test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + import com.google.common.base.Optional; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; +import java.util.concurrent.Future; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -43,19 +55,6 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; -import java.util.concurrent.Future; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - /** * Unit tests for BrokerFacade. * @@ -234,6 +233,9 @@ public class BrokerFacadeTest { when(wTransaction.submit()).thenReturn(expFuture); + NormalizedNode dummyNode2 = createDummyNode("dummy:namespace2", "2014-07-01", "dummy local name2"); + + CheckedFuture actualFuture = brokerFacade .commitConfigurationDataDelete(instanceID); diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java index 1c8e53e69f..7b216ef1ba 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java @@ -12,17 +12,27 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URISyntaxException; + import javax.ws.rs.WebApplicationException; + import org.junit.BeforeClass; import org.junit.Test; import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider; import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider; +import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.Node; -import org.opendaylight.yangtools.yang.data.api.SimpleNode; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class XmlAndJsonToCnSnLeafRefTest extends YangAndXmlAndDataSchemaLoader { + final QName refContQName = QName.create("referenced:module", "2014-04-17", "cont"); + final QName refLf1QName = QName.create(refContQName, "lf1"); + final QName contQName = QName.create("leafref:module", "2014-04-17", "cont"); + final QName lf1QName = QName.create(contQName, "lf1"); + final QName lf2QName = QName.create(contQName, "lf2"); + final QName lf3QName = QName.create(contQName, "lf3"); + @BeforeClass public static void initialize() { dataLoad("/leafref/yang", 2, "leafref-module", "cont"); @@ -36,7 +46,11 @@ public class XmlAndJsonToCnSnLeafRefTest extends YangAndXmlAndDataSchemaLoader { CompositeNode cnSn = (CompositeNode)node; TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath); - verifyContPredicate(cnSn, "/ns:cont/ns:lf1", "/cont/lf1", "/ns:cont/ns:lf1", "../lf1"); + + verifyContPredicate(cnSn, "lf4", YangInstanceIdentifier.builder().node(refContQName).node(refLf1QName).build()); + verifyContPredicate(cnSn, "lf2", YangInstanceIdentifier.builder().node(contQName).node(lf1QName).build()); + verifyContPredicate(cnSn, "lf3", YangInstanceIdentifier.builder().node(contQName).node(lf2QName).build()); + verifyContPredicate(cnSn, "lf5", YangInstanceIdentifier.builder().node(contQName).node(lf3QName).build()); } @Test @@ -47,31 +61,23 @@ public class XmlAndJsonToCnSnLeafRefTest extends YangAndXmlAndDataSchemaLoader { CompositeNode cnSn = (CompositeNode)node; TestUtils.normalizeCompositeNode(cnSn, modules, schemaNodePath); - verifyContPredicate(cnSn, "/leafref-module:cont/leafref-module:lf1", "/leafref-module:cont/leafref-module:lf1", - "/referenced-module:cont/referenced-module:lf1", "/leafref-module:cont/leafref-module:lf1"); + + verifyContPredicate(cnSn, "lf4", YangInstanceIdentifier.builder().node(refContQName).node(refLf1QName).build()); + verifyContPredicate(cnSn, "lf2", YangInstanceIdentifier.builder().node(contQName).node(lf1QName).build()); + verifyContPredicate(cnSn, "lf3", YangInstanceIdentifier.builder().node(contQName).node(lf2QName).build()); + verifyContPredicate(cnSn, "lf5", YangInstanceIdentifier.builder().node(contQName).node(lf3QName).build()); } - private void verifyContPredicate(CompositeNode cnSn, String... values) throws URISyntaxException { - Object lf2Value = null; - Object lf3Value = null; - Object lf4Value = null; - Object lf5Value = null; - - for (Node node : cnSn.getValue()) { - if (node.getNodeType().getLocalName().equals("lf2")) { - lf2Value = ((SimpleNode) node).getValue(); - } else if (node.getNodeType().getLocalName().equals("lf3")) { - lf3Value = ((SimpleNode) node).getValue(); - } else if (node.getNodeType().getLocalName().equals("lf4")) { - lf4Value = ((SimpleNode) node).getValue(); - } else if (node.getNodeType().getLocalName().equals("lf5")) { - lf5Value = ((SimpleNode) node).getValue(); + private void verifyContPredicate(CompositeNode cnSn, String leafName, Object value) throws URISyntaxException { + Object parsed = null; + + for (final Node node : cnSn.getValue()) { + if (node.getNodeType().getLocalName().equals(leafName)) { + parsed = node.getValue(); } } - assertEquals(values[0], lf2Value); - assertEquals(values[1], lf3Value); - assertEquals(values[2], lf4Value); - assertEquals(values[3], lf5Value); + + assertEquals(value, parsed); } } diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java index d0af29e913..64568da769 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java +++ b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java @@ -54,8 +54,7 @@ public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader { } assertNotNull(lf2); - assertTrue(lf2.getValue() instanceof String); - assertEquals("121", lf2.getValue()); + assertEquals(121, lf2.getValue()); } @Test diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/leafref/cont-augment-module.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/leafref/cont-augment-module.yang index afc23b7946..27b2dae243 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/leafref/cont-augment-module.yang +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/leafref/cont-augment-module.yang @@ -1,42 +1,42 @@ module cont-augment-module { - namespace "cont:augment:module"; + namespace "cont:augment:module"; prefix "cntaugmod"; - + import main-module {prefix mamo; revision-date 2013-12-2;} - + revision 2013-12-2 { - + } - + augment "/mamo:cont" { leaf-list lflst1 { type leafref { - path "../lf1"; + path "../mamo:lf1"; } - } - + } + leaf lf4 { type leafref { - path "../lf1"; + path "../mamo:lf1"; } } - + /* reference to not leaf element */ leaf lf6 { type leafref { path "../lflst1"; } } - + leaf lf7 { type leafref { path "../lf4"; } } } - - - + + + } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/leafref/xml/data_ref_to_not_leaf.xml b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/leafref/xml/data_ref_to_not_leaf.xml index 10632a44af..b72d438c28 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/leafref/xml/data_ref_to_not_leaf.xml +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/leafref/xml/data_ref_to_not_leaf.xml @@ -1,3 +1,3 @@ - 44.33 + 44 \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/leafref/json/jsondata.json b/opendaylight/md-sal/sal-rest-connector/src/test/resources/leafref/json/jsondata.json index cbe455b33b..f4a435e3bf 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/resources/leafref/json/jsondata.json +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/leafref/json/jsondata.json @@ -2,7 +2,7 @@ "leafref-module:cont" : { "lf4" : "/referenced-module:cont/referenced-module:lf1", "lf2" : "/leafref-module:cont/leafref-module:lf1", - "lf3" : "/leafref-module:cont/leafref-module:lf1", - "lf5" : "/leafref-module:cont/leafref-module:lf1" + "lf3" : "/leafref-module:cont/leafref-module:lf2", + "lf5" : "/leafref-module:cont/leafref-module:lf3" } } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/leafref/xml/xmldata.xml b/opendaylight/md-sal/sal-rest-connector/src/test/resources/leafref/xml/xmldata.xml index 01bf092d27..1b5ce835fc 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/resources/leafref/xml/xmldata.xml +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/leafref/xml/xmldata.xml @@ -1,6 +1,6 @@ - - /ns:cont/ns:lf1 - /ns:cont/ns:lf1 - /cont/lf1 - ../lf1 + + /nsa:cont/nsa:lf1 + /nsa:cont/nsa:lf1 + /ns:cont/ns:lf2 + /nsa:cont/nsa:lf3 diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/leafref-module b/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/leafref-module index 8ca9f09096..6fe770b40b 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/leafref-module +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/leafref-module @@ -1,19 +1,61 @@ module leafref-module { - namespace "leafref:module"; + namespace "leafref:module"; prefix "lfrfmo"; - revision 2013-11-18 { + revision 2013-11-18 { } + identity base {} + container cont { leaf lf1 { type int32; } leaf lf2 { type leafref { - path "/cont/lf1"; + path "/cont/lf1"; + } + } + + leaf lf-ident { + type identityref { + base "lfrfmo:base"; } } + + leaf lf-ident-ref { + type leafref { + path "/cont/lf-ident"; + } + } + + leaf lf-ident-ref-relative { + type leafref { + path "../lf-ident"; + } + } + + leaf lf-ident-ref-relative-cnd { + type leafref { + path "/lfrfmo:cont/lfrfmo:lis[lfrfmo:id='abc']/lf-ident-ref"; + } + } + + + list lis { + key "id"; + + leaf id { + type string; + } + + leaf lf-ident-ref { + type leafref { + path "/cont/lf-ident"; + } + } + } + } - + } \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/xml/data.xml b/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/xml/data.xml index 06200a69b5..c3071e5610 100644 --- a/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/xml/data.xml +++ b/opendaylight/md-sal/sal-rest-connector/src/test/resources/xml-to-cnsn/leafref/xml/data.xml @@ -1,4 +1,8 @@ 121 121 + a:base + a:base + a:base + a:base \ No newline at end of file diff --git a/opendaylight/md-sal/sal-rest-docgen/pom.xml b/opendaylight/md-sal/sal-rest-docgen/pom.xml index 5abb4f8910..3d3c52d7d1 100644 --- a/opendaylight/md-sal/sal-rest-docgen/pom.xml +++ b/opendaylight/md-sal/sal-rest-docgen/pom.xml @@ -10,10 +10,6 @@ sal-rest-docgen bundle - - 3.0.4.Final - - com.fasterxml.jackson.core @@ -42,7 +38,6 @@ org.jboss.resteasy jaxrs-api - ${jaxrs-api.version} diff --git a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/DocProvider.java b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/DocProvider.java index 9a1816b90e..9442ca0c07 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/DocProvider.java +++ b/opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/DocProvider.java @@ -70,7 +70,7 @@ public class DocProvider implements BundleActivator, ServiceTrackerCustomizer
      (context, Broker.class, this); brokerServiceTracker.open(); } diff --git a/opendaylight/md-sal/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGeneratorTest.java b/opendaylight/md-sal/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGeneratorTest.java index 9165281f9d..02c5137fe9 100644 --- a/opendaylight/md-sal/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGeneratorTest.java +++ b/opendaylight/md-sal/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGeneratorTest.java @@ -14,7 +14,6 @@ import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import javax.ws.rs.core.UriInfo; -import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; @@ -205,7 +204,7 @@ public class ApiDocGeneratorTest { if (m.getKey().getAbsolutePath().endsWith("toaster.yang")) { ApiDeclaration doc = generator.getSwaggerDocSpec(m.getValue(), "http://localhost:8080/restconf", "", schemaContext); - Assert.assertNotNull(doc); + assertNotNull(doc); // testing bugs.opendaylight.org bug 1290. UnionType model type. String jsonString = doc.getModels().toString(); diff --git a/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/impl/NotificationServiceImpl.java b/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/impl/NotificationServiceImpl.java index c08f329f0d..192836e9fa 100644 --- a/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/impl/NotificationServiceImpl.java +++ b/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/impl/NotificationServiceImpl.java @@ -39,7 +39,7 @@ public class NotificationServiceImpl implements NotificationService { notifications.add(new QName(notificationType.toString())); String notificationStreamName = RemoteStreamTools.createNotificationStream(salRemoteService, notifications); final Map desiredEventStream = RemoteStreamTools.createEventStream(restconfClientContext, notificationStreamName); - RemoteNotificationListener remoteNotificationListener = new RemoteNotificationListener(listener); + RemoteNotificationListener remoteNotificationListener = new RemoteNotificationListener(listener); final ListenerRegistration listenerRegistration = restconfClientContext.getEventStreamContext(desiredEventStream.get(desiredEventStream.get(notificationStreamName))) .registerNotificationListener(remoteNotificationListener); diff --git a/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/listeners/RemoteNotificationListener.java b/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/listeners/RemoteNotificationListener.java index 895a5030e9..82fa2ae2e9 100644 --- a/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/listeners/RemoteNotificationListener.java +++ b/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/listeners/RemoteNotificationListener.java @@ -8,15 +8,16 @@ package org.opendaylight.controller.sal.restconf.broker.listeners; import org.opendaylight.controller.sal.binding.api.NotificationListener; +import org.opendaylight.yangtools.yang.binding.Notification; -public class RemoteNotificationListener implements org.opendaylight.yangtools.yang.binding.NotificationListener { +public class RemoteNotificationListener implements org.opendaylight.yangtools.yang.binding.NotificationListener { - org.opendaylight.controller.sal.binding.api.NotificationListener listener; + NotificationListener listener; - public RemoteNotificationListener(NotificationListener listener){ + public RemoteNotificationListener(NotificationListener listener){ this.listener = listener; } - public NotificationListener getListener(){ + public NotificationListener getListener() { return this.listener; } diff --git a/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/listeners/SalNotificationListener.java b/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/listeners/SalNotificationListener.java index 16ca0aee93..3c4bbba4a4 100644 --- a/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/listeners/SalNotificationListener.java +++ b/opendaylight/md-sal/sal-restconf-broker/src/main/java/org/opendaylight/controller/sal/restconf/broker/listeners/SalNotificationListener.java @@ -11,14 +11,14 @@ import org.opendaylight.controller.sal.binding.api.NotificationListener; import org.opendaylight.yangtools.yang.binding.Notification; -public class SalNotificationListener implements NotificationListener { - private NotificationListener notificationListener; +public class SalNotificationListener implements NotificationListener { + private NotificationListener notificationListener; - public SalNotificationListener( NotificationListener notificationListener){ + public SalNotificationListener( NotificationListener notificationListener){ this.notificationListener = notificationListener; } @Override public void onNotification(Notification notification) { - this.notificationListener.onNotification(notification); + this.notificationListener.onNotification((T)notification); } } diff --git a/opendaylight/md-sal/samples/l2switch/implementation/pom.xml b/opendaylight/md-sal/samples/l2switch/implementation/pom.xml deleted file mode 100644 index a0e119b49c..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller.samples - sal-samples - 1.2.0-SNAPSHOT - ../.. - - org.opendaylight.controller.samples.l2switch.md - l2switch-impl - bundle - - - org.opendaylight.controller - sal - - - - org.opendaylight.controller - sal-binding-api - - - org.opendaylight.controller.model - model-flow-service - - - - org.opendaylight.controller.model - model-inventory - - - org.opendaylight.controller.model - model-topology - - - org.opendaylight.controller.samples.l2switch.md - l2switch-model - ${project.version} - - - org.opendaylight.controller.thirdparty - net.sf.jung2 - - - org.opendaylight.yangtools - yang-binding - - - org.opendaylight.yangtools - yang-common - - - junit - junit - test - - - org.mockito - mockito-all - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.sample.l2switch.md.L2SwitchProvider - - ${project.build.directory}/META-INF - - - - - diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/L2SwitchProvider.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/L2SwitchProvider.java deleted file mode 100644 index d123456262..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/L2SwitchProvider.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md; - -import org.opendaylight.controller.sample.l2switch.md.addresstracker.AddressTracker; -import org.opendaylight.controller.sample.l2switch.md.flow.FlowWriterService; -import org.opendaylight.controller.sample.l2switch.md.flow.FlowWriterServiceImpl; -import org.opendaylight.controller.sample.l2switch.md.inventory.InventoryService; -import org.opendaylight.controller.sample.l2switch.md.packet.PacketHandler; -import org.opendaylight.controller.sample.l2switch.md.topology.NetworkGraphDijkstra; -import org.opendaylight.controller.sample.l2switch.md.topology.NetworkGraphService; -import org.opendaylight.controller.sample.l2switch.md.topology.TopologyLinkDataChangeHandler; -import org.opendaylight.controller.sal.binding.api.AbstractBindingAwareConsumer; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationService; -import org.opendaylight.controller.sal.binding.api.data.DataBrokerService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.NotificationListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * L2SwitchProvider serves as the Activator for our L2Switch OSGI bundle. - */ -public class L2SwitchProvider extends AbstractBindingAwareConsumer - implements AutoCloseable { - - private final static Logger _logger = LoggerFactory.getLogger(L2SwitchProvider.class); - - private ListenerRegistration listenerRegistration; - private AddressTracker addressTracker; - private TopologyLinkDataChangeHandler topologyLinkDataChangeHandler; - - - /** - * Setup the L2Switch. - * @param consumerContext The context of the L2Switch. - */ - @Override - public void onSessionInitialized(BindingAwareBroker.ConsumerContext consumerContext) { - DataBrokerService dataService = consumerContext.getSALService(DataBrokerService.class); - addressTracker = new AddressTracker(dataService); - - NetworkGraphService networkGraphService = new NetworkGraphDijkstra(); - FlowWriterService flowWriterService = new FlowWriterServiceImpl(dataService, networkGraphService); - - NotificationService notificationService = - consumerContext.getSALService(NotificationService.class); - PacketProcessingService packetProcessingService = - consumerContext.getRpcService(PacketProcessingService.class); - PacketHandler packetHandler = new PacketHandler(); - packetHandler.setAddressTracker(addressTracker); - packetHandler.setFlowWriterService(flowWriterService); - packetHandler.setPacketProcessingService(packetProcessingService); - packetHandler.setInventoryService(new InventoryService(dataService)); - - this.listenerRegistration = notificationService.registerNotificationListener(packetHandler); - this.topologyLinkDataChangeHandler = new TopologyLinkDataChangeHandler(dataService, networkGraphService); - topologyLinkDataChangeHandler.registerAsDataChangeListener(); - } - - /** - * Cleanup the L2Switch. - * @throws Exception occurs when the NotificationListener is closed - */ - @Override - public void close() throws Exception { - if (listenerRegistration != null) - listenerRegistration.close(); - } -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/addresstracker/AddressTracker.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/addresstracker/AddressTracker.java deleted file mode 100644 index ae5f03110c..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/addresstracker/AddressTracker.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.addresstracker; - -import org.opendaylight.controller.md.sal.common.api.TransactionStatus; -import org.opendaylight.controller.sal.binding.api.data.DataBrokerService; -import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.address.tracker.rev140402.L2Addresses; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.address.tracker.rev140402.l2.addresses.L2Address; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.address.tracker.rev140402.l2.addresses.L2AddressBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.address.tracker.rev140402.l2.addresses.L2AddressKey; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.Future; - -/** - * AddressTracker manages the MD-SAL data tree for L2Address (mac, node connector pairings) information. - */ -public class AddressTracker { - - private final static Logger _logger = LoggerFactory.getLogger(AddressTracker.class); - private DataBrokerService dataService; - - /** - * Construct an AddressTracker with the specified inputs - * @param dataService The DataBrokerService for the AddressTracker - */ - public AddressTracker(DataBrokerService dataService) { - this.dataService = dataService; - } - - /** - * Get all the L2 Addresses in the MD-SAL data tree - * @return All the L2 Addresses in the MD-SAL data tree - */ - public L2Addresses getAddresses() { - return (L2Addresses)dataService.readOperationalData(InstanceIdentifier.builder(L2Addresses.class).toInstance()); - } - - /** - * Get a specific L2 Address in the MD-SAL data tree - * @param macAddress A MacAddress associated with an L2 Address object - * @return The L2 Address corresponding to the specified macAddress - */ - public L2Address getAddress(MacAddress macAddress) { - return (L2Address) dataService.readOperationalData(createPath(macAddress)); - } - - /** - * Add L2 Address into the MD-SAL data tree - * @param macAddress The MacAddress of the new L2Address object - * @param nodeConnectorRef The NodeConnectorRef of the new L2Address object - * @return Future containing the result of the add operation - */ - public Future> addAddress(MacAddress macAddress, NodeConnectorRef nodeConnectorRef) { - if(macAddress == null || nodeConnectorRef == null) { - return null; - } - - // Create L2Address - final L2AddressBuilder builder = new L2AddressBuilder(); - builder.setKey(new L2AddressKey(macAddress)) - .setMac(macAddress) - .setNodeConnectorRef(nodeConnectorRef); - - // Add L2Address to MD-SAL data tree - final DataModificationTransaction it = dataService.beginTransaction(); - it.putOperationalData(createPath(macAddress), builder.build()); - return it.commit(); - } - - /** - * Remove L2Address from the MD-SAL data tree - * @param macAddress The MacAddress of an L2Address object - * @return Future containing the result of the remove operation - */ - public Future> removeHost(MacAddress macAddress) { - final DataModificationTransaction it = dataService.beginTransaction(); - it.removeOperationalData(createPath(macAddress)); - return it.commit(); - } - - /** - * Create InstanceIdentifier path for an L2Address in the MD-SAL data tree - * @param macAddress The MacAddress of an L2Address object - * @return InstanceIdentifier of the L2Address corresponding to the specified macAddress - */ - private InstanceIdentifier createPath(MacAddress macAddress) { - return InstanceIdentifier.builder(L2Addresses.class) - .child(L2Address.class, new L2AddressKey(macAddress)).toInstance(); - } -} \ No newline at end of file diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterService.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterService.java deleted file mode 100644 index 2d5149e492..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterService.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.flow; - -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; - -/** - * Service that adds packet forwarding flows to configuration data store. - */ -public interface FlowWriterService { - - /** - * Writes a flow that forwards packets to destPort if destination mac in packet is destMac and - * source Mac in packet is sourceMac. If sourceMac is null then flow would not set any source mac, - * resulting in all packets with destMac being forwarded to destPort. - * - * @param sourceMac - * @param destMac - * @param destNodeConnectorRef - */ - public void addMacToMacFlow(MacAddress sourceMac, MacAddress destMac, NodeConnectorRef destNodeConnectorRef); - - /** - * Writes mac-to-mac flow on all ports that are in the path between given source and destination ports. - * It uses path provided by NetworkGraphService{@link org.opendaylight.controller.sample.l2switch.md.topology.NetworkGraphService} to find a links{@link org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link} - * between given ports. And then writes appropriate flow on each port that is covered in that path. - * - * @param sourceMac - * @param sourceNodeConnectorRef - * @param destMac - * @param destNodeConnectorRef - */ - public void addMacToMacFlowsUsingShortestPath(MacAddress sourceMac, NodeConnectorRef sourceNodeConnectorRef, MacAddress destMac, NodeConnectorRef destNodeConnectorRef); - - -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterServiceImpl.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterServiceImpl.java deleted file mode 100644 index fccda9d578..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterServiceImpl.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.flow; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; - -import org.opendaylight.controller.sample.l2switch.md.topology.NetworkGraphService; -import org.opendaylight.controller.sample.l2switch.md.util.InstanceIdentifierUtils; -import org.opendaylight.controller.md.sal.common.api.TransactionStatus; -import org.opendaylight.controller.sal.binding.api.data.DataBrokerService; -import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.output.action._case.OutputActionBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action; -import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.ApplyActionsCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActions; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.math.BigInteger; -import java.util.List; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Implementation of FlowWriterService{@link org.opendaylight.controller.sample.l2switch.md.flow.FlowWriterService}, - * that builds required flow and writes to configuration data store using provided DataBrokerService - * {@link org.opendaylight.controller.sal.binding.api.data.DataBrokerService} - */ -public class FlowWriterServiceImpl implements FlowWriterService { - private static final Logger _logger = LoggerFactory.getLogger(FlowWriterServiceImpl.class); - private final DataBrokerService dataBrokerService; - private final NetworkGraphService networkGraphService; - private AtomicLong flowIdInc = new AtomicLong(); - private AtomicLong flowCookieInc = new AtomicLong(0x2a00000000000000L); - - - public FlowWriterServiceImpl(DataBrokerService dataBrokerService, NetworkGraphService networkGraphService) { - Preconditions.checkNotNull(dataBrokerService, "dataBrokerService should not be null."); - Preconditions.checkNotNull(networkGraphService, "networkGraphService should not be null."); - this.dataBrokerService = dataBrokerService; - this.networkGraphService = networkGraphService; - } - - /** - * Writes a flow that forwards packets to destPort if destination mac in packet is destMac and - * source Mac in packet is sourceMac. If sourceMac is null then flow would not set any source mac, - * resulting in all packets with destMac being forwarded to destPort. - * - * @param sourceMac - * @param destMac - * @param destNodeConnectorRef - */ - @Override - public void addMacToMacFlow(MacAddress sourceMac, MacAddress destMac, NodeConnectorRef destNodeConnectorRef) { - - Preconditions.checkNotNull(destMac, "Destination mac address should not be null."); - Preconditions.checkNotNull(destNodeConnectorRef, "Destination port should not be null."); - - - // do not add flow if both macs are same. - if(sourceMac != null && destMac.equals(sourceMac)) { - _logger.info("In addMacToMacFlow: No flows added. Source and Destination mac are same."); - return; - } - - // get flow table key - TableKey flowTableKey = new TableKey((short) 0); //TODO: Hard coded Table Id 0, need to get it from Configuration data. - - //build a flow path based on node connector to program flow - InstanceIdentifier flowPath = buildFlowPath(destNodeConnectorRef, flowTableKey); - - // build a flow that target given mac id - Flow flowBody = createMacToMacFlow(flowTableKey.getId(), 0, sourceMac, destMac, destNodeConnectorRef); - - // commit the flow in config data - writeFlowToConfigData(flowPath, flowBody); - } - - /** - * Writes mac-to-mac flow on all ports that are in the path between given source and destination ports. - * It uses path provided by NetworkGraphService - * {@link org.opendaylight.controller.sample.l2switch.md.topology.NetworkGraphService} to find a links - * {@link org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link} - * between given ports. And then writes appropriate flow on each port that is covered in that path. - * - * @param sourceMac - * @param sourceNodeConnectorRef - * @param destMac - * @param destNodeConnectorRef - */ - @Override - public void addMacToMacFlowsUsingShortestPath(MacAddress sourceMac, - NodeConnectorRef sourceNodeConnectorRef, - MacAddress destMac, - NodeConnectorRef destNodeConnectorRef) { - Preconditions.checkNotNull(sourceMac, "Source mac address should not be null."); - Preconditions.checkNotNull(sourceNodeConnectorRef, "Source port should not be null."); - Preconditions.checkNotNull(destMac, "Destination mac address should not be null."); - Preconditions.checkNotNull(destNodeConnectorRef, "Destination port should not be null."); - - if(sourceNodeConnectorRef.equals(destNodeConnectorRef)) { - _logger.info("In addMacToMacFlowsUsingShortestPath: No flows added. Source and Destination ports are same."); - return; - - } - NodeId sourceNodeId = new NodeId(sourceNodeConnectorRef.getValue().firstKeyOf(Node.class, NodeKey.class).getId().getValue()); - NodeId destNodeId = new NodeId(destNodeConnectorRef.getValue().firstKeyOf(Node.class, NodeKey.class).getId().getValue()); - - // add destMac-To-sourceMac flow on source port - addMacToMacFlow(destMac, sourceMac, sourceNodeConnectorRef); - - // add sourceMac-To-destMac flow on destination port - addMacToMacFlow(sourceMac, destMac, destNodeConnectorRef); - - if(!sourceNodeId.equals(destNodeId)) { - List linksInBeween = networkGraphService.getPath(sourceNodeId, destNodeId); - - if(linksInBeween != null) { - // assumes the list order is maintained and starts with link that has source as source node - for(Link link : linksInBeween) { - // add sourceMac-To-destMac flow on source port - addMacToMacFlow(sourceMac, destMac, getSourceNodeConnectorRef(link)); - - // add destMac-To-sourceMac flow on destination port - addMacToMacFlow(destMac, sourceMac, getDestNodeConnectorRef(link)); - } - } - } - } - - private NodeConnectorRef getSourceNodeConnectorRef(Link link) { - InstanceIdentifier nodeConnectorInstanceIdentifier - = InstanceIdentifierUtils.createNodeConnectorIdentifier( - link.getSource().getSourceNode().getValue(), - link.getSource().getSourceTp().getValue()); - return new NodeConnectorRef(nodeConnectorInstanceIdentifier); - } - - private NodeConnectorRef getDestNodeConnectorRef(Link link) { - InstanceIdentifier nodeConnectorInstanceIdentifier - = InstanceIdentifierUtils.createNodeConnectorIdentifier( - link.getDestination().getDestNode().getValue(), - link.getDestination().getDestTp().getValue()); - - return new NodeConnectorRef(nodeConnectorInstanceIdentifier); - } - - /** - * @param nodeConnectorRef - * @return - */ - private InstanceIdentifier buildFlowPath(NodeConnectorRef nodeConnectorRef, TableKey flowTableKey) { - - // generate unique flow key - FlowId flowId = new FlowId(String.valueOf(flowIdInc.getAndIncrement())); - FlowKey flowKey = new FlowKey(flowId); - - return InstanceIdentifierUtils.generateFlowInstanceIdentifier(nodeConnectorRef, flowTableKey, flowKey); - } - - /** - * @param tableId - * @param priority - * @param sourceMac - * @param destMac - * @param destPort - * @return {@link org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder} - * builds flow that forwards all packets with destMac to given port - */ - private Flow createMacToMacFlow(Short tableId, int priority, - MacAddress sourceMac, MacAddress destMac, NodeConnectorRef destPort) { - - // start building flow - FlowBuilder macToMacFlow = new FlowBuilder() // - .setTableId(tableId) // - .setFlowName("mac2mac"); - - // use its own hash code for id. - macToMacFlow.setId(new FlowId(Long.toString(macToMacFlow.hashCode()))); - - // create a match that has mac to mac ethernet match - EthernetMatchBuilder ethernetMatchBuilder = new EthernetMatchBuilder() // - .setEthernetDestination(new EthernetDestinationBuilder() // - .setAddress(destMac) // - .build()); - // set source in the match only if present - if(sourceMac != null) { - ethernetMatchBuilder.setEthernetSource(new EthernetSourceBuilder() - .setAddress(sourceMac) - .build()); - } - EthernetMatch ethernetMatch = ethernetMatchBuilder.build(); - Match match = new MatchBuilder() - .setEthernetMatch(ethernetMatch) - .build(); - - - Uri destPortUri = destPort.getValue().firstKeyOf(NodeConnector.class, NodeConnectorKey.class).getId(); - - Action outputToControllerAction = new ActionBuilder() // - .setOrder(0) - .setAction(new OutputActionCaseBuilder() // - .setOutputAction(new OutputActionBuilder() // - .setMaxLength(new Integer(0xffff)) // - .setOutputNodeConnector(destPortUri) // - .build()) // - .build()) // - .build(); - - // Create an Apply Action - ApplyActions applyActions = new ApplyActionsBuilder().setAction(ImmutableList.of(outputToControllerAction)) - .build(); - - // Wrap our Apply Action in an Instruction - Instruction applyActionsInstruction = new InstructionBuilder() // - .setOrder(0) - .setInstruction(new ApplyActionsCaseBuilder()// - .setApplyActions(applyActions) // - .build()) // - .build(); - - // Put our Instruction in a list of Instructions - macToMacFlow - .setMatch(match) // - .setInstructions(new InstructionsBuilder() // - .setInstruction(ImmutableList.of(applyActionsInstruction)) // - .build()) // - .setPriority(priority) // - .setBufferId(0L) // - .setHardTimeout(0) // - .setIdleTimeout(0) // - .setCookie(new FlowCookie(BigInteger.valueOf(flowCookieInc.getAndIncrement()))) - .setFlags(new FlowModFlags(false, false, false, false, false)); - - return macToMacFlow.build(); - } - - /** - * Starts and commits data change transaction which - * modifies provided flow path with supplied body. - * - * @param flowPath - * @param flowBody - * @return transaction commit - */ - private Future> writeFlowToConfigData(InstanceIdentifier flowPath, - Flow flowBody) { - DataModificationTransaction addFlowTransaction = dataBrokerService.beginTransaction(); - addFlowTransaction.putConfigurationData(flowPath, flowBody); - return addFlowTransaction.commit(); - } -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/inventory/InventoryService.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/inventory/InventoryService.java deleted file mode 100644 index 1ec65e8f81..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/inventory/InventoryService.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.inventory; - -import org.opendaylight.controller.sample.l2switch.md.util.InstanceIdentifierUtils; -import org.opendaylight.controller.sal.binding.api.data.DataBrokerService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * InventoryService provides functions related to Nodes & NodeConnectors. - */ -public class InventoryService { - private DataBrokerService dataService; - // Key: SwitchId, Value: NodeConnectorRef that corresponds to NC between controller & switch - private HashMap controllerSwitchConnectors; - - /** - * Construct an InventoryService object with the specified inputs. - * @param dataService The DataBrokerService associated with the InventoryService. - */ - public InventoryService(DataBrokerService dataService) { - this.dataService = dataService; - controllerSwitchConnectors = new HashMap(); - } - - public HashMap getControllerSwitchConnectors() { - return controllerSwitchConnectors; - } - - // ToDo: Improve performance for thousands of switch ports - /** - * Get the External NodeConnectors of the network, which are the NodeConnectors connected to hosts. - * @return The list of external node connectors. - */ - public List getExternalNodeConnectors() { - // External NodeConnectors = All - Internal - ArrayList externalNodeConnectors = new ArrayList(); - Set internalNodeConnectors = new HashSet<>(); - - // Read Topology -- find list of switch-to-switch internal node connectors - NetworkTopology networkTopology = - (NetworkTopology)dataService.readOperationalData( - InstanceIdentifier.builder(NetworkTopology.class).toInstance()); - - for (Topology topology : networkTopology.getTopology()) { - Topology completeTopology = - (Topology)dataService.readOperationalData( - InstanceIdentifierUtils.generateTopologyInstanceIdentifier( - topology.getTopologyId().getValue())); - - for (Link link : completeTopology.getLink()) { - internalNodeConnectors.add(link.getDestination().getDestTp().getValue()); - internalNodeConnectors.add(link.getSource().getSourceTp().getValue()); - } - } - - // Read Inventory -- contains list of all nodeConnectors - InstanceIdentifier.InstanceIdentifierBuilder nodesInsIdBuilder = InstanceIdentifier.builder(Nodes.class); - Nodes nodes = (Nodes)dataService.readOperationalData(nodesInsIdBuilder.toInstance()); - if (nodes != null) { - for (Node node : nodes.getNode()) { - Node completeNode = (Node)dataService.readOperationalData(InstanceIdentifierUtils.createNodePath(node.getId())); - for (NodeConnector nodeConnector : completeNode.getNodeConnector()) { - // NodeConnector isn't switch-to-switch, so it must be controller-to-switch (internal) or external - if (!internalNodeConnectors.contains(nodeConnector.getId().getValue())) { - NodeConnectorRef ncRef = new NodeConnectorRef( - InstanceIdentifier.builder(Nodes.class).child(Node.class, node.getKey()) - .child(NodeConnector.class, nodeConnector.getKey()).toInstance()); - - // External node connectors have "-" in their name for mininet, i.e. "s1-eth1" - if (nodeConnector.getAugmentation(FlowCapableNodeConnector.class).getName().contains("-")) { - externalNodeConnectors.add(ncRef); - } - // Controller-to-switch internal node connectors - else { - controllerSwitchConnectors.put(node.getId().getValue(), ncRef); - } - } - } - } - } - - return externalNodeConnectors; - } -} \ No newline at end of file diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/packet/PacketHandler.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/packet/PacketHandler.java deleted file mode 100644 index b4ea94242c..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/packet/PacketHandler.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.packet; - -import org.opendaylight.controller.sample.l2switch.md.addresstracker.AddressTracker; -import org.opendaylight.controller.sample.l2switch.md.flow.FlowWriterService; -import org.opendaylight.controller.sample.l2switch.md.inventory.InventoryService; -import org.opendaylight.controller.sample.l2switch.md.util.InstanceIdentifierUtils; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.LLDP; -import org.opendaylight.controller.sal.packet.LinkEncap; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.address.tracker.rev140402.l2.addresses.L2Address; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInputBuilder; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.List; - -/** - * PacketHandler examines Ethernet packets to find L2Addresses (mac, nodeConnector) pairings - * of the sender and learns them. - * It also forwards the data packets appropriately dependending upon whether it knows about the - * target or not. - */ -public class PacketHandler implements PacketProcessingListener { - - private final static Logger _logger = LoggerFactory.getLogger(PacketHandler.class); - - private PacketProcessingService packetProcessingService; - private AddressTracker addressTracker; - private FlowWriterService flowWriterService; - private InventoryService inventoryService; - - public void setAddressTracker(AddressTracker addressTracker) { - this.addressTracker = addressTracker; - } - - public void setPacketProcessingService(PacketProcessingService packetProcessingService) { - this.packetProcessingService = packetProcessingService; - } - - public void setFlowWriterService(FlowWriterService flowWriterService) { - this.flowWriterService = flowWriterService; - } - - public void setInventoryService(InventoryService inventoryService) { - this.inventoryService = inventoryService; - } - - /** - * The handler function for all incoming packets. - * @param packetReceived The incoming packet. - */ - @Override - public void onPacketReceived(PacketReceived packetReceived) { - - if(packetReceived == null) return; - - try { - byte[] payload = packetReceived.getPayload(); - RawPacket rawPacket = new RawPacket(payload); - NodeConnectorRef ingress = packetReceived.getIngress(); - - Packet packet = decodeDataPacket(rawPacket); - - if(!(packet instanceof Ethernet)) return; - - handleEthernetPacket(packet, ingress); - - } catch(Exception e) { - _logger.error("Failed to handle packet {}", packetReceived, e); - } - } - - /** - * The handler function for Ethernet packets. - * @param packet The incoming Ethernet packet. - * @param ingress The NodeConnector where the Ethernet packet came from. - */ - private void handleEthernetPacket(Packet packet, NodeConnectorRef ingress) { - byte[] srcMac = ((Ethernet) packet).getSourceMACAddress(); - byte[] destMac = ((Ethernet) packet).getDestinationMACAddress(); - - if (srcMac == null || srcMac.length == 0) return; - - Object enclosedPacket = packet.getPayload(); - - if (enclosedPacket instanceof LLDP) - return; // LLDP packets are handled by OpenFlowPlugin - - // get l2address by src mac - // if unknown, add l2address - MacAddress srcMacAddress = toMacAddress(srcMac); - L2Address src = addressTracker.getAddress(srcMacAddress); - boolean isSrcKnown = (src != null); - if (!isSrcKnown) { - addressTracker.addAddress(srcMacAddress, ingress); - } - - // get host by dest mac - // if known set dest known to true - MacAddress destMacAddress = toMacAddress(destMac); - L2Address dest = addressTracker.getAddress(destMacAddress); - boolean isDestKnown = (dest != null); - - byte[] payload = packet.getRawPayload(); - // if (src and dest known) - // sendpacket to dest and add src<->dest flow - if(isSrcKnown & isDestKnown) { - flowWriterService.addMacToMacFlowsUsingShortestPath(srcMacAddress, src.getNodeConnectorRef(), - destMacAddress, dest.getNodeConnectorRef()); - sendPacketOut(payload, getControllerNodeConnector(dest.getNodeConnectorRef()), dest.getNodeConnectorRef()); - } else { - // if (dest unknown) - // sendpacket to external links minus ingress - floodExternalPorts(payload, ingress); - } - } - - /** - * Floods the specified payload on external ports, which are ports not connected to switches. - * @param payload The payload to be flooded. - * @param ingress The NodeConnector where the payload came from. - */ - private void floodExternalPorts(byte[] payload, NodeConnectorRef ingress) { - List externalPorts = inventoryService.getExternalNodeConnectors(); - externalPorts.remove(ingress); - - for (NodeConnectorRef egress : externalPorts) { - sendPacketOut(payload, getControllerNodeConnector(egress), egress); - } - } - - /** - * Sends the specified packet on the specified port. - * @param payload The payload to be sent. - * @param ingress The NodeConnector where the payload came from. - * @param egress The NodeConnector where the payload will go. - */ - private void sendPacketOut(byte[] payload, NodeConnectorRef ingress, NodeConnectorRef egress) { - if (ingress == null || egress == null) return; - InstanceIdentifier egressNodePath = InstanceIdentifierUtils.getNodePath(egress.getValue()); - TransmitPacketInput input = new TransmitPacketInputBuilder() // - .setPayload(payload) // - .setNode(new NodeRef(egressNodePath)) // - .setEgress(egress) // - .setIngress(ingress) // - .build(); - packetProcessingService.transmitPacket(input); - } - - /** - * Decodes an incoming packet. - * @param raw The raw packet to be decoded. - * @return The decoded form of the raw packet. - */ - private Packet decodeDataPacket(RawPacket raw) { - if(raw == null) { - return null; - } - byte[] data = raw.getPacketData(); - if(data.length <= 0) { - return null; - } - if(raw.getEncap().equals(LinkEncap.ETHERNET)) { - Ethernet res = new Ethernet(); - try { - res.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte); - res.setRawPayload(raw.getPacketData()); - } catch(Exception e) { - _logger.warn("Failed to decode packet: {}", e.getMessage()); - } - return res; - } - return null; - } - - /** - * Creates a MacAddress object out of a byte array. - * @param dataLinkAddress The byte-array form of a MacAddress - * @return MacAddress of the specified dataLinkAddress. - */ - private MacAddress toMacAddress(byte[] dataLinkAddress) { - return new MacAddress(HexEncode.bytesToHexStringFormat(dataLinkAddress)); - } - - /** - * Gets the NodeConnector that connects the controller & switch for a specified switch port/node connector. - * @param nodeConnectorRef The nodeConnector of a switch. - * @return The NodeConnector that that connects the controller & switch. - */ - private NodeConnectorRef getControllerNodeConnector(NodeConnectorRef nodeConnectorRef) { - NodeConnectorRef controllerSwitchNodeConnector = null; - HashMap controllerSwitchConnectors = inventoryService.getControllerSwitchConnectors(); - InstanceIdentifier nodePath = InstanceIdentifierUtils.getNodePath(nodeConnectorRef.getValue()); - if (nodePath != null) { - NodeKey nodeKey = InstanceIdentifierUtils.getNodeKey(nodePath); - if (nodeKey != null) { - controllerSwitchNodeConnector = controllerSwitchConnectors.get(nodeKey.getId().getValue()); - } - } - return controllerSwitchNodeConnector; - } -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphDijkstra.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphDijkstra.java deleted file mode 100644 index a90ac5a007..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphDijkstra.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.topology; - -import com.google.common.base.Preconditions; -import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath; -import edu.uci.ics.jung.graph.DirectedSparseGraph; -import edu.uci.ics.jung.graph.Graph; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - -/** - * Implementation of NetworkGraphService{@link org.opendaylight.controller.sample.l2switch.md.topology.NetworkGraphService}. - * It uses Jung graph library internally to maintain a graph and optimum way to return shortest path using - * Dijkstra algorithm. - */ -public class NetworkGraphDijkstra implements NetworkGraphService { - - private static final Logger _logger = LoggerFactory.getLogger(NetworkGraphDijkstra.class); - - DijkstraShortestPath shortestPath = null; - Graph networkGraph = null; - - /** - * Adds links to existing graph or creates new directed graph with given links if graph was not initialized. - * @param links - */ - @Override - public synchronized void addLinks(List links) { - if(links == null || links.isEmpty()) { - _logger.info("In addLinks: No link added as links is null or empty."); - return; - } - - if(networkGraph == null) { - networkGraph = new DirectedSparseGraph<>(); - } - - for(Link link : links) { - NodeId sourceNodeId = link.getSource().getSourceNode(); - NodeId destinationNodeId = link.getDestination().getDestNode(); - networkGraph.addVertex(sourceNodeId); - networkGraph.addVertex(destinationNodeId); - networkGraph.addEdge(link, sourceNodeId, destinationNodeId); - } - if(shortestPath == null) { - shortestPath = new DijkstraShortestPath<>(networkGraph); - } else { - shortestPath.reset(); - } - } - - /** - * removes links from existing graph. - * @param links - */ - @Override - public synchronized void removeLinks(List links) { - Preconditions.checkNotNull(networkGraph, "Graph is not initialized, add links first."); - - if(links == null || links.isEmpty()) { - _logger.info("In removeLinks: No link removed as links is null or empty."); - return; - } - - for(Link link : links) { - networkGraph.removeEdge(link); - } - - if(shortestPath == null) { - shortestPath = new DijkstraShortestPath<>(networkGraph); - } else { - shortestPath.reset(); - } - } - - /** - * returns a path between 2 nodes. Uses Dijkstra's algorithm to return shortest path. - * @param sourceNodeId - * @param destinationNodeId - * @return - */ - @Override - public synchronized List getPath(NodeId sourceNodeId, NodeId destinationNodeId) { - Preconditions.checkNotNull(shortestPath, "Graph is not initialized, add links first."); - - if(sourceNodeId == null || destinationNodeId == null) { - _logger.info("In getPath: returning null, as sourceNodeId or destinationNodeId is null."); - return null; - } - - return shortestPath.getPath(sourceNodeId, destinationNodeId); - } - - /** - * Clears the prebuilt graph, in case same service instance is required to process a new graph. - */ - @Override - public synchronized void clear() { - networkGraph = null; - shortestPath = null; - } -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphService.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphService.java deleted file mode 100644 index 173be342c4..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphService.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.topology; - -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link; - -import java.util.List; - -/** - * Service that allows to build a network graph using Topology links - * {@link org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link} - * and exposes operation that can be performed on such graph. - */ -public interface NetworkGraphService { - - /** - * Adds links to existing graph or creates new graph with given links if graph was not initialized. - * @param links - */ - public void addLinks(List links); - - /** - * removes links from existing graph. - * @param links - */ - public void removeLinks(List links); - - /** - * returns a path between 2 nodes. Implementation should ideally return shortest path. - * @param sourceNodeId - * @param destinationNodeId - * @return - */ - public List getPath(NodeId sourceNodeId, NodeId destinationNodeId); - - /** - * Clears the prebuilt graph, in case same service instance is required to process a new graph. - */ - public void clear(); -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/TopologyLinkDataChangeHandler.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/TopologyLinkDataChangeHandler.java deleted file mode 100644 index 254ebf8b4a..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/topology/TopologyLinkDataChangeHandler.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.topology; - -import com.google.common.base.Preconditions; -import org.opendaylight.controller.sample.l2switch.md.util.InstanceIdentifierUtils; -import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent; -import org.opendaylight.controller.sal.binding.api.data.DataBrokerService; -import org.opendaylight.controller.sal.binding.api.data.DataChangeListener; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.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.Link; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -/** - * Listens to data change events on topology links - * {@link org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link} - * and maintains a topology graph using provided NetworkGraphService - * {@link org.opendaylight.controller.sample.l2switch.md.topology.NetworkGraphService}. - * It refreshes the graph after a delay(default 10 sec) to accommodate burst of change events if they come in bulk. - * This is to avoid continuous refresh of graph on a series of change events in short time. - */ -public class TopologyLinkDataChangeHandler implements DataChangeListener { - private static final Logger _logger = LoggerFactory.getLogger(TopologyLinkDataChangeHandler.class); - private static final String DEFAULT_TOPOLOGY_ID = "flow:1"; - - private boolean networkGraphRefreshScheduled = false; - private final ScheduledExecutorService networkGraphRefreshScheduler = Executors.newScheduledThreadPool(1); - private final long DEFAULT_GRAPH_REFRESH_DELAY = 10; - private final long graphRefreshDelayInSec; - - private final NetworkGraphService networkGraphService; - private final DataBrokerService dataBrokerService; - - /** - * Uses default delay to refresh topology graph if this constructor is used. - * @param dataBrokerService - * @param networkGraphService - */ - public TopologyLinkDataChangeHandler(DataBrokerService dataBrokerService, NetworkGraphService networkGraphService) { - Preconditions.checkNotNull(dataBrokerService, "dataBrokerService should not be null."); - Preconditions.checkNotNull(networkGraphService, "networkGraphService should not be null."); - this.dataBrokerService = dataBrokerService; - this.networkGraphService = networkGraphService; - this.graphRefreshDelayInSec = DEFAULT_GRAPH_REFRESH_DELAY; - } - - /** - * - * @param dataBrokerService - * @param networkGraphService - * @param graphRefreshDelayInSec - */ - public TopologyLinkDataChangeHandler(DataBrokerService dataBrokerService, NetworkGraphService networkGraphService, - long graphRefreshDelayInSec) { - Preconditions.checkNotNull(dataBrokerService, "dataBrokerService should not be null."); - Preconditions.checkNotNull(networkGraphService, "networkGraphService should not be null."); - this.dataBrokerService = dataBrokerService; - this.networkGraphService = networkGraphService; - this.graphRefreshDelayInSec = graphRefreshDelayInSec; - } - - /** - * Based on if links have been added or removed in topology data store, schedules a refresh of network graph. - * @param dataChangeEvent - */ - @Override - public void onDataChanged(DataChangeEvent, DataObject> dataChangeEvent) { - if(dataChangeEvent == null) { - _logger.info("In onDataChanged: No Processing done as dataChangeEvent is null."); - } - Map, DataObject> linkOriginalData = dataChangeEvent.getOriginalOperationalData(); - Map, DataObject> linkUpdatedData = dataChangeEvent.getUpdatedOperationalData(); - // change this logic, once MD-SAL start populating DeletedOperationData Set - if(linkOriginalData != null && linkUpdatedData != null - && (linkOriginalData.size() != 0 || linkUpdatedData.size() != 0) - && !networkGraphRefreshScheduled) { - networkGraphRefreshScheduled = linkOriginalData.size() != linkUpdatedData.size(); - if(networkGraphRefreshScheduled) { - networkGraphRefreshScheduler.schedule(new NetworkGraphRefresher(), graphRefreshDelayInSec, TimeUnit.SECONDS); - } - } - - } - - /** - * Registers as a data listener to receive changes done to - * {@link org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link} - * under {@link org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology} - * operation data root. - */ - - public void registerAsDataChangeListener() { - InstanceIdentifier linkInstance = InstanceIdentifier.builder(NetworkTopology.class) - .child(Topology.class, new TopologyKey(new TopologyId(DEFAULT_TOPOLOGY_ID))).child(Link.class).toInstance(); - dataBrokerService.registerDataChangeListener(linkInstance, this); - } - - /** - * - */ - private class NetworkGraphRefresher implements Runnable { - /** - * - */ - @Override - public void run() { - networkGraphRefreshScheduled = false; - //TODO: it should refer to changed links only from DataChangeEvent above. - List links = getLinksFromTopology(DEFAULT_TOPOLOGY_ID); - networkGraphService.clear();// can remove this once changed links are addressed - if(links != null && !links.isEmpty()) { - networkGraphService.addLinks(links); - } - } - - /** - * @param topologyId - * @return - */ - private List getLinksFromTopology(String topologyId) { - InstanceIdentifier topologyInstanceIdentifier = InstanceIdentifierUtils.generateTopologyInstanceIdentifier(topologyId); - Topology topology = (Topology) dataBrokerService.readOperationalData(topologyInstanceIdentifier); - return topology.getLink(); - } - } -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/util/InstanceIdentifierUtils.java b/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/util/InstanceIdentifierUtils.java deleted file mode 100644 index c2be488d93..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/main/java/org/opendaylight/controller/sample/l2switch/md/util/InstanceIdentifierUtils.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.util; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -/* InstanceIdentifierUtils provides utility functions related to InstanceIdentifiers. - */ -public final class InstanceIdentifierUtils { - - private InstanceIdentifierUtils() { - throw new UnsupportedOperationException("Utility class should never be instantiated"); - } - - /** - * Creates an Instance Identifier (path) for node with specified id - * - * @param nodeId - * @return - */ - public static final InstanceIdentifier createNodePath(final NodeId nodeId) { - return InstanceIdentifier.builder(Nodes.class) // - .child(Node.class, new NodeKey(nodeId)) // - .build(); - } - - /** - * Shorten's node child path to node path. - * - * @param nodeChild child of node, from which we want node path. - * @return - */ - public static final InstanceIdentifier getNodePath(final InstanceIdentifier nodeChild) { - return nodeChild.firstIdentifierOf(Node.class); - } - - - /** - * Creates a table path by appending table specific location to node path - * - * @param nodePath - * @param tableKey - * @return - */ - public static final InstanceIdentifier createTablePath(final InstanceIdentifier nodePath, final TableKey tableKey) { - return nodePath.builder() - .augmentation(FlowCapableNode.class) - .child(Table.class, tableKey) - .build(); - } - - /** - * Creates a path for particular flow, by appending flow-specific information - * to table path. - * - * @param table - * @param flowKey - * @return - */ - public static InstanceIdentifier createFlowPath(final InstanceIdentifier
      table, final FlowKey flowKey) { - return table.child(Flow.class, flowKey); - } - - /** - * Extract table id from table path. - * - * @param tablePath - * @return - */ - public static Short getTableId(final InstanceIdentifier
      tablePath) { - return tablePath.firstKeyOf(Table.class, TableKey.class).getId(); - } - - /** - * Extracts NodeConnectorKey from node connector path. - */ - public static NodeConnectorKey getNodeConnectorKey(final InstanceIdentifier nodeConnectorPath) { - return nodeConnectorPath.firstKeyOf(NodeConnector.class, NodeConnectorKey.class); - } - - /** - * Extracts NodeKey from node path. - */ - public static NodeKey getNodeKey(final InstanceIdentifier nodePath) { - return nodePath.firstKeyOf(Node.class, NodeKey.class); - } - - - // - public static final InstanceIdentifier createNodeConnectorIdentifier(final String nodeIdValue, - final String nodeConnectorIdValue) { - return createNodePath(new NodeId(nodeIdValue)) - .child(NodeConnector.class, new NodeConnectorKey(new NodeConnectorId(nodeConnectorIdValue))); - } - - /** - * @param nodeConnectorRef - * @return - */ - public static InstanceIdentifier generateNodeInstanceIdentifier(final NodeConnectorRef nodeConnectorRef) { - return nodeConnectorRef.getValue().firstIdentifierOf(Node.class); - } - - /** - * @param nodeConnectorRef - * @param flowTableKey - * @return - */ - public static InstanceIdentifier
      generateFlowTableInstanceIdentifier(final NodeConnectorRef nodeConnectorRef, final TableKey flowTableKey) { - return generateNodeInstanceIdentifier(nodeConnectorRef).builder() - .augmentation(FlowCapableNode.class) - .child(Table.class, flowTableKey) - .build(); - } - - /** - * @param nodeConnectorRef - * @param flowTableKey - * @param flowKey - * @return - */ - public static InstanceIdentifier generateFlowInstanceIdentifier(final NodeConnectorRef nodeConnectorRef, - final TableKey flowTableKey, - final FlowKey flowKey) { - return generateFlowTableInstanceIdentifier(nodeConnectorRef, flowTableKey).child(Flow.class, flowKey); - } - - public static InstanceIdentifier generateTopologyInstanceIdentifier(final String topologyId) { - return InstanceIdentifier.builder(NetworkTopology.class) - .child(Topology.class, new TopologyKey(new TopologyId(topologyId))) - .build(); - } -} - diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterServiceImplTest.java b/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterServiceImplTest.java deleted file mode 100644 index 50f74cc33f..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/flow/FlowWriterServiceImplTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.flow; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.sal.binding.api.data.DataBrokerService; -import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction; -import org.opendaylight.controller.sample.l2switch.md.topology.NetworkGraphService; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -/** - */ -public class FlowWriterServiceImplTest { - private DataBrokerService dataBrokerService; - private NodeConnectorRef srcNodeConnectorRef; - private NodeConnectorRef destNodeConnectorRef; - private MacAddress destMacAddress; - private MacAddress srcMacAddress; - private DataModificationTransaction dataModificationTransaction; - private NetworkGraphService networkGraphService; - - @Before - public void init() { - dataBrokerService = mock(DataBrokerService.class); - networkGraphService = mock(NetworkGraphService.class); - //build source node connector ref - InstanceIdentifier srcNodesInstanceIdentifier = InstanceIdentifier.create(Nodes.class); - InstanceIdentifier srcNodeInstanceIdentifier = srcNodesInstanceIdentifier - .child(Node.class, new NodeKey(new NodeId("openflow:1"))); - InstanceIdentifier srcNodeConnectorInstanceIdentifier = srcNodeInstanceIdentifier - .child(NodeConnector.class, new NodeConnectorKey(new NodeConnectorId("openflow:1:2"))); - srcNodeConnectorRef = new NodeConnectorRef(srcNodeConnectorInstanceIdentifier); - - //build dest node connector ref - InstanceIdentifier nodesInstanceIdentifier - = InstanceIdentifier.builder(Nodes.class) - .build(); - InstanceIdentifier nodeInstanceIdentifier = - nodesInstanceIdentifier.child(Node.class, new NodeKey(new NodeId("openflow:2"))); - InstanceIdentifier nodeConnectorInstanceIdentifier = - nodeInstanceIdentifier.child(NodeConnector.class, new NodeConnectorKey(new NodeConnectorId("openflow:2:2"))); - destNodeConnectorRef = new NodeConnectorRef(nodeConnectorInstanceIdentifier); - destMacAddress = new MacAddress("00:0a:95:9d:68:16"); - srcMacAddress = new MacAddress("00:0a:95:8c:97:24"); - dataModificationTransaction = mock(DataModificationTransaction.class); - when(dataBrokerService.beginTransaction()).thenReturn(dataModificationTransaction); - } - - @Test - public void testFlowWriterServiceImpl_NPEWhenDataBrokerServiceIsNull() throws Exception { - try { - new FlowWriterServiceImpl(null, networkGraphService); - fail("Expected null pointer exception."); - } catch(NullPointerException npe) { - assertEquals("dataBrokerService should not be null.", npe.getMessage()); - } - } - - @Test - public void testAddMacToMacFlow_NPEWhenNullSourceMacDestMacAndNodeConnectorRef() throws Exception { - FlowWriterService flowWriterService = new FlowWriterServiceImpl(dataBrokerService, networkGraphService); - try { - flowWriterService.addMacToMacFlow(null, null, null); - fail("Expected null pointer exception."); - } catch(NullPointerException npe) { - assertEquals("Destination mac address should not be null.", npe.getMessage()); - } - } - - @Test - public void testAddMacToMacFlow_NPEWhenSourceMacNullMac() throws Exception { - FlowWriterService flowWriterService = new FlowWriterServiceImpl(dataBrokerService, networkGraphService); - try { - flowWriterService.addMacToMacFlow(null, null, destNodeConnectorRef); - fail("Expected null pointer exception."); - } catch(NullPointerException npe) { - assertEquals("Destination mac address should not be null.", npe.getMessage()); - } - } - - @Test - public void testAddMacToMacFlow_NPEWhenNullSourceMacNodeConnectorRef() throws Exception { - FlowWriterService flowWriterService = new FlowWriterServiceImpl(dataBrokerService, networkGraphService); - try { - flowWriterService.addMacToMacFlow(null, destMacAddress, null); - fail("Expected null pointer exception."); - } catch(NullPointerException npe) { - assertEquals("Destination port should not be null.", npe.getMessage()); - } - } - - @Test - public void testAddMacToMacFlow_WhenNullSourceMac() throws Exception { - FlowWriterService flowWriterService = new FlowWriterServiceImpl(dataBrokerService, networkGraphService); - flowWriterService.addMacToMacFlow(null, destMacAddress, destNodeConnectorRef); - verify(dataBrokerService, times(1)).beginTransaction(); - verify(dataModificationTransaction, times(1)).commit(); - } - - @Test - public void testAddMacToMacFlow_WhenSrcAndDestMacAreSame() throws Exception { - FlowWriterService flowWriterService = new FlowWriterServiceImpl(dataBrokerService, networkGraphService); - flowWriterService.addMacToMacFlow(new MacAddress(destMacAddress.getValue()), destMacAddress, destNodeConnectorRef); - verify(dataBrokerService, never()).beginTransaction(); - verify(dataModificationTransaction, never()).commit(); - - } - - @Test - public void testAddMacToMacFlow_SunnyDay() throws Exception { - FlowWriterService flowWriterService = new FlowWriterServiceImpl(dataBrokerService, networkGraphService); - flowWriterService.addMacToMacFlow(srcMacAddress, destMacAddress, destNodeConnectorRef); - verify(dataBrokerService, times(1)).beginTransaction(); - verify(dataModificationTransaction, times(1)).commit(); - } - -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphDijkstraTest.java b/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphDijkstraTest.java deleted file mode 100644 index 3669a5c979..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/topology/NetworkGraphDijkstraTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.topology; - -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.link.attributes.Destination; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.link.attributes.Source; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link; - -import java.util.ArrayList; -import java.util.List; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - */ -public class NetworkGraphDijkstraTest { - Link link1, link2, link3, link4, link5, link6, link7, link8, link9, link10,link11,link12; - Destination dest1, dest2, dest3, dest4, dest5, dest6,dest7,dest8,dest9,dest10,dest11,dest12; - Source src1, src2, src3, src4, src5, src6,src7,src8,src9,src10,src11,src12; - NodeId nodeId1 = new NodeId("openflow:1"); - NodeId nodeId2 = new NodeId("openflow:2"); - NodeId nodeId3 = new NodeId("openflow:3"); - NodeId nodeId4 = new NodeId("openflow:4"); - NodeId nodeId5 = new NodeId("openflow:5"); - NodeId nodeId6 = new NodeId("openflow:6"); - NodeId nodeId7 = new NodeId("openflow:7"); - List links = new ArrayList<>(); - - @Before - public void init() { - link1 = mock(Link.class); - link2 = mock(Link.class); - link3 = mock(Link.class); - link4 = mock(Link.class); - link5 = mock(Link.class); - link6 = mock(Link.class); - link7 = mock(Link.class); - link8 = mock(Link.class); - link9 = mock(Link.class); - link10 = mock(Link.class); - link11 = mock(Link.class); - link12 = mock(Link.class); - dest1 = mock(Destination.class); - dest2 = mock(Destination.class); - dest3 = mock(Destination.class); - dest4 = mock(Destination.class); - dest5 = mock(Destination.class); - dest6 = mock(Destination.class); - dest7 = mock(Destination.class); - dest8 = mock(Destination.class); - dest9 = mock(Destination.class); - dest10 = mock(Destination.class); - dest11 = mock(Destination.class); - dest12 = mock(Destination.class); - src1 = mock(Source.class); - src2 = mock(Source.class); - src3 = mock(Source.class); - src4 = mock(Source.class); - src5 = mock(Source.class); - src6 = mock(Source.class); - src7 = mock(Source.class); - src8 = mock(Source.class); - src9 = mock(Source.class); - src10 = mock(Source.class); - src11 = mock(Source.class); - src12 = mock(Source.class); - when(link1.getSource()).thenReturn(src1); - when(link2.getSource()).thenReturn(src2); - when(link3.getSource()).thenReturn(src3); - when(link4.getSource()).thenReturn(src4); - when(link5.getSource()).thenReturn(src5); - when(link6.getSource()).thenReturn(src6); - when(link7.getSource()).thenReturn(src7); - when(link8.getSource()).thenReturn(src8); - when(link9.getSource()).thenReturn(src9); - when(link10.getSource()).thenReturn(src10); - when(link11.getSource()).thenReturn(src11); - when(link12.getSource()).thenReturn(src12); - when(link1.getDestination()).thenReturn(dest1); - when(link2.getDestination()).thenReturn(dest2); - when(link3.getDestination()).thenReturn(dest3); - when(link4.getDestination()).thenReturn(dest4); - when(link5.getDestination()).thenReturn(dest5); - when(link6.getDestination()).thenReturn(dest6); - when(link7.getDestination()).thenReturn(dest7); - when(link8.getDestination()).thenReturn(dest8); - when(link9.getDestination()).thenReturn(dest9); - when(link10.getDestination()).thenReturn(dest10); - when(link11.getDestination()).thenReturn(dest11); - when(link12.getDestination()).thenReturn(dest12); - when(src1.getSourceNode()).thenReturn(nodeId1); - when(dest1.getDestNode()).thenReturn(nodeId2); - when(src2.getSourceNode()).thenReturn(nodeId2); - when(dest2.getDestNode()).thenReturn(nodeId1); - when(src3.getSourceNode()).thenReturn(nodeId1); - when(dest3.getDestNode()).thenReturn(nodeId3); - when(src4.getSourceNode()).thenReturn(nodeId3); - when(dest4.getDestNode()).thenReturn(nodeId1); - when(src5.getSourceNode()).thenReturn(nodeId2); - when(dest5.getDestNode()).thenReturn(nodeId4); - when(src6.getSourceNode()).thenReturn(nodeId4); - when(dest6.getDestNode()).thenReturn(nodeId2); - when(src7.getSourceNode()).thenReturn(nodeId2); - when(dest7.getDestNode()).thenReturn(nodeId5); - when(src8.getSourceNode()).thenReturn(nodeId5); - when(dest8.getDestNode()).thenReturn(nodeId2); - when(src9.getSourceNode()).thenReturn(nodeId6); - when(dest9.getDestNode()).thenReturn(nodeId3); - when(src10.getSourceNode()).thenReturn(nodeId3); - when(dest10.getDestNode()).thenReturn(nodeId6); - when(src11.getSourceNode()).thenReturn(nodeId7); - when(dest11.getDestNode()).thenReturn(nodeId3); - when(src12.getSourceNode()).thenReturn(nodeId3); - when(dest12.getDestNode()).thenReturn(nodeId7); - links.add(link1); - links.add(link2); - links.add(link3); - links.add(link4); - links.add(link5); - links.add(link6); - links.add(link7); - links.add(link8); - links.add(link9); - links.add(link10); - links.add(link11); - links.add(link12); - - } - - @Test - public void testAddLinksAndGetPath() throws Exception { - NetworkGraphService networkGraphService = new NetworkGraphDijkstra(); - networkGraphService.addLinks(links); - List path = networkGraphService.getPath(nodeId2, nodeId3); - assertEquals("path size is not as expected.", 2, path.size()); - assertEquals("link source is not as expected.", nodeId2, path.get(0).getSource().getSourceNode()); - assertEquals("link destination is not as expected.", nodeId1, path.get(0).getDestination().getDestNode()); - path = networkGraphService.getPath(nodeId3, nodeId2); - assertEquals("path size is not as expected.", 2, path.size()); - assertEquals("link source is not as expected.", nodeId3, path.get(0).getSource().getSourceNode()); - assertEquals("link destination is not as expected.", nodeId1, path.get(0).getDestination().getDestNode()); - - path = networkGraphService.getPath(nodeId4, nodeId6); - assertEquals("path size is not as expected.", 4, path.size()); - assertEquals("link source is not as expected.", nodeId4, path.get(0).getSource().getSourceNode()); - assertEquals("link destination is not as expected.", nodeId2, path.get(0).getDestination().getDestNode()); - } -} diff --git a/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/topology/TopologyLinkDataChangeHandlerTest.java b/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/topology/TopologyLinkDataChangeHandlerTest.java deleted file mode 100644 index 9ecd25651a..0000000000 --- a/opendaylight/md-sal/samples/l2switch/implementation/src/test/java/org/opendaylight/controller/sample/l2switch/md/topology/TopologyLinkDataChangeHandlerTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sample.l2switch.md.topology; - -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.sample.l2switch.md.util.InstanceIdentifierUtils; -import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent; -import org.opendaylight.controller.sal.binding.api.data.DataBrokerService; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; -import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - */ -public class TopologyLinkDataChangeHandlerTest { - NetworkGraphService networkGraphService; - DataBrokerService dataBrokerService; - DataChangeEvent dataChangeEvent; - Topology topology; - Link link; - - @Before - public void init() { - networkGraphService = mock(NetworkGraphService.class); - dataBrokerService = mock(DataBrokerService.class); - dataChangeEvent = mock(DataChangeEvent.class); - link = mock(Link.class); - topology = mock(Topology.class); - } - - @Test - public void testOnDataChange() throws Exception { - TopologyLinkDataChangeHandler topologyLinkDataChangeHandler = new TopologyLinkDataChangeHandler(dataBrokerService, networkGraphService, 2); - Map, DataObject> original = new HashMap, DataObject>(); - InstanceIdentifier instanceIdentifier = InstanceIdentifierUtils.generateTopologyInstanceIdentifier("flow:1"); - DataObject dataObject = mock(DataObject.class); - Map, DataObject> updated = new HashMap, DataObject>(); - updated.put(instanceIdentifier, dataObject); - when(dataChangeEvent.getUpdatedOperationalData()).thenReturn(updated); - when(dataChangeEvent.getOriginalOperationalData()).thenReturn(original); - List links = new ArrayList<>(); - links.add(link); - when(dataBrokerService.readOperationalData(instanceIdentifier)).thenReturn(topology); - when(topology.getLink()).thenReturn(links); - - topologyLinkDataChangeHandler.onDataChanged(dataChangeEvent); - Thread.sleep(2100); - verify(networkGraphService, times(1)).addLinks(links); - } -} diff --git a/opendaylight/md-sal/samples/l2switch/model/pom.xml b/opendaylight/md-sal/samples/l2switch/model/pom.xml deleted file mode 100644 index fa35c1f6cd..0000000000 --- a/opendaylight/md-sal/samples/l2switch/model/pom.xml +++ /dev/null @@ -1,94 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller.samples - sal-samples - 1.2.0-SNAPSHOT - ../.. - - org.opendaylight.controller.samples.l2switch.md - l2switch-model - bundle - - - - org.opendaylight.controller.model - model-inventory - - - org.opendaylight.yangtools - yang-binding - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.yangtools.model - ietf-yang-types - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.groupId}.${project.artifactId} - org.opendaylight.yangtools.yang.binding.annotations, * - ${project.basedir}/META-INF - - - - - org.opendaylight.yangtools - yang-maven-plugin - ${yangtools.version} - - - org.opendaylight.yangtools - maven-sal-api-gen-plugin - ${yangtools.version} - jar - - - org.opendaylight.yangtools - yang-binding - ${yangtools.version} - jar - - - - - - generate-sources - - - src/main/yang - - - org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl - ${salGeneratorPath} - - - org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl - target/site/models - - - org.opendaylight.yangtools.yang.wadl.generator.maven.WadlGenerator - target/site/models - - - true - - - - - - - - diff --git a/opendaylight/md-sal/samples/l2switch/model/src/main/yang/l2-address-tracker.yang b/opendaylight/md-sal/samples/l2switch/model/src/main/yang/l2-address-tracker.yang deleted file mode 100644 index d694c6883d..0000000000 --- a/opendaylight/md-sal/samples/l2switch/model/src/main/yang/l2-address-tracker.yang +++ /dev/null @@ -1,45 +0,0 @@ -module l2-address-tracker { - yang-version 1; - namespace "urn:opendaylight:l2-address-tracker"; - prefix l2-address-tracker; - - import ietf-yang-types { - prefix yang; - revision-date 2010-09-24; - } - import opendaylight-inventory { - prefix inv; - revision-date 2013-08-19; - } - - organization "Cisco Systems Inc"; - contact - "Alex Fan "; - description - "YANG version of the L2 Address Tracker Data Model"; - - revision 2014-04-02 { - description - "L2 Address Tracker module draft."; - } - - grouping l2-address { - leaf mac { - type yang:mac-address; - mandatory true; - description - "the mac address of the host."; - } - leaf node-connector-ref { - type inv:node-connector-ref; - } - } - - container l2-addresses { - config false; - list l2-address { - key "mac"; - uses l2-address; - } - } -} \ No newline at end of file diff --git a/opendaylight/md-sal/samples/l2switch/pom.xml b/opendaylight/md-sal/samples/l2switch/pom.xml deleted file mode 100644 index 6a715c74ab..0000000000 --- a/opendaylight/md-sal/samples/l2switch/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - - - org.opendaylight.controller.samples - sal-samples - 1.2.0-SNAPSHOT - - - l2switch.aggregator - org.opendaylight.controller.samples.l2switch - 1.1.0-SNAPSHOT - pom - - - model - implementation - - - diff --git a/opendaylight/md-sal/samples/pom.xml b/opendaylight/md-sal/samples/pom.xml index 6070c72472..378b03318a 100644 --- a/opendaylight/md-sal/samples/pom.xml +++ b/opendaylight/md-sal/samples/pom.xml @@ -16,7 +16,6 @@ toaster-consumer toaster-provider toaster-config - l2switch clustering-test-app diff --git a/opendaylight/md-sal/samples/toaster-provider/src/main/java/org/opendaylight/controller/sample/toaster/provider/OpendaylightToaster.java b/opendaylight/md-sal/samples/toaster-provider/src/main/java/org/opendaylight/controller/sample/toaster/provider/OpendaylightToaster.java index b7518e094d..332d375282 100644 --- a/opendaylight/md-sal/samples/toaster-provider/src/main/java/org/opendaylight/controller/sample/toaster/provider/OpendaylightToaster.java +++ b/opendaylight/md-sal/samples/toaster-provider/src/main/java/org/opendaylight/controller/sample/toaster/provider/OpendaylightToaster.java @@ -141,6 +141,8 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti { darknessFactor.set( darkness ); } + + LOG.info("onDataChanged - new Toaster config: {}", toaster); } } diff --git a/opendaylight/md-sal/statistics-manager/pom.xml b/opendaylight/md-sal/statistics-manager/pom.xml index 1a443177c6..eb6c51b351 100644 --- a/opendaylight/md-sal/statistics-manager/pom.xml +++ b/opendaylight/md-sal/statistics-manager/pom.xml @@ -45,7 +45,6 @@ org.slf4j slf4j-log4j12 - ${slf4j.version} test diff --git a/opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/impl/StatAbstractListenCommit.java b/opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/impl/StatAbstractListenCommit.java index 6db73d5ddc..10bfcba678 100644 --- a/opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/impl/StatAbstractListenCommit.java +++ b/opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/impl/StatAbstractListenCommit.java @@ -123,6 +123,8 @@ public abstract class StatAbstractListenCommit Optional readLatestConfiguration(final InstanceIdentifier path) { diff --git a/opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/impl/StatisticsManagerImpl.java b/opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/impl/StatisticsManagerImpl.java index 0f8030f620..ca0e5b20ed 100644 --- a/opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/impl/StatisticsManagerImpl.java +++ b/opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/impl/StatisticsManagerImpl.java @@ -124,6 +124,7 @@ public class StatisticsManagerImpl implements StatisticsManager, Runnable { @Override public void close() throws Exception { + LOG.info("StatisticsManager close called"); finishing = true; if (nodeRegistrator != null) { nodeRegistrator.close(); diff --git a/opendaylight/netconf/config-netconf-connector/pom.xml b/opendaylight/netconf/config-netconf-connector/pom.xml index edba4e11da..2b3015243f 100644 --- a/opendaylight/netconf/config-netconf-connector/pom.xml +++ b/opendaylight/netconf/config-netconf-connector/pom.xml @@ -106,32 +106,7 @@ org.opendaylight.controller.netconf.confignetconfconnector.util, org.opendaylight.controller.netconf.confignetconfconnector.osgi, org.opendaylight.controller.netconf.confignetconfconnector.exception, - com.google.common.base, - com.google.common.collect, - javax.annotation, - javax.management, - javax.management.openmbean, - org.opendaylight.controller.config.api, - org.opendaylight.controller.config.api.jmx, - org.opendaylight.controller.config.yangjmxgenerator, - org.opendaylight.controller.config.yangjmxgenerator.attribute, - org.opendaylight.controller.netconf.api, - org.opendaylight.controller.netconf.mapping.api, - org.opendaylight.controller.netconf.util.mapping, - org.opendaylight.controller.netconf.util.xml, - org.opendaylight.controller.netconf.util.exception, - org.opendaylight.yangtools.yang.common, - org.opendaylight.yangtools.yang.model.api, - org.osgi.framework, - org.osgi.util.tracker, - org.slf4j, - org.w3c.dom, - com.google.common.io, - org.opendaylight.yangtools.yang.model.api.type, - org.opendaylight.yangtools.sal.binding.generator.spi, - org.opendaylight.yangtools.sal.binding.yang.types, - org.opendaylight.controller.config.util - + * diff --git a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleCompositeAttributeWritingStrategy.java b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleCompositeAttributeWritingStrategy.java index 10b643f9f4..47fbc6ddcf 100644 --- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleCompositeAttributeWritingStrategy.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleCompositeAttributeWritingStrategy.java @@ -26,8 +26,8 @@ public class SimpleCompositeAttributeWritingStrategy extends SimpleAttributeWrit protected Object preprocess(Object value) { Util.checkType(value, Map.class); - Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value); - return ((Map)value).values().iterator().next(); + Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value); + return ((Map)value).values().iterator().next(); } } diff --git a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleIdentityRefAttributeWritingStrategy.java b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleIdentityRefAttributeWritingStrategy.java index 104bf4df94..1e5d2bb8d9 100644 --- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleIdentityRefAttributeWritingStrategy.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleIdentityRefAttributeWritingStrategy.java @@ -33,8 +33,8 @@ public class SimpleIdentityRefAttributeWritingStrategy extends SimpleAttributeWr protected Object preprocess(Object value) { Util.checkType(value, Map.class); - Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value); - Object stringValue = ((Map) value).values().iterator().next(); + Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value); + Object stringValue = ((Map) value).values().iterator().next(); Util.checkType(stringValue, String.class); return stringValue; diff --git a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleUnionAttributeWritingStrategy.java b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleUnionAttributeWritingStrategy.java index d75feb273e..4802cba7af 100644 --- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleUnionAttributeWritingStrategy.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/toxml/SimpleUnionAttributeWritingStrategy.java @@ -27,12 +27,12 @@ public class SimpleUnionAttributeWritingStrategy extends SimpleAttributeWritingS protected Object preprocess(Object value) { Util.checkType(value, Map.class); - Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value); - Object listOfStrings = ((Map) value).values().iterator().next(); + Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value); + Object listOfStrings = ((Map) value).values().iterator().next(); Util.checkType(listOfStrings, List.class); StringBuilder b = new StringBuilder(); - for (Object character: (List)listOfStrings) { + for (Object character: (List)listOfStrings) { Util.checkType(character, String.class); b.append(character); } diff --git a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpcElementResolved.java b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpcElementResolved.java index 7fd8928928..551da722c0 100644 --- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpcElementResolved.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpcElementResolved.java @@ -8,20 +8,23 @@ package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc; -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import com.google.common.collect.Maps; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.management.ObjectName; import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.ModuleRpcs; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.Modules; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.modules.Module; -import javax.management.ObjectName; - -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.base.Strings; +import com.google.common.collect.Maps; /** * Represents parsed xpath to runtime bean instance @@ -46,6 +49,11 @@ public final class RuntimeRpcElementResolved { return moduleName; } + @VisibleForTesting + Map getAdditionalAttributes() { + return additionalAttributes; + } + public String getInstanceName() { return instanceName; } @@ -70,22 +78,45 @@ public final class RuntimeRpcElementResolved { return ObjectNameUtil.createRuntimeBeanName(moduleName, instanceName, additionalAttributesJavaNames); } + /** + * Pattern for an absolute instance identifier xpath pointing to a runtime bean instance e.g: + *
      +     * /modules/module[name=instanceName][type=moduleType]
      +     * 
      + * or + *
      +     * /a:modules/a:module[a:name=instanceName][a:type=moduleType]
      +     * 
      + */ private static final String xpathPatternBlueprint = - "/" + XmlNetconfConstants.MODULES_KEY - + "/" + XmlNetconfConstants.MODULE_KEY - + "\\[" - - + "(?type|name)" - + "='(?[^']+)'" - + "( and |\\]\\[)" - + "(?type|name)" - + "='(?[^']+)'" - - + "\\]" - + "(?.*)"; + "/" + getRegExForPrefixedName(Modules.QNAME.getLocalName())+ "/" + getRegExForPrefixedName(Module.QNAME.getLocalName()) + + + "\\[" + + "(?" + getRegExForPrefixedName(XmlNetconfConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlNetconfConstants.NAME_KEY) + ")" + + "=('|\")?(?[^'\"\\]]+)('|\")?" + + "( and |\\]\\[)" + + "(?" + getRegExForPrefixedName(XmlNetconfConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlNetconfConstants.NAME_KEY) + ")" + + "=('|\")?(?[^'\"\\]]+)('|\")?" + + "\\]" + + + "(?.*)"; + + /** + * Return reg ex that matches either the name with or without a prefix + */ + private static String getRegExForPrefixedName(final String name) { + return "([^:]+:)?" + name; + } private static final Pattern xpathPattern = Pattern.compile(xpathPatternBlueprint); - private static final String additionalPatternBlueprint = "(?.+)\\[(.+)='(?.+)'\\]"; + + /** + * Pattern for additional path elements inside xpath for instance identifier pointing to an inner runtime bean e.g: + *
      +     * /modules/module[name=instanceName and type=moduleType]/inner[key=b]
      +     * 
      + */ + private static final String additionalPatternBlueprint = getRegExForPrefixedName("(?.+)") + "\\[(?" + getRegExForPrefixedName("(.+)") + ")=('|\")?(?[^'\"\\]]+)('|\")?\\]"; private static final Pattern additionalPattern = Pattern.compile(additionalPatternBlueprint); public static RuntimeRpcElementResolved fromXpath(String xpath, String elementName, String namespace) { @@ -115,20 +146,19 @@ public final class RuntimeRpcElementResolved { PatternGroupResolver(String key1, String value1, String value2, String additional) { this.key1 = Preconditions.checkNotNull(key1); this.value1 = Preconditions.checkNotNull(value1); - this.value2 = Preconditions.checkNotNull(value2); - this.additional = Preconditions.checkNotNull(additional); } String getModuleName() { - return key1.equals(XmlNetconfConstants.TYPE_KEY) ? value1 : value2; + return key1.contains(XmlNetconfConstants.TYPE_KEY) ? value1 : value2; } String getInstanceName() { - return key1.equals(XmlNetconfConstants.NAME_KEY) ? value1 : value2; + return key1.contains(XmlNetconfConstants.NAME_KEY) ? value1 : value2; } + Map getAdditionalKeys(String elementName, String moduleName) { HashMap additionalAttributes = Maps.newHashMap(); @@ -141,7 +171,7 @@ public final class RuntimeRpcElementResolved { Preconditions .checkState( matcher.matches(), - "Attribute %s not in required form on rpc element %s, required format for additional attributes is %s", + "Attribute %s not in required form on rpc element %s, required format for additional attributes is: %s", additionalKeyValue, elementName, additionalPatternBlueprint); String name = matcher.group("additionalKey"); runtimeBeanYangName = name; diff --git a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/Activator.java b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/Activator.java index 3ba92b092e..99f9c04fcc 100644 --- a/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/Activator.java +++ b/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/Activator.java @@ -29,7 +29,7 @@ public class Activator implements BundleActivator { private static final Logger logger = LoggerFactory.getLogger(Activator.class); private BundleContext context; - private ServiceRegistration osgiRegistration; + private ServiceRegistration osgiRegistration; private ConfigRegistryLookupThread configRegistryLookup = null; @Override diff --git a/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/NetconfMappingTest.java b/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/NetconfMappingTest.java index 641881cf9e..28849d0033 100644 --- a/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/NetconfMappingTest.java +++ b/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/NetconfMappingTest.java @@ -55,10 +55,10 @@ import org.custommonkey.xmlunit.NodeTestException; import org.custommonkey.xmlunit.NodeTester; import org.custommonkey.xmlunit.XMLAssert; import org.custommonkey.xmlunit.XMLUnit; +import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; -import org.junit.matchers.JUnitMatchers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.opendaylight.controller.config.api.ConflictingVersionException; @@ -569,7 +569,7 @@ public class NetconfMappingTest extends AbstractConfigTest { } private void assertContainsString(String string, String substring) { - assertThat(string, JUnitMatchers.containsString(substring)); + assertThat(string, CoreMatchers.containsString(substring)); } private void checkEnum(final Document response) throws Exception { diff --git a/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpcElementResolvedTest.java b/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpcElementResolvedTest.java new file mode 100644 index 0000000000..3c4213cbc3 --- /dev/null +++ b/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpcElementResolvedTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc; + +import static org.junit.Assert.assertEquals; +import com.google.common.collect.ImmutableMap; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class RuntimeRpcElementResolvedTest { + + private static final String MODULE_TYPE = "moduleType"; + private static final String INSTANCE_NAME = "instanceName"; + @Parameterized.Parameter(0) + public String xpath; + @Parameterized.Parameter(1) + public Map additional; + + @Parameterized.Parameters(name = "{index}: parsed({0}) contains moduleName:{1} and instanceName:{2}") + public static Collection data() { + return Arrays.asList(new Object[][] { + // With namespaces + { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']", + new HashMap<>(ImmutableMap.of("listener-state", "127.0.0.1"))}, + { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']", + null}, + + // Without namespaces + { "/modules/module[name=instanceName][type=moduleType]", null}, + { "/modules/module[type=moduleType][name='instanceName']", null}, + { "/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null}, + { "/modules/module[type=moduleType and name=instanceName]", null}, + { "/modules/module[name=\"instanceName\" and type=moduleType]", null}, + { "/modules/module[type=\"moduleType\" and name=instanceName]", null}, + { "/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null}, + + // With inner beans + { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]", Collections.singletonMap("inner", "b")}, + { "/modules/module[name=instanceName and type=moduleType]/inner[key=b]", Collections.singletonMap("inner", "b")}, + { "/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']", Collections.singletonMap("inner", "b")}, + { "/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]", Collections.singletonMap("inner", "b")}, + + { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]", + new HashMap<>(ImmutableMap.of("inner", "a", "inner2", "b")) + }, + }); + } + + @Test + public void testFromXpath() throws Exception { + final RuntimeRpcElementResolved resolved = RuntimeRpcElementResolved.fromXpath(xpath, "element", "namespace"); + assertEquals(MODULE_TYPE, resolved.getModuleName()); + assertEquals(INSTANCE_NAME, resolved.getInstanceName()); + if (additional != null) { + assertEquals(additional, resolved.getAdditionalAttributes()); + } + } +} diff --git a/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImplTest.java b/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImplTest.java index 1e650c08b1..b051c6c1c6 100644 --- a/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImplTest.java +++ b/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImplTest.java @@ -24,7 +24,7 @@ import java.util.Set; import org.junit.Assert; import org.junit.Test; -import org.junit.matchers.JUnitMatchers; +import org.hamcrest.CoreMatchers; import org.opendaylight.controller.config.api.LookupRegistry; import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry; import org.opendaylight.yangtools.yang.common.QName; @@ -72,11 +72,11 @@ public class NetconfOperationServiceImplTest { String message = e.getMessage(); Assert.assertThat( message, - JUnitMatchers + CoreMatchers .containsString("missing from config subsystem but present in yangstore: [(namespace?revision=1970-01-01)qname2]")); Assert.assertThat( message, - JUnitMatchers + CoreMatchers .containsString("All modules present in config: [(namespace?revision=1970-01-01)qname1]")); } } diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/CapabilityStrippingConfigSnapshotHolder.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/CapabilityStrippingConfigSnapshotHolder.java index ab353e349b..eac58cbd7f 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/CapabilityStrippingConfigSnapshotHolder.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/CapabilityStrippingConfigSnapshotHolder.java @@ -9,6 +9,12 @@ package org.opendaylight.controller.netconf.persist.impl; import com.google.common.annotations.VisibleForTesting; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map.Entry; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.netconf.util.xml.XmlElement; import org.opendaylight.controller.netconf.util.xml.XmlUtil; @@ -17,19 +23,12 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Attr; import org.w3c.dom.Element; -import java.util.Collections; -import java.util.HashSet; -import java.util.Map.Entry; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - /** * Inspects snapshot xml to be stored, remove all capabilities that are not referenced by it. * Useful when persisting current configuration. */ public class CapabilityStrippingConfigSnapshotHolder implements ConfigSnapshotHolder { - private static final Logger logger = LoggerFactory.getLogger(CapabilityStrippingConfigSnapshotHolder.class); + private static final Logger LOG = LoggerFactory.getLogger(CapabilityStrippingConfigSnapshotHolder.class); private final String configSnapshot; private final StripCapabilitiesResult stripCapabilitiesResult; @@ -54,7 +53,7 @@ public class CapabilityStrippingConfigSnapshotHolder implements ConfigSnapshotHo static StripCapabilitiesResult stripCapabilities(XmlElement configElement, Set allCapabilitiesFromHello) { // collect all namespaces Set foundNamespacesInXML = getNamespaces(configElement); - logger.trace("All capabilities {}\nFound namespaces in XML {}", allCapabilitiesFromHello, foundNamespacesInXML); + LOG.trace("All capabilities {}\nFound namespaces in XML {}", allCapabilitiesFromHello, foundNamespacesInXML); // required are referenced both in xml and hello SortedSet requiredCapabilities = new TreeSet<>(); // can be removed @@ -68,7 +67,7 @@ public class CapabilityStrippingConfigSnapshotHolder implements ConfigSnapshotHo } } - logger.trace("Required capabilities {}, \nObsolete capabilities {}", + LOG.trace("Required capabilities {}, \nObsolete capabilities {}", requiredCapabilities, obsoleteCapabilities); return new StripCapabilitiesResult(requiredCapabilities, obsoleteCapabilities); diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java index d72c26cb77..7618807a0e 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java @@ -8,21 +8,20 @@ package org.opendaylight.controller.netconf.persist.impl; -import org.opendaylight.controller.config.persist.api.Persister; -import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification; -import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean; -import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import java.io.Closeable; +import java.io.IOException; import javax.annotation.concurrent.ThreadSafe; import javax.management.InstanceNotFoundException; import javax.management.MBeanServerConnection; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; -import java.io.Closeable; -import java.io.IOException; +import org.opendaylight.controller.config.persist.api.Persister; +import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification; +import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean; +import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Responsible for listening for notifications from netconf (via JMX) containing latest @@ -32,7 +31,7 @@ import java.io.IOException; @ThreadSafe public class ConfigPersisterNotificationHandler implements Closeable { - private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class); + private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class); private final MBeanServerConnection mBeanServerConnection; private final NotificationListener listener; @@ -48,7 +47,7 @@ public class ConfigPersisterNotificationHandler implements Closeable { } private static void registerAsJMXListener(final MBeanServerConnection mBeanServerConnection, final NotificationListener listener) { - logger.trace("Called registerAsJMXListener"); + LOG.trace("Called registerAsJMXListener"); try { mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.OBJECT_NAME, listener, null, null); } catch (InstanceNotFoundException | IOException e) { @@ -65,13 +64,13 @@ public class ConfigPersisterNotificationHandler implements Closeable { mBeanServerConnection.removeNotificationListener(on, listener); } } catch (final Exception e) { - logger.warn("Unable to unregister {} as listener for {}", listener, on, e); + LOG.warn("Unable to unregister {} as listener for {}", listener, on, e); } } } class ConfigPersisterNotificationListener implements NotificationListener { - private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationListener.class); + private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterNotificationListener.class); private final Persister persisterAggregator; @@ -87,14 +86,14 @@ class ConfigPersisterNotificationListener implements NotificationListener { // Socket should not be closed at this point // Activator unregisters this as JMX listener before close is called - logger.trace("Received notification {}", notification); + LOG.trace("Received notification {}", notification); if (notification instanceof CommitJMXNotification) { try { handleAfterCommitNotification((CommitJMXNotification) notification); } catch (final Exception e) { // log exceptions from notification Handler here since // notificationBroadcastSupport logs only DEBUG level - logger.warn("Failed to handle notification {}", notification, e); + LOG.warn("Failed to handle notification {}", notification, e); throw e; } } else { @@ -106,7 +105,7 @@ class ConfigPersisterNotificationListener implements NotificationListener { try { persisterAggregator.persistConfig(new CapabilityStrippingConfigSnapshotHolder(notification.getConfigSnapshot(), notification.getCapabilities())); - logger.trace("Configuration persisted successfully"); + LOG.trace("Configuration persisted successfully"); } catch (final IOException e) { throw new RuntimeException("Unable to persist configuration snapshot", e); } diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusherImpl.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusherImpl.java index b346522f44..b06219c978 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusherImpl.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusherImpl.java @@ -53,7 +53,7 @@ import org.xml.sax.SAXException; @Immutable public class ConfigPusherImpl implements ConfigPusher { - private static final Logger logger = LoggerFactory.getLogger(ConfigPusherImpl.class); + private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class); private final long maxWaitForCapabilitiesMillis; private final long conflictingVersionTimeoutMillis; @@ -83,35 +83,35 @@ public class ConfigPusherImpl implements ConfigPusher { * it is good idea to perform garbage collection to prune * any garbage we have accumulated during startup. */ - logger.debug("Running post-initialization garbage collection..."); + LOG.debug("Running post-initialization garbage collection..."); System.gc(); - logger.debug("Post-initialization garbage collection completed."); - logger.debug("ConfigPusher has pushed configs {}, gc completed", configs); + LOG.debug("Post-initialization garbage collection completed."); + LOG.debug("ConfigPusher has pushed configs {}, gc completed", configs); } catch (NetconfDocumentedException e) { - logger.error("Error pushing configs {}",configs); + LOG.error("Error pushing configs {}",configs); throw new IllegalStateException(e); } } } public void pushConfigs(List configs) throws InterruptedException { - logger.debug("Requested to push configs {}", configs); + LOG.debug("Requested to push configs {}", configs); this.queue.put(configs); } private LinkedHashMap internalPushConfigs(List configs) throws NetconfDocumentedException { - logger.debug("Last config snapshots to be pushed to netconf: {}", configs); + LOG.debug("Last config snapshots to be pushed to netconf: {}", configs); LinkedHashMap result = new LinkedHashMap<>(); // start pushing snapshots: for (ConfigSnapshotHolder configSnapshotHolder : configs) { if(configSnapshotHolder != null) { EditAndCommitResponse editAndCommitResponseWithRetries = pushConfigWithConflictingVersionRetries(configSnapshotHolder); - logger.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result); + LOG.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result); result.put(configSnapshotHolder, editAndCommitResponseWithRetries); } } - logger.debug("All configuration snapshots have been pushed successfully."); + LOG.debug("All configuration snapshots have been pushed successfully."); return result; } @@ -133,7 +133,7 @@ public class ConfigPusherImpl implements ConfigPusher { return pushConfig(configSnapshotHolder, operationService); } catch (ConflictingVersionException e) { lastException = e; - logger.debug("Conflicting version detected, will retry after timeout"); + LOG.debug("Conflicting version detected, will retry after timeout"); sleep(); } } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis); @@ -148,7 +148,7 @@ public class ConfigPusherImpl implements ConfigPusher { try { return getOperationService(expectedCapabilities, idForReporting); } catch (NotEnoughCapabilitiesException e) { - logger.debug("Not enough capabilities: " + e.toString()); + LOG.debug("Not enough capabilities: {}", e.toString()); lastException = e; sleep(); } @@ -187,9 +187,9 @@ public class ConfigPusherImpl implements ConfigPusher { return serviceCandidate; } else { serviceCandidate.close(); - logger.trace("Netconf server did not provide required capabilities for {} " + + LOG.trace("Netconf server did not provide required capabilities for {} ", idForReporting, "Expected but not found: {}, all expected {}, current {}", - idForReporting, notFoundDiff, expectedCapabilities, serviceCandidate.getCapabilities() + notFoundDiff, expectedCapabilities, serviceCandidate.getCapabilities() ); throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff); } @@ -234,7 +234,7 @@ public class ConfigPusherImpl implements ConfigPusher { } catch (SAXException | IOException e) { throw new IllegalStateException("Cannot parse " + configSnapshotHolder); } - logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder); + LOG.trace("Pushing last configuration to netconf: {}", configSnapshotHolder); Stopwatch stopwatch = new Stopwatch().start(); NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted); @@ -244,16 +244,16 @@ public class ConfigPusherImpl implements ConfigPusher { Document commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), operationService, "commit", configSnapshotHolder.toString()); - if (logger.isTraceEnabled()) { + if (LOG.isTraceEnabled()) { StringBuilder response = new StringBuilder("editConfig response = {"); response.append(XmlUtil.toString(editResponseMessage)); response.append("}"); response.append("commit response = {"); response.append(XmlUtil.toString(commitResponseMessage)); response.append("}"); - logger.trace("Last configuration loaded successfully"); - logger.trace("Detailed message {}", response); - logger.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS)); + LOG.trace("Last configuration loaded successfully"); + LOG.trace("Detailed message {}", response); + LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS)); } return new EditAndCommitResponse(editResponseMessage, commitResponseMessage); } diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/NoOpStorageAdapter.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/NoOpStorageAdapter.java index 27f930990d..26e497387a 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/NoOpStorageAdapter.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/NoOpStorageAdapter.java @@ -8,6 +8,9 @@ package org.opendaylight.controller.netconf.persist.impl; +import java.io.IOException; +import java.util.Collections; +import java.util.List; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.config.persist.api.Persister; import org.opendaylight.controller.config.persist.api.PropertiesProvider; @@ -15,32 +18,28 @@ import org.opendaylight.controller.config.persist.api.StorageAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Collections; -import java.util.List; - public class NoOpStorageAdapter implements StorageAdapter, Persister { - private static final Logger logger = LoggerFactory.getLogger(NoOpStorageAdapter.class); + private static final Logger LOG = LoggerFactory.getLogger(NoOpStorageAdapter.class); @Override public Persister instantiate(PropertiesProvider propertiesProvider) { - logger.debug("instantiate called with {}", propertiesProvider); + LOG.debug("instantiate called with {}", propertiesProvider); return this; } @Override public void persistConfig(ConfigSnapshotHolder holder) throws IOException { - logger.debug("persistConfig called with {}", holder); + LOG.debug("persistConfig called with {}", holder); } @Override public List loadLastConfigs() throws IOException { - logger.debug("loadLastConfig called"); + LOG.debug("loadLastConfig called"); return Collections.emptyList(); } @Override public void close() { - logger.debug("close called"); + LOG.debug("close called"); } } diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregator.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregator.java index 7e68ac1875..0c51166fe4 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregator.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregator.java @@ -56,7 +56,7 @@ import org.slf4j.LoggerFactory; * */ public final class PersisterAggregator implements Persister { - private static final Logger logger = LoggerFactory.getLogger(PersisterAggregator.class); + private static final Logger LOG = LoggerFactory.getLogger(PersisterAggregator.class); public static class PersisterWithConfiguration { @@ -139,7 +139,7 @@ public final class PersisterAggregator implements Persister { persisterWithConfigurations.add(PersisterAggregator.loadConfiguration(index, propertiesProvider)); } } - logger.debug("Initialized persister with following adapters {}", persisterWithConfigurations); + LOG.debug("Initialized persister with following adapters {}", persisterWithConfigurations); return new PersisterAggregator(persisterWithConfigurations); } @@ -147,7 +147,7 @@ public final class PersisterAggregator implements Persister { public void persistConfig(ConfigSnapshotHolder holder) throws IOException { for (PersisterWithConfiguration persisterWithConfiguration: persisterWithConfigurations){ if (!persisterWithConfiguration.readOnly){ - logger.debug("Calling {}.persistConfig", persisterWithConfiguration.getStorage()); + LOG.debug("Calling {}.persistConfig", persisterWithConfiguration.getStorage()); persisterWithConfiguration.getStorage().persistConfig(holder); } } @@ -169,12 +169,12 @@ public final class PersisterAggregator implements Persister { throw new RuntimeException("Error while calling loadLastConfig on " + persisterWithConfiguration, e); } if (!configs.isEmpty()) { - logger.debug("Found non empty configs using {}:{}", persisterWithConfiguration, configs); + LOG.debug("Found non empty configs using {}:{}", persisterWithConfiguration, configs); return configs; } } // no storage had an answer - logger.debug("No non-empty list of configuration snapshots found"); + LOG.debug("No non-empty list of configuration snapshots found"); return Collections.emptyList(); } @@ -190,7 +190,7 @@ public final class PersisterAggregator implements Persister { try{ persisterWithConfiguration.storage.close(); }catch(RuntimeException e) { - logger.error("Error while closing {}", persisterWithConfiguration.storage, e); + LOG.error("Error while closing {}", persisterWithConfiguration.storage, e); if (lastException == null){ lastException = e; } else { diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterActivator.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterActivator.java index 8e9f9978c4..135d5ff9be 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterActivator.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterActivator.java @@ -8,13 +8,12 @@ package org.opendaylight.controller.netconf.persist.impl.osgi; +import com.google.common.annotations.VisibleForTesting; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; - import javax.management.MBeanServer; - import org.opendaylight.controller.config.persist.api.ConfigPusher; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider; @@ -34,11 +33,9 @@ import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.annotations.VisibleForTesting; - public class ConfigPersisterActivator implements BundleActivator { - private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterActivator.class); + private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterActivator.class); private static final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); public static final String MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY = "maxWaitForCapabilitiesMillis"; @@ -57,7 +54,7 @@ public class ConfigPersisterActivator implements BundleActivator { @Override public void start(final BundleContext context) throws Exception { - logger.debug("ConfigPersister starting"); + LOG.debug("ConfigPersister starting"); this.context = context; autoCloseables = new ArrayList<>(); @@ -68,7 +65,7 @@ public class ConfigPersisterActivator implements BundleActivator { long maxWaitForCapabilitiesMillis = getMaxWaitForCapabilitiesMillis(propertiesProvider); List configs = persisterAggregator.loadLastConfigs(); long conflictingVersionTimeoutMillis = getConflictingVersionTimeoutMillis(propertiesProvider); - logger.debug("Following configs will be pushed: {}", configs); + LOG.debug("Following configs will be pushed: {}", configs); InnerCustomizer innerCustomizer = new InnerCustomizer(configs, maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis, persisterAggregator); @@ -117,7 +114,7 @@ public class ConfigPersisterActivator implements BundleActivator { @Override public NetconfOperationProvider addingService(ServiceReference reference) { - logger.trace("Got OuterCustomizer.addingService {}", reference); + LOG.trace("Got OuterCustomizer.addingService {}", reference); // JMX was registered, track config-netconf-connector Filter filter; try { @@ -156,15 +153,15 @@ public class ConfigPersisterActivator implements BundleActivator { @Override public NetconfOperationServiceFactory addingService(ServiceReference reference) { - logger.trace("Got InnerCustomizer.addingService {}", reference); + LOG.trace("Got InnerCustomizer.addingService {}", reference); NetconfOperationServiceFactory service = reference.getBundle().getBundleContext().getService(reference); - logger.debug("Creating new job queue"); + LOG.debug("Creating new job queue"); final ConfigPusherImpl configPusher = new ConfigPusherImpl(service, maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis); - logger.debug("Configuration Persister got {}", service); - logger.debug("Context was {}", context); - logger.debug("Registration was {}", registration); + LOG.debug("Configuration Persister got {}", service); + LOG.debug("Context was {}", context); + LOG.debug("Registration was {}", registration); final Thread pushingThread = new Thread(new Runnable() { @Override @@ -177,12 +174,12 @@ public class ConfigPersisterActivator implements BundleActivator { registration = context.registerService(ConfigPusher.class.getName(), configPusher, null); configPusher.process(autoCloseables, platformMBeanServer, persisterAggregator); } else { - logger.warn("Unable to process configs as BundleContext is null"); + LOG.warn("Unable to process configs as BundleContext is null"); } } catch (InterruptedException e) { - logger.info("ConfigPusher thread stopped",e); + LOG.info("ConfigPusher thread stopped",e); } - logger.info("Configuration Persister initialization completed."); + LOG.info("Configuration Persister initialization completed."); } }, "config-pusher"); synchronized (autoCloseables) { diff --git a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/PropertiesProviderBaseImpl.java b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/PropertiesProviderBaseImpl.java index 2a95cca937..d73f3b801e 100644 --- a/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/PropertiesProviderBaseImpl.java +++ b/opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/osgi/PropertiesProviderBaseImpl.java @@ -14,7 +14,7 @@ import org.slf4j.LoggerFactory; public class PropertiesProviderBaseImpl implements PropertiesProvider { - private static final Logger logger = LoggerFactory.getLogger(PropertiesProviderBaseImpl.class); + private static final Logger LOG = LoggerFactory.getLogger(PropertiesProviderBaseImpl.class); private final BundleContext bundleContext; public PropertiesProviderBaseImpl(BundleContext bundleContext) { @@ -28,7 +28,7 @@ public class PropertiesProviderBaseImpl implements PropertiesProvider { } public String getPropertyWithoutPrefix(String fullKey){ - logger.trace("Full key {}", fullKey); + LOG.trace("Full key {}", fullKey); return bundleContext.getProperty(fullKey); } diff --git a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/CapabilityStrippingConfigSnapshotHolderTest.java b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/CapabilityStrippingConfigSnapshotHolderTest.java index 7e9d80abc0..b22924a722 100644 --- a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/CapabilityStrippingConfigSnapshotHolderTest.java +++ b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/CapabilityStrippingConfigSnapshotHolderTest.java @@ -7,18 +7,17 @@ */ package org.opendaylight.controller.netconf.persist.impl; +import static org.junit.Assert.assertEquals; + import com.google.common.collect.Sets; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.w3c.dom.Element; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import static org.junit.Assert.assertEquals; - public class CapabilityStrippingConfigSnapshotHolderTest { @Test diff --git a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandlerTest.java b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandlerTest.java index f16083e3f3..e96b547169 100644 --- a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandlerTest.java +++ b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandlerTest.java @@ -17,7 +17,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import javax.management.MBeanServerConnection; - import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; diff --git a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationListenerTest.java b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationListenerTest.java index bf031f192a..f0cd267dd6 100644 --- a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationListenerTest.java +++ b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationListenerTest.java @@ -8,10 +8,9 @@ package org.opendaylight.controller.netconf.persist.impl; +import com.google.common.collect.Lists; import java.util.Collections; - import javax.management.Notification; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -25,8 +24,6 @@ import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification; import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification; import org.opendaylight.controller.netconf.util.xml.XmlUtil; -import com.google.common.collect.Lists; - public class ConfigPersisterNotificationListenerTest { @Mock diff --git a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/DummyAdapter.java b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/DummyAdapter.java index e824b58832..792f8cd1c0 100644 --- a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/DummyAdapter.java +++ b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/DummyAdapter.java @@ -7,15 +7,14 @@ */ package org.opendaylight.controller.netconf.persist.impl; +import java.io.IOException; +import java.util.Collections; +import java.util.List; import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; import org.opendaylight.controller.config.persist.api.Persister; import org.opendaylight.controller.config.persist.api.PropertiesProvider; import org.opendaylight.controller.config.persist.api.StorageAdapter; -import java.io.IOException; -import java.util.Collections; -import java.util.List; - public class DummyAdapter implements StorageAdapter, Persister { static int persist = 0; diff --git a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregatorTest.java b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregatorTest.java index cd646aeb07..e6464f8403 100644 --- a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregatorTest.java +++ b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/PersisterAggregatorTest.java @@ -8,30 +8,27 @@ package org.opendaylight.controller.netconf.persist.impl; -import com.google.common.collect.Lists; - -import org.junit.Test; -import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; -import org.opendaylight.controller.config.persist.api.Persister; -import org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter; -import org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator; -import org.opendaylight.controller.netconf.persist.impl.osgi.PropertiesProviderBaseImpl; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.opendaylight.controller.netconf.persist.impl.PersisterAggregator.PersisterWithConfiguration; -import static org.opendaylight.controller.netconf.persist.impl.PersisterAggregatorTest.TestingPropertiesProvider.loadFile; + +import com.google.common.collect.Lists; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import org.junit.Test; +import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder; +import org.opendaylight.controller.config.persist.api.Persister; +import org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter; +import org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator; +import org.opendaylight.controller.netconf.persist.impl.osgi.PropertiesProviderBaseImpl; public class PersisterAggregatorTest { @@ -72,7 +69,7 @@ public class PersisterAggregatorTest { @Test public void testDummyAdapter() throws Exception { - PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(loadFile("test1.properties")); + PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(TestingPropertiesProvider.loadFile("test1.properties")); List persisters = persisterAggregator.getPersisterWithConfigurations(); assertEquals(1, persisters.size()); PersisterWithConfiguration persister = persisters.get(0); @@ -107,7 +104,7 @@ public class PersisterAggregatorTest { @Test public void testLoadFromPropertyFile() throws Exception { - PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(loadFile("test2.properties")); + PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(TestingPropertiesProvider.loadFile("test2.properties")); List persisters = persisterAggregator.getPersisterWithConfigurations(); assertEquals(1, persisters.size()); PersisterWithConfiguration persister = persisters.get(0); @@ -118,7 +115,7 @@ public class PersisterAggregatorTest { @Test public void testFileStorageNumberOfBackups() throws Exception { try { - PersisterAggregator.createFromProperties(loadFile("test3.properties")); + PersisterAggregator.createFromProperties(TestingPropertiesProvider.loadFile("test3.properties")); fail(); } catch (RuntimeException e) { assertThat( diff --git a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterTest.java b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterTest.java index e02e27a745..142d8f5226 100644 --- a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterTest.java +++ b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/ConfigPersisterTest.java @@ -7,7 +7,15 @@ */ package org.opendaylight.controller.netconf.persist.impl.osgi; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + import com.google.common.collect.Sets; +import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -25,17 +33,8 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; -import java.io.IOException; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - public class ConfigPersisterTest { - private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterTest.class); + private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterTest.class); private MockedBundleContext ctx; private ConfigPersisterActivator configPersisterActivator; @@ -136,7 +135,7 @@ public class ConfigPersisterTest { doReturn(getConflictingService()).when(ctx.serviceFactory).createService(anyString()); Thread.sleep(500); // working service: - logger.info("Switching to working service **"); + LOG.info("Switching to working service **"); doReturn(getWorkingService(getOKDocument())).when(ctx.serviceFactory).createService(anyString()); Thread.sleep(1000); assertCannotRegisterAsJMXListener_pushWasSuccessful(); diff --git a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/MockedBundleContext.java b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/MockedBundleContext.java index 3e5249468d..0d866ecda7 100644 --- a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/MockedBundleContext.java +++ b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/MockedBundleContext.java @@ -13,6 +13,8 @@ import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import java.io.Closeable; import java.io.IOException; import java.util.Collections; @@ -20,7 +22,6 @@ import java.util.Dictionary; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; - import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.opendaylight.controller.config.persist.api.ConfigPusher; @@ -38,9 +39,6 @@ import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - final class MockedBundleContext { @Mock private BundleContext context; diff --git a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/TestingExceptionHandler.java b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/TestingExceptionHandler.java index 3f04010015..fcd39d6ae6 100644 --- a/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/TestingExceptionHandler.java +++ b/opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/TestingExceptionHandler.java @@ -7,25 +7,25 @@ */ package org.opendaylight.controller.netconf.persist.impl.osgi; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import org.junit.matchers.JUnitMatchers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; final class TestingExceptionHandler implements Thread.UncaughtExceptionHandler { - private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterTest.class); + private static final Logger LOG = LoggerFactory.getLogger(TestingExceptionHandler.class); private Throwable t; @Override public void uncaughtException(Thread t, Throwable e) { - logger.debug("Uncaught exception in thread {}", t, e); + LOG.debug("Uncaught exception in thread {}", t, e); this.t = e; } @@ -49,7 +49,7 @@ final class TestingExceptionHandler implements Thread.UncaughtExceptionHandler { private void assertException(Throwable t, Class exType, String exMessageToContain) { assertEquals("Expected exception of type " + exType + " but was " + t, exType, t.getClass()); if(exMessageToContain!=null) { - assertThat(t.getMessage(), JUnitMatchers.containsString(exMessageToContain)); + assertThat(t.getMessage(), containsString(exMessageToContain)); } } diff --git a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfDocumentedException.java b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfDocumentedException.java index 0c365b9d30..e5f32653c5 100644 --- a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfDocumentedException.java +++ b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfDocumentedException.java @@ -21,10 +21,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; - import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - import org.opendaylight.controller.config.api.ConflictingVersionException; import org.opendaylight.controller.config.api.ValidationException; import org.slf4j.Logger; diff --git a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfSession.java b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfSession.java index 0bd54979f8..ca91589d74 100644 --- a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfSession.java +++ b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfSession.java @@ -8,7 +8,6 @@ package org.opendaylight.controller.netconf.api; import io.netty.channel.ChannelFuture; - import org.opendaylight.protocol.framework.ProtocolSession; public interface NetconfSession extends ProtocolSession { diff --git a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/CommitJMXNotification.java b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/CommitJMXNotification.java index 74cd4a4e05..4e3954a24d 100644 --- a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/CommitJMXNotification.java +++ b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/CommitJMXNotification.java @@ -8,10 +8,9 @@ package org.opendaylight.controller.netconf.api.jmx; -import org.w3c.dom.Element; - -import javax.management.NotificationBroadcasterSupport; import java.util.Set; +import javax.management.NotificationBroadcasterSupport; +import org.w3c.dom.Element; public class CommitJMXNotification extends NetconfJMXNotification { diff --git a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java index e45d3c38a2..edc0bc99c5 100644 --- a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java +++ b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java @@ -8,9 +8,8 @@ package org.opendaylight.controller.netconf.api.jmx; -import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; - import javax.management.ObjectName; +import org.opendaylight.controller.config.api.jmx.ObjectNameUtil; public interface DefaultCommitOperationMXBean { diff --git a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/NetconfJMXNotification.java b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/NetconfJMXNotification.java index 5aa4bffce3..cba98ee435 100644 --- a/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/NetconfJMXNotification.java +++ b/opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/NetconfJMXNotification.java @@ -9,10 +9,8 @@ package org.opendaylight.controller.netconf.api.jmx; import java.util.Set; - import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; - import org.w3c.dom.Element; public abstract class NetconfJMXNotification extends Notification { diff --git a/opendaylight/netconf/netconf-api/src/test/java/org/opendaylight/controller/netconf/api/NetconfDocumentedExceptionTest.java b/opendaylight/netconf/netconf-api/src/test/java/org/opendaylight/controller/netconf/api/NetconfDocumentedExceptionTest.java index cdf8b913ec..dc18b106bf 100644 --- a/opendaylight/netconf/netconf-api/src/test/java/org/opendaylight/controller/netconf/api/NetconfDocumentedExceptionTest.java +++ b/opendaylight/netconf/netconf-api/src/test/java/org/opendaylight/controller/netconf/api/NetconfDocumentedExceptionTest.java @@ -11,15 +11,14 @@ package org.opendaylight.controller.netconf.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.Iterator; - import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; - import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity; @@ -29,8 +28,6 @@ import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; import org.w3c.dom.Document; import org.w3c.dom.Node; -import com.google.common.collect.ImmutableMap; - /** * Unit tests for NetconfDocumentedException. diff --git a/opendaylight/netconf/netconf-artifacts/pom.xml b/opendaylight/netconf/netconf-artifacts/pom.xml new file mode 100644 index 0000000000..eb3cac18df --- /dev/null +++ b/opendaylight/netconf/netconf-artifacts/pom.xml @@ -0,0 +1,164 @@ + + + + + + 4.0.0 + org.opendaylight.controller + netconf-artifacts + 0.3.0-SNAPSHOT + pom + + + + + ${project.groupId} + netconf-config-dispatcher + ${project.version} + + + ${project.groupId} + config-netconf-connector + ${project.version} + + + ${project.groupId} + config-persister-impl + ${project.version} + + + ${project.groupId} + netconf-api + ${project.version} + + + ${project.groupId} + netconf-auth + ${project.version} + + + ${project.groupId} + netconf-cli + ${project.version} + + + ${project.groupId} + netconf-client + ${project.version} + + + ${project.groupId} + netconf-config + ${project.version} + + + ${project.groupId} + netconf-connector-config + ${project.version} + + + ${project.groupId} + netconf-impl + ${project.version} + + + ${project.groupId} + netconf-mapping-api + ${project.version} + + + ${project.groupId} + netconf-monitoring + ${project.version} + + + ${project.groupId} + netconf-netty-util + ${project.version} + + + ${project.groupId} + netconf-ssh + ${project.version} + + + ${project.groupId} + netconf-tcp + ${project.version} + + + ${project.groupId} + netconf-testtool + ${project.version} + + + ${project.groupId} + netconf-usermanager + ${project.version} + + + ${project.groupId} + netconf-util + ${project.version} + + + + ${project.groupId} + ietf-netconf-monitoring + ${project.version} + + + ${project.groupId} + ietf-netconf-monitoring-extension + ${project.version} + + + + ${project.groupId} + netconf-client + ${project.version} + test-jar + + + ${project.groupId} + netconf-impl + ${project.version} + test-jar + + + ${project.groupId} + netconf-netty-util + ${project.version} + test-jar + + + ${project.groupId} + netconf-ssh + ${project.version} + test-jar + + + ${project.groupId} + netconf-util + ${project.version} + test-jar + + + + ${project.groupId} + features-netconf + ${project.version} + features + xml + runtime + + + + + diff --git a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientDispatcherImplTest.java b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientDispatcherImplTest.java index 5a2ec5656f..dfbb972e8c 100644 --- a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientDispatcherImplTest.java +++ b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientDispatcherImplTest.java @@ -21,7 +21,6 @@ import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl; import org.opendaylight.controller.netconf.client.NetconfClientSessionListener; import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration; -import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder; import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration; import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler; @@ -32,7 +31,6 @@ import org.opendaylight.protocol.framework.ReconnectStrategyFactory; import java.net.InetSocketAddress; import java.util.concurrent.Future; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; diff --git a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorFactoryTest.java b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorFactoryTest.java index 0557a0c268..62d6275b9e 100644 --- a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorFactoryTest.java +++ b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorFactoryTest.java @@ -13,13 +13,10 @@ import io.netty.channel.Channel; import io.netty.util.HashedWheelTimer; import io.netty.util.Timer; import io.netty.util.concurrent.Promise; -import org.apache.sshd.common.SessionListener; import org.junit.Test; import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader; import org.opendaylight.protocol.framework.SessionListenerFactory; import org.opendaylight.protocol.framework.SessionNegotiator; - -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -29,15 +26,15 @@ public class NetconfClientSessionNegotiatorFactoryTest { public void testGetSessionNegotiator() throws Exception { NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class); Timer timer = new HashedWheelTimer(); - SessionListenerFactory listenerFactory = mock(SessionListenerFactory.class); + SessionListenerFactory listenerFactory = mock(SessionListenerFactory.class); doReturn(sessionListener).when(listenerFactory).getSessionListener(); Channel channel = mock(Channel.class); - Promise promise = mock(Promise.class); + Promise promise = mock(Promise.class); NetconfClientSessionNegotiatorFactory negotiatorFactory = new NetconfClientSessionNegotiatorFactory(timer, Optional.absent(), 200L); - SessionNegotiator sessionNegotiator = negotiatorFactory.getSessionNegotiator(listenerFactory, channel, promise); + SessionNegotiator sessionNegotiator = negotiatorFactory.getSessionNegotiator(listenerFactory, channel, promise); assertNotNull(sessionNegotiator); } } diff --git a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorTest.java b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorTest.java index 333e9deae4..187f13b258 100644 --- a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorTest.java +++ b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionNegotiatorTest.java @@ -8,22 +8,35 @@ package org.opendaylight.controller.netconf.client; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import com.google.common.base.Optional; -import io.netty.channel.*; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.ChannelProgressivePromise; import io.netty.handler.ssl.SslHandler; import io.netty.util.HashedWheelTimer; +import io.netty.util.Timer; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; -import org.apache.mina.handler.demux.ExceptionHandler; +import java.util.Set; import org.junit.Before; import org.junit.Test; -import org.mockito.Mockito; import org.mockito.internal.util.collections.Sets; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences; import org.opendaylight.controller.netconf.api.NetconfMessage; -import io.netty.util.Timer; import org.opendaylight.controller.netconf.nettyutil.handler.ChunkedFramingMechanismEncoder; import org.opendaylight.controller.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder; import org.opendaylight.controller.netconf.nettyutil.handler.NetconfXMLToMessageDecoder; @@ -31,14 +44,8 @@ import org.opendaylight.controller.netconf.nettyutil.handler.exi.NetconfStartExi import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage; import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader; import org.opendaylight.controller.netconf.util.test.XmlFileLoader; -import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.openexi.proc.common.EXIOptions; import org.w3c.dom.Document; -import java.util.Set; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.*; public class NetconfClientSessionNegotiatorTest { @@ -96,8 +103,8 @@ public class NetconfClientSessionNegotiatorTest { return pipeline; } - private NetconfClientSessionNegotiator createNetconfClientSessionNegotiator(Promise promise, - NetconfMessage startExi) { + private NetconfClientSessionNegotiator createNetconfClientSessionNegotiator(final Promise promise, + final NetconfMessage startExi) { ChannelProgressivePromise progressivePromise = mock(ChannelProgressivePromise.class); NetconfClientSessionPreferences preferences = new NetconfClientSessionPreferences(helloMessage, startExi); doReturn(progressivePromise).when(promise).setFailure(any(Throwable.class)); @@ -115,7 +122,7 @@ public class NetconfClientSessionNegotiatorTest { NetconfClientSessionNegotiator negotiator = createNetconfClientSessionNegotiator(promise, null); negotiator.channelActive(null); - Set caps = Sets.newSet("a", "b"); + Set caps = Sets.newSet("a", "b"); NetconfHelloMessage helloServerMessage = NetconfHelloMessage.createServerHello(caps, 10); negotiator.handleMessage(helloServerMessage); verify(promise).setSuccess(anyObject()); @@ -130,12 +137,12 @@ public class NetconfClientSessionNegotiatorTest { NetconfClientSessionNegotiator negotiator = createNetconfClientSessionNegotiator(promise, exiMessage); negotiator.channelActive(null); - Set caps = Sets.newSet("exi:1.0"); + Set caps = Sets.newSet("exi:1.0"); NetconfHelloMessage helloMessage = NetconfHelloMessage.createServerHello(caps, 10); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { + public Object answer(final InvocationOnMock invocationOnMock) throws Throwable { channelInboundHandlerAdapter = ((ChannelInboundHandlerAdapter) invocationOnMock.getArguments()[2]); return null; } diff --git a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionTest.java b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionTest.java index 4175190e14..731a3fe960 100644 --- a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionTest.java +++ b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfClientSessionTest.java @@ -12,7 +12,6 @@ import com.google.common.collect.Lists; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelPipeline; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; @@ -23,7 +22,6 @@ import org.opendaylight.controller.netconf.client.NetconfClientSessionListener; import org.opendaylight.controller.netconf.nettyutil.handler.NetconfEXICodec; import org.openexi.proc.common.EXIOptions; -import java.util.ArrayList; import java.util.Collection; import static org.junit.Assert.assertEquals; diff --git a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfReconnectingClientConfigurationTest.java b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfReconnectingClientConfigurationTest.java index e79a370ec7..a9754654d5 100644 --- a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfReconnectingClientConfigurationTest.java +++ b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/NetconfReconnectingClientConfigurationTest.java @@ -12,7 +12,6 @@ import com.google.common.base.Optional; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; -import org.opendaylight.controller.config.yang.protocol.framework.NeverReconnectStrategyFactoryModule; import org.opendaylight.controller.netconf.client.NetconfClientSessionListener; import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration; diff --git a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SimpleNetconfClientSessionListenerTest.java b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SimpleNetconfClientSessionListenerTest.java index e067cc225f..9065ca45a2 100644 --- a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SimpleNetconfClientSessionListenerTest.java +++ b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SimpleNetconfClientSessionListenerTest.java @@ -9,7 +9,6 @@ package org.opendaylight.controller.netconf.client; import io.netty.channel.*; import io.netty.util.concurrent.Future; -import io.netty.util.concurrent.Promise; import org.junit.Before; import org.junit.Test; import org.mockito.internal.util.collections.Sets; @@ -26,7 +25,7 @@ public class SimpleNetconfClientSessionListenerTest { private Channel channel; private ChannelFuture channelFuture; - Set caps; + Set caps; private NetconfHelloMessage helloMessage; private NetconfMessage message; private NetconfClientSessionListener sessionListener; diff --git a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SshClientChannelInitializerTest.java b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SshClientChannelInitializerTest.java index 0830c2967b..8c55d8cc10 100644 --- a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SshClientChannelInitializerTest.java +++ b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/SshClientChannelInitializerTest.java @@ -29,7 +29,7 @@ public class SshClientChannelInitializerTest { NetconfClientSessionNegotiatorFactory negotiatorFactory = mock(NetconfClientSessionNegotiatorFactory.class); NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class); - SessionNegotiator sessionNegotiator = mock(SessionNegotiator.class); + SessionNegotiator sessionNegotiator = mock(SessionNegotiator.class); doReturn("").when(sessionNegotiator).toString(); doReturn(sessionNegotiator).when(negotiatorFactory).getSessionNegotiator(any(SessionListenerFactory.class), any(Channel.class), any(Promise.class)); ChannelPipeline pipeline = mock(ChannelPipeline.class); diff --git a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/TcpClientChannelInitializerTest.java b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/TcpClientChannelInitializerTest.java index e355cf45e7..9c57565981 100644 --- a/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/TcpClientChannelInitializerTest.java +++ b/opendaylight/netconf/netconf-client/src/test/java/org/opendaylight/controller/netconf/client/TcpClientChannelInitializerTest.java @@ -13,7 +13,6 @@ import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelPipeline; import io.netty.util.concurrent.Promise; import org.junit.Test; -import org.opendaylight.controller.netconf.nettyutil.AbstractChannelInitializer; import org.opendaylight.protocol.framework.SessionListenerFactory; import org.opendaylight.protocol.framework.SessionNegotiator; @@ -23,7 +22,7 @@ public class TcpClientChannelInitializerTest { @Test public void testInitializeSessionNegotiator() throws Exception { NetconfClientSessionNegotiatorFactory factory = mock(NetconfClientSessionNegotiatorFactory.class); - SessionNegotiator sessionNegotiator = mock(SessionNegotiator.class); + SessionNegotiator sessionNegotiator = mock(SessionNegotiator.class); doReturn("").when(sessionNegotiator).toString(); doReturn(sessionNegotiator).when(factory).getSessionNegotiator(any(SessionListenerFactory.class), any(Channel.class), any(Promise.class)); NetconfClientSessionListener listener = mock(NetconfClientSessionListener.class); diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/SubtreeFilter.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/SubtreeFilter.java index 6e81584133..8b2ca86010 100644 --- a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/SubtreeFilter.java +++ b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/SubtreeFilter.java @@ -10,6 +10,7 @@ package org.opendaylight.controller.netconf.impl; import com.google.common.base.Optional; import java.io.IOException; +import java.util.Map; import org.opendaylight.controller.netconf.api.NetconfDocumentedException; import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; import org.opendaylight.controller.netconf.util.mapping.AbstractNetconfOperation.OperationNameAndNamespace; @@ -73,7 +74,7 @@ public class SubtreeFilter { return result; } - private static void addSubtree(XmlElement filter, XmlElement src, XmlElement dst) { + private static void addSubtree(XmlElement filter, XmlElement src, XmlElement dst) throws NetconfDocumentedException { for (XmlElement srcChild : src.getChildElements()) { for (XmlElement filterChild : filter.getChildElements()) { addSubtree2(filterChild, srcChild, dst); @@ -81,7 +82,7 @@ public class SubtreeFilter { } } - private static MatchingResult addSubtree2(XmlElement filter, XmlElement src, XmlElement dstParent) { + private static MatchingResult addSubtree2(XmlElement filter, XmlElement src, XmlElement dstParent) throws NetconfDocumentedException { Document document = dstParent.getDomElement().getOwnerDocument(); MatchingResult matches = matches(src, filter); if (matches != MatchingResult.NO_MATCH && matches != MatchingResult.CONTENT_MISMATCH) { @@ -123,7 +124,7 @@ public class SubtreeFilter { * Shallow compare src node to filter: tag name and namespace must match. * If filter node has no children and has text content, it also must match. */ - private static MatchingResult matches(XmlElement src, XmlElement filter) { + private static MatchingResult matches(XmlElement src, XmlElement filter) throws NetconfDocumentedException { boolean tagMatch = src.getName().equals(filter.getName()) && src.getNamespaceOptionally().equals(filter.getNamespaceOptionally()); MatchingResult result = null; @@ -131,7 +132,7 @@ public class SubtreeFilter { // match text content Optional maybeText = filter.getOnlyTextContentOptionally(); if (maybeText.isPresent()) { - if (maybeText.equals(src.getOnlyTextContentOptionally())) { + if (maybeText.equals(src.getOnlyTextContentOptionally()) || prefixedContentMatches(filter, src)) { result = MatchingResult.CONTENT_MATCH; } else { result = MatchingResult.CONTENT_MISMATCH; @@ -159,10 +160,30 @@ public class SubtreeFilter { if (result == null) { result = MatchingResult.NO_MATCH; } - logger.debug("Matching {} to {} resulted in {}", src, filter, tagMatch); + logger.debug("Matching {} to {} resulted in {}", src, filter, result); return result; } + private static boolean prefixedContentMatches(final XmlElement filter, final XmlElement src) throws NetconfDocumentedException { + final Map.Entry prefixToNamespaceOfFilter = filter.findNamespaceOfTextContent(); + final Map.Entry prefixToNamespaceOfSrc = src.findNamespaceOfTextContent(); + + final String prefix = prefixToNamespaceOfFilter.getKey(); + // If this is not a prefixed content, we do not need to continue since content do not match + if(prefix.equals(XmlElement.DEFAULT_NAMESPACE_PREFIX)) { + return false; + } + // Namespace mismatch + if(!prefixToNamespaceOfFilter.getValue().equals(prefixToNamespaceOfSrc.getValue())) { + return false; + } + + final String unprefixedFilterContent = filter.getTextContent().substring(prefixToNamespaceOfFilter.getKey().length() + 1); + final String unprefixedSrcContnet = src.getTextContent().substring(prefixToNamespaceOfSrc.getKey().length() + 1); + // Finally compare unprefixed content + return unprefixedFilterContent.equals(unprefixedSrcContnet); + } + enum MatchingResult { NO_MATCH, TAG_MATCH, CONTENT_MATCH, CONTENT_MISMATCH } diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultNetconfOperation.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultNetconfOperation.java index 13d4ab290b..2646b7e26e 100644 --- a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultNetconfOperation.java +++ b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultNetconfOperation.java @@ -1,14 +1,14 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.netconf.impl.mapping.operations; - -import org.opendaylight.controller.netconf.impl.NetconfServerSession; - -public interface DefaultNetconfOperation { - void setNetconfSession(NetconfServerSession s); -} +/* + * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.netconf.impl.mapping.operations; + +import org.opendaylight.controller.netconf.impl.NetconfServerSession; + +public interface DefaultNetconfOperation { + void setNetconfSession(NetconfServerSession s); +} diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStartExi.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStartExi.java index cccb1a3ac3..6de185ac1c 100644 --- a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStartExi.java +++ b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStartExi.java @@ -1,71 +1,71 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.netconf.impl.mapping.operations; - -import org.opendaylight.controller.netconf.api.NetconfDocumentedException; -import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity; -import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag; -import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType; -import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.controller.netconf.api.NetconfMessage; -import org.opendaylight.controller.netconf.impl.NetconfServerSession; -import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution; -import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation; -import org.opendaylight.controller.netconf.util.xml.XmlElement; -import org.opendaylight.controller.netconf.util.xml.XmlUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -public class DefaultStartExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation { - public static final String START_EXI = "start-exi"; - - private static final Logger logger = LoggerFactory.getLogger(DefaultStartExi.class); - private NetconfServerSession netconfSession; - - public DefaultStartExi(String netconfSessionIdForReporting) { - super(netconfSessionIdForReporting); - } - - @Override - public Document handle(Document message, - NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException { - logger.debug("Received start-exi message {} ", XmlUtil.toString(message)); - - try { - netconfSession.startExiCommunication(new NetconfMessage(message)); - } catch (IllegalArgumentException e) { - throw new NetconfDocumentedException("Failed to parse EXI parameters", ErrorType.protocol, - ErrorTag.operation_failed, ErrorSeverity.error); - } - - return super.handle(message, subsequentOperation); - } - - @Override - protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException { - Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK); - logger.trace("{} operation successful", START_EXI); - return getSchemaResult; - } - - @Override - protected String getOperationName() { - return START_EXI; - } - - @Override - protected String getOperationNamespace() { - return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0; - } - - @Override - public void setNetconfSession(NetconfServerSession s) { - netconfSession = s; - } -} +/* + * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.netconf.impl.mapping.operations; + +import org.opendaylight.controller.netconf.api.NetconfDocumentedException; +import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity; +import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag; +import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType; +import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.controller.netconf.api.NetconfMessage; +import org.opendaylight.controller.netconf.impl.NetconfServerSession; +import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution; +import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation; +import org.opendaylight.controller.netconf.util.xml.XmlElement; +import org.opendaylight.controller.netconf.util.xml.XmlUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +public class DefaultStartExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation { + public static final String START_EXI = "start-exi"; + + private static final Logger logger = LoggerFactory.getLogger(DefaultStartExi.class); + private NetconfServerSession netconfSession; + + public DefaultStartExi(String netconfSessionIdForReporting) { + super(netconfSessionIdForReporting); + } + + @Override + public Document handle(Document message, + NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException { + logger.debug("Received start-exi message {} ", XmlUtil.toString(message)); + + try { + netconfSession.startExiCommunication(new NetconfMessage(message)); + } catch (IllegalArgumentException e) { + throw new NetconfDocumentedException("Failed to parse EXI parameters", ErrorType.protocol, + ErrorTag.operation_failed, ErrorSeverity.error); + } + + return super.handle(message, subsequentOperation); + } + + @Override + protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException { + Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK); + logger.trace("{} operation successful", START_EXI); + return getSchemaResult; + } + + @Override + protected String getOperationName() { + return START_EXI; + } + + @Override + protected String getOperationNamespace() { + return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0; + } + + @Override + public void setNetconfSession(NetconfServerSession s) { + netconfSession = s; + } +} diff --git a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStopExi.java b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStopExi.java index 2a24ae32fa..233638d5b0 100644 --- a/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStopExi.java +++ b/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStopExi.java @@ -1,58 +1,58 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.netconf.impl.mapping.operations; - -import org.opendaylight.controller.netconf.api.NetconfDocumentedException; -import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; -import org.opendaylight.controller.netconf.impl.NetconfServerSession; -import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation; -import org.opendaylight.controller.netconf.util.xml.XmlElement; -import org.opendaylight.controller.netconf.util.xml.XmlUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -public class DefaultStopExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation { - - public static final String STOP_EXI = "stop-exi"; - private NetconfServerSession netconfSession; - - private static final Logger logger = LoggerFactory - .getLogger(DefaultStartExi.class); - - public DefaultStopExi(String netconfSessionIdForReporting) { - super(netconfSessionIdForReporting); - } - - @Override - protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException { - logger.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement)); - - netconfSession.stopExiCommunication(); - - Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK); - logger.trace("{} operation successful", STOP_EXI); - return getSchemaResult; - } - - @Override - protected String getOperationName() { - return STOP_EXI; - } - - @Override - protected String getOperationNamespace() { - return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0; - } - - @Override - public void setNetconfSession(NetconfServerSession s) { - this.netconfSession = s; - } -} +/* + * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.controller.netconf.impl.mapping.operations; + +import org.opendaylight.controller.netconf.api.NetconfDocumentedException; +import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; +import org.opendaylight.controller.netconf.impl.NetconfServerSession; +import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation; +import org.opendaylight.controller.netconf.util.xml.XmlElement; +import org.opendaylight.controller.netconf.util.xml.XmlUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class DefaultStopExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation { + + public static final String STOP_EXI = "stop-exi"; + private NetconfServerSession netconfSession; + + private static final Logger logger = LoggerFactory + .getLogger(DefaultStartExi.class); + + public DefaultStopExi(String netconfSessionIdForReporting) { + super(netconfSessionIdForReporting); + } + + @Override + protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException { + logger.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement)); + + netconfSession.stopExiCommunication(); + + Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK); + logger.trace("{} operation successful", STOP_EXI); + return getSchemaResult; + } + + @Override + protected String getOperationName() { + return STOP_EXI; + } + + @Override + protected String getOperationNamespace() { + return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0; + } + + @Override + public void setNetconfSession(NetconfServerSession s) { + this.netconfSession = s; + } +} diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/AdditionalHeaderParserTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/AdditionalHeaderParserTest.java index c2dcd67921..444d4fe4ab 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/AdditionalHeaderParserTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/AdditionalHeaderParserTest.java @@ -7,8 +7,7 @@ */ package org.opendaylight.controller.netconf.impl; -import junit.framework.Assert; - +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader; @@ -18,18 +17,18 @@ public class AdditionalHeaderParserTest { public void testParsing() throws Exception { String s = "[netconf;10.12.0.102:48528;ssh;;;;;;]"; NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(s); - Assert.assertEquals("netconf", header.getUserName()); - Assert.assertEquals("10.12.0.102", header.getAddress()); - Assert.assertEquals("ssh", header.getTransport()); + assertEquals("netconf", header.getUserName()); + assertEquals("10.12.0.102", header.getAddress()); + assertEquals("ssh", header.getTransport()); } @Test public void testParsing2() throws Exception { String s = "[tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]"; NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(s); - Assert.assertEquals("tomas", header.getUserName()); - Assert.assertEquals("10.0.0.0", header.getAddress()); - Assert.assertEquals("tcp", header.getTransport()); + assertEquals("tomas", header.getUserName()); + assertEquals("10.0.0.0", header.getAddress()); + assertEquals("tcp", header.getTransport()); } @Test(expected = IllegalArgumentException.class) diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/ExiEncodeDecodeTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/ExiEncodeDecodeTest.java index 58c6566d91..b54b218033 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/ExiEncodeDecodeTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/ExiEncodeDecodeTest.java @@ -7,7 +7,7 @@ */ package org.opendaylight.controller.netconf.impl; -import static junit.framework.Assert.assertNotNull; +import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.opendaylight.controller.netconf.api.NetconfMessage; diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/NetconfMonitoringServiceImplTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/NetconfMonitoringServiceImplTest.java index 1b078be9a4..2125035799 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/NetconfMonitoringServiceImplTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/NetconfMonitoringServiceImplTest.java @@ -12,7 +12,6 @@ import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import io.netty.channel.Channel; -import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; @@ -56,7 +55,6 @@ public class NetconfMonitoringServiceImplTest { public void testSessions() throws Exception { doReturn("sessToStr").when(managementSession).toString(); service.onSessionUp(managementSession); - List list = Lists.newArrayList(managementSession); } @Test(expected = RuntimeException.class) @@ -75,17 +73,17 @@ public class NetconfMonitoringServiceImplTest { public void testGetSchemas3() throws Exception { doReturn("").when(managementSession).toString(); Capability cap = mock(Capability.class); - Set caps = Sets.newHashSet(cap); - Set services = Sets.newHashSet(operationService); + Set caps = Sets.newHashSet(cap); + Set services = Sets.newHashSet(operationService); doReturn(snapshot).when(operationProvider).openSnapshot(anyString()); doReturn(services).when(snapshot).getServices(); doReturn(caps).when(operationService).getCapabilities(); - Optional opt = mock(Optional.class); + Optional opt = mock(Optional.class); doReturn(opt).when(cap).getCapabilitySchema(); doReturn(true).when(opt).isPresent(); doReturn(opt).when(cap).getModuleNamespace(); doReturn("namespace").when(opt).get(); - Optional optRev = Optional.of("rev"); + Optional optRev = Optional.of("rev"); doReturn(optRev).when(cap).getRevision(); doReturn(Optional.of("modName")).when(cap).getModuleName(); doReturn(Optional.of(Lists.newArrayList("loc"))).when(cap).getLocation(); diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/SubtreeFilterTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/SubtreeFilterTest.java index b11834386e..51dfa4b1a8 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/SubtreeFilterTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/SubtreeFilterTest.java @@ -36,7 +36,7 @@ public class SubtreeFilterTest { @Parameters public static Collection data() { List result = new ArrayList<>(); - for (int i = 0; i <= 8; i++) { + for (int i = 0; i <= 10; i++) { result.add(new Object[]{i}); } return result; diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultCloseSessionTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultCloseSessionTest.java index ae3d65646f..d6b0201ab8 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultCloseSessionTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultCloseSessionTest.java @@ -13,8 +13,6 @@ import org.opendaylight.controller.netconf.api.NetconfDocumentedException; import org.opendaylight.controller.netconf.util.xml.XmlElement; import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.w3c.dom.Document; -import org.w3c.dom.Element; - import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultGetSchemaTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultGetSchemaTest.java index b655e90f2b..4218176f1d 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultGetSchemaTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultGetSchemaTest.java @@ -8,8 +8,13 @@ package org.opendaylight.controller.netconf.impl.mapping.operations; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; import com.google.common.base.Optional; -import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.netconf.api.NetconfDocumentedException; @@ -18,13 +23,6 @@ import org.opendaylight.controller.netconf.util.xml.XmlElement; import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.w3c.dom.Document; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - public class DefaultGetSchemaTest { private CapabilityProvider cap; diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfImplActivatorTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfImplActivatorTest.java index b59ea884c5..fd9295a4b3 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfImplActivatorTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfImplActivatorTest.java @@ -9,18 +9,23 @@ package org.opendaylight.controller.netconf.impl.osgi; import java.util.Arrays; -import java.util.Collection; import java.util.Dictionary; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService; -import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider; -import org.osgi.framework.*; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Filter; +import org.osgi.framework.ServiceListener; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; public class NetconfImplActivatorTest { @@ -29,9 +34,9 @@ public class NetconfImplActivatorTest { @Mock private Filter filter; @Mock - private ServiceReference reference; + private ServiceReference reference; @Mock - private ServiceRegistration registration; + private ServiceRegistration registration; @Before public void setUp() throws Exception { @@ -39,7 +44,7 @@ public class NetconfImplActivatorTest { doReturn(filter).when(bundle).createFilter(anyString()); doNothing().when(bundle).addServiceListener(any(ServiceListener.class), anyString()); - ServiceReference[] refs = new ServiceReference[0]; + ServiceReference[] refs = new ServiceReference[0]; doReturn(refs).when(bundle).getServiceReferences(anyString(), anyString()); doReturn(Arrays.asList(refs)).when(bundle).getServiceReferences(any(Class.class), anyString()); doReturn("").when(bundle).getProperty(anyString()); diff --git a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceFactoryTrackerTest.java b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceFactoryTrackerTest.java index 374e8aeb9f..0d7158aa21 100644 --- a/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceFactoryTrackerTest.java +++ b/opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/osgi/NetconfOperationServiceFactoryTrackerTest.java @@ -32,7 +32,7 @@ public class NetconfOperationServiceFactoryTrackerTest { @Mock private NetconfOperationServiceFactory factory; @Mock - private ServiceReference reference; + private ServiceReference reference; private NetconfOperationServiceFactoryTracker tracker; diff --git a/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/post-filter.xml b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/post-filter.xml new file mode 100644 index 0000000000..3331cb8610 --- /dev/null +++ b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/post-filter.xml @@ -0,0 +1,47 @@ + + + + + + + prefix:sal-netconf-connector + controller-config + 1830 + 20000 + 2000 + 1.5 + admin + + prefix:dom-broker-osgi-registry + dom-broker + + + prefix:netconf-client-dispatcher + global-netconf-dispatcher + + admin +
      127.0.0.1
      + + prefix:threadpool + global-netconf-processing-executor + + false + + prefix:binding-broker-osgi-registry + binding-osgi-broker + + 0 + + prefix:netty-event-executor + global-event-executor + +
      +
      +
      +
      \ No newline at end of file diff --git a/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/pre-filter.xml b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/pre-filter.xml new file mode 100644 index 0000000000..f2620bbb4d --- /dev/null +++ b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/pre-filter.xml @@ -0,0 +1,52 @@ + + + + + + + prefix:sal-netconf-connector + controller-config + 1830 + 20000 + 2000 + 1.5 + admin + + prefix:dom-broker-osgi-registry + dom-broker + + + prefix:netconf-client-dispatcher + global-netconf-dispatcher + + admin +
      127.0.0.1
      + + prefix:threadpool + global-netconf-processing-executor + + false + + prefix:binding-broker-osgi-registry + binding-osgi-broker + + 0 + + prefix:netty-event-executor + global-event-executor + +
      + + prefix:shutdown + shutdown + + +
      +
      +
      \ No newline at end of file diff --git a/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/request.xml b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/request.xml new file mode 100644 index 0000000000..259b123bdf --- /dev/null +++ b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/10/request.xml @@ -0,0 +1,15 @@ + + + + + + + + + x:sal-netconf-connector + controller-config + + + + + diff --git a/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/post-filter.xml b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/post-filter.xml new file mode 100644 index 0000000000..afe9655326 --- /dev/null +++ b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/post-filter.xml @@ -0,0 +1,14 @@ + + + + + + fred + x:admin + Fred Flintstone + + + + + \ No newline at end of file diff --git a/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/pre-filter.xml b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/pre-filter.xml new file mode 100644 index 0000000000..eca3241f05 --- /dev/null +++ b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/pre-filter.xml @@ -0,0 +1,40 @@ + + + + + + root + superuser + Charlie Root + + 1 + 1 + + + + fred + x:admin + Fred Flintstone + + 2 + 2 + + + + barney + admin + Barney Rubble + + 2 + 3 + + + + + + admin + + + + + \ No newline at end of file diff --git a/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/request.xml b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/request.xml new file mode 100644 index 0000000000..47da0feec1 --- /dev/null +++ b/opendaylight/netconf/netconf-impl/src/test/resources/subtree/9/request.xml @@ -0,0 +1,19 @@ + + + + + + + + + + fred + a:admin + + + + + + + \ No newline at end of file diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java index d8eb841a79..cc170358dd 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java @@ -7,7 +7,7 @@ */ package org.opendaylight.controller.netconf.it; -import static junit.framework.Assert.assertEquals; +import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; diff --git a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java index 1adcd7e491..6e265a44a5 100644 --- a/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java +++ b/opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java @@ -21,14 +21,23 @@ import com.google.common.collect.Lists; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import io.netty.channel.EventLoopGroup; import io.netty.channel.local.LocalAddress; +import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.GlobalEventExecutor; import java.io.IOException; import java.net.InetSocketAddress; +import java.nio.file.Files; import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.sshd.server.PasswordAuthenticator; +import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.server.session.ServerSession; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -40,13 +49,13 @@ import org.opendaylight.controller.netconf.client.NetconfClientDispatcher; import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl; import org.opendaylight.controller.netconf.client.NetconfClientSessionListener; import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener; +import org.opendaylight.controller.netconf.client.TestingNetconfClient; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder; -import org.opendaylight.controller.netconf.client.TestingNetconfClient; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword; -import org.opendaylight.controller.netconf.ssh.NetconfSSHServer; -import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator; +import org.opendaylight.controller.netconf.ssh.SshProxyServer; +import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder; import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil; import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil; import org.opendaylight.controller.netconf.util.xml.XmlUtil; @@ -68,19 +77,39 @@ public class NetconfITSecureTest extends AbstractNetconfConfigTest { public static final String USERNAME = "user"; public static final String PASSWORD = "pwd"; - private NetconfSSHServer sshServer; + private SshProxyServer sshProxyServer; + + private ExecutorService nioExec; + private EventLoopGroup clientGroup; + private ScheduledExecutorService minaTimerEx; @Before public void setUp() throws Exception { - final char[] pem = PEMGenerator.generate().toCharArray(); - sshServer = NetconfSSHServer.start(TLS_ADDRESS.getPort(), NetconfConfigUtil.getNetconfLocalAddress(), getNettyThreadgroup(), pem); - sshServer.setAuthProvider(getAuthProvider()); + nioExec = Executors.newFixedThreadPool(1); + clientGroup = new NioEventLoopGroup(); + minaTimerEx = Executors.newScheduledThreadPool(1); + sshProxyServer = new SshProxyServer(minaTimerEx, clientGroup, nioExec); + sshProxyServer.bind( + new SshProxyServerConfigurationBuilder() + .setBindingAddress(TLS_ADDRESS) + .setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress()) + .setAuthenticator(new PasswordAuthenticator() { + @Override + public boolean authenticate(final String username, final String password, final ServerSession session) { + return true; + } + }) + .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString())) + .setIdleTimeout(Integer.MAX_VALUE) + .createSshProxyServerConfiguration()); } @After public void tearDown() throws Exception { - sshServer.close(); - sshServer.join(); + sshProxyServer.close(); + clientGroup.shutdownGracefully().await(); + minaTimerEx.shutdownNow(); + nioExec.shutdownNow(); } @Test diff --git a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/GetTest.java b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/GetTest.java index 5fceac06dd..5a744fda14 100644 --- a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/GetTest.java +++ b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/GetTest.java @@ -8,13 +8,12 @@ package org.opendaylight.controller.netconf.monitoring; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertTrue; -import static junit.framework.TestCase.fail; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; - import java.util.Collections; import org.hamcrest.CoreMatchers; import org.junit.Before; diff --git a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivatorTest.java b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivatorTest.java index 40493569d6..b5b9f3c060 100644 --- a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivatorTest.java +++ b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringActivatorTest.java @@ -8,6 +8,12 @@ package org.opendaylight.controller.netconf.monitoring.osgi; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.util.Arrays; import org.junit.Before; import org.junit.Test; @@ -18,10 +24,6 @@ import org.osgi.framework.Filter; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.*; - public class NetconfMonitoringActivatorTest { @Mock @@ -34,7 +36,7 @@ public class NetconfMonitoringActivatorTest { MockitoAnnotations.initMocks(this); doReturn(filter).when(context).createFilter(anyString()); doNothing().when(context).addServiceListener(any(ServiceListener.class), anyString()); - ServiceReference[] refs = new ServiceReference[2]; + ServiceReference[] refs = new ServiceReference[2]; doReturn(Arrays.asList(refs)).when(context).getServiceReferences(any(Class.class), anyString()); doReturn(refs).when(context).getServiceReferences(anyString(), anyString()); } diff --git a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTrackerTest.java b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTrackerTest.java index 2a53a6ce45..b992b0e44f 100644 --- a/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTrackerTest.java +++ b/opendaylight/netconf/netconf-monitoring/src/test/java/org/opendaylight/controller/netconf/monitoring/osgi/NetconfMonitoringServiceTrackerTest.java @@ -8,6 +8,12 @@ package org.opendaylight.controller.netconf.monitoring.osgi; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.util.Hashtable; import org.junit.Before; import org.junit.Test; @@ -20,18 +26,14 @@ import org.osgi.framework.Filter; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyCollection; -import static org.mockito.Mockito.*; - public class NetconfMonitoringServiceTrackerTest { @Mock - private ServiceReference reference; + private ServiceReference reference; @Mock private BundleContext context; @Mock - private ServiceRegistration serviceRegistration; + private ServiceRegistration serviceRegistration; @Mock private Filter filter; @Mock diff --git a/opendaylight/netconf/netconf-netty-util/pom.xml b/opendaylight/netconf/netconf-netty-util/pom.xml index e2afcc42f5..f1f7375f0a 100644 --- a/opendaylight/netconf/netconf-netty-util/pom.xml +++ b/opendaylight/netconf/netconf-netty-util/pom.xml @@ -48,10 +48,6 @@ org.opendaylight.controller protocol-framework - - org.opendaylight.controller.thirdparty - ganymed - org.apache.sshd sshd-core @@ -89,7 +85,7 @@ maven-bundle-plugin - org.apache.sshd.*, ch.ethz.ssh2, com.google.common.base, com.google.common.collect, io.netty.buffer, + org.apache.sshd.*, com.google.common.base, com.google.common.collect, io.netty.buffer, io.netty.channel, io.netty.channel.socket, io.netty.handler.codec, io.netty.handler.ssl, io.netty.util, io.netty.util.concurrent, javax.xml.transform, javax.xml.transform.dom, javax.xml.transform.sax, javax.xml.transform.stream, org.opendaylight.controller.netconf.api, @@ -108,7 +104,6 @@ org.apache.maven.plugins maven-jar-plugin - 2.4 diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/exi/EXIParameters.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/exi/EXIParameters.java index 531ba3ccb7..ccd7dead9f 100644 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/exi/EXIParameters.java +++ b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/exi/EXIParameters.java @@ -48,18 +48,18 @@ public final class EXIParameters { final String alignmentTextContent = alignmentElement.getTextContent().trim(); switch (alignmentTextContent) { - case EXI_PARAMETER_BIT_PACKED: - options.setAlignmentType(AlignmentType.bitPacked); - break; - case EXI_PARAMETER_BYTE_ALIGNED: - options.setAlignmentType(AlignmentType.byteAligned); - break; - case EXI_PARAMETER_COMPRESSED: - options.setAlignmentType(AlignmentType.compress); - break; - case EXI_PARAMETER_PRE_COMPRESSION: - options.setAlignmentType(AlignmentType.preCompress); - break; + case EXI_PARAMETER_BIT_PACKED: + options.setAlignmentType(AlignmentType.bitPacked); + break; + case EXI_PARAMETER_BYTE_ALIGNED: + options.setAlignmentType(AlignmentType.byteAligned); + break; + case EXI_PARAMETER_COMPRESSED: + options.setAlignmentType(AlignmentType.compress); + break; + case EXI_PARAMETER_PRE_COMPRESSION: + options.setAlignmentType(AlignmentType.preCompress); + break; } } diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java index 3bd7232023..fa7d0900ed 100644 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java +++ b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java @@ -8,12 +8,9 @@ package org.opendaylight.controller.netconf.nettyutil.handler.ssh.client; -import com.google.common.base.Preconditions; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelOutboundHandlerAdapter; -import io.netty.channel.ChannelPromise; import java.io.IOException; import java.net.SocketAddress; + import org.apache.sshd.ClientChannel; import org.apache.sshd.ClientSession; import org.apache.sshd.SshClient; @@ -26,6 +23,13 @@ import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication. import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.base.Preconditions; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelOutboundHandlerAdapter; +import io.netty.channel.ChannelPromise; + /** * Netty SSH handler class. Acts as interface between Netty and SSH library. */ @@ -47,7 +51,7 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { private final AuthenticationHandler authenticationHandler; private final SshClient sshClient; - private AsyncSshHanderReader sshReadAsyncListener; + private AsyncSshHandlerReader sshReadAsyncListener; private AsyncSshHandlerWriter sshWriteAsyncHandler; private ClientChannel channel; @@ -138,7 +142,20 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { connectPromise.setSuccess(); connectPromise = null; - sshReadAsyncListener = new AsyncSshHanderReader(this, ctx, channel.getAsyncOut()); + // TODO we should also read from error stream and at least log from that + + sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() { + @Override + public void close() throws Exception { + AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()); + } + }, new AsyncSshHandlerReader.ReadMsgHandler() { + @Override + public void onMessageRead(final ByteBuf msg) { + ctx.fireChannelRead(msg); + } + }, channel.toString(), channel.getAsyncOut()); + // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null if(channel != null) { sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn()); diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHanderReader.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java similarity index 66% rename from opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHanderReader.java rename to opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java index 73a24f27b2..ada15583cd 100644 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHanderReader.java +++ b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java @@ -8,9 +8,8 @@ package org.opendaylight.controller.netconf.nettyutil.handler.ssh.client; +import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelOutboundHandler; import org.apache.sshd.common.future.SshFutureListener; import org.apache.sshd.common.io.IoInputStream; import org.apache.sshd.common.io.IoReadFuture; @@ -22,22 +21,24 @@ import org.slf4j.LoggerFactory; * Listener on async input stream from SSH session. * This listeners schedules reads in a loop until the session is closed or read fails. */ -final class AsyncSshHanderReader implements SshFutureListener, AutoCloseable { +public final class AsyncSshHandlerReader implements SshFutureListener, AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(AsyncSshHandler.class); private static final int BUFFER_SIZE = 8192; - private final ChannelOutboundHandler asyncSshHandler; - private final ChannelHandlerContext ctx; + private final AutoCloseable connectionClosedCallback; + private final ReadMsgHandler readHandler; + private final String channelId; private IoInputStream asyncOut; private Buffer buf; private IoReadFuture currentReadFuture; - public AsyncSshHanderReader(final ChannelOutboundHandler asyncSshHandler, final ChannelHandlerContext ctx, final IoInputStream asyncOut) { - this.asyncSshHandler = asyncSshHandler; - this.ctx = ctx; + public AsyncSshHandlerReader(final AutoCloseable connectionClosedCallback, final ReadMsgHandler readHandler, final String channelId, final IoInputStream asyncOut) { + this.connectionClosedCallback = connectionClosedCallback; + this.readHandler = readHandler; + this.channelId = channelId; this.asyncOut = asyncOut; buf = new Buffer(BUFFER_SIZE); asyncOut.read(buf).addListener(this); @@ -48,16 +49,20 @@ final class AsyncSshHanderReader implements SshFutureListener, Aut if(future.getException() != null) { if(asyncOut.isClosed() || asyncOut.isClosing()) { // Ssh dropped - logger.debug("Ssh session dropped on channel: {}", ctx.channel(), future.getException()); + logger.debug("Ssh session dropped on channel: {}", channelId, future.getException()); } else { - logger.warn("Exception while reading from SSH remote on channel {}", ctx.channel(), future.getException()); + logger.warn("Exception while reading from SSH remote on channel {}", channelId, future.getException()); } invokeDisconnect(); return; } if (future.getRead() > 0) { - ctx.fireChannelRead(Unpooled.wrappedBuffer(buf.array(), 0, future.getRead())); + final ByteBuf msg = Unpooled.wrappedBuffer(buf.array(), 0, future.getRead()); + if(logger.isTraceEnabled()) { + logger.trace("Reading message on channel: {}, message: {}", channelId, AsyncSshHandlerWriter.byteBufToString(msg)); + } + readHandler.onMessageRead(msg); // Schedule next read buf = new Buffer(BUFFER_SIZE); @@ -68,7 +73,7 @@ final class AsyncSshHanderReader implements SshFutureListener, Aut private void invokeDisconnect() { try { - asyncSshHandler.disconnect(ctx, ctx.newPromise()); + connectionClosedCallback.close(); } catch (final Exception e) { // This should not happen throw new IllegalStateException(e); @@ -80,8 +85,14 @@ final class AsyncSshHanderReader implements SshFutureListener, Aut // Remove self as listener on close to prevent reading from closed input if(currentReadFuture != null) { currentReadFuture.removeListener(this); + currentReadFuture = null; } asyncOut = null; } + + public interface ReadMsgHandler { + + void onMessageRead(ByteBuf msg); + } } diff --git a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerWriter.java b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerWriter.java index eace0ac7ea..8e639bd47c 100644 --- a/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerWriter.java +++ b/opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerWriter.java @@ -28,7 +28,7 @@ import org.slf4j.LoggerFactory; * Async Ssh writer. Takes messages(byte arrays) and sends them encrypted to remote server. * Also handles pending writes by caching requests until pending state is over. */ -final class AsyncSshHandlerWriter implements AutoCloseable { +public final class AsyncSshHandlerWriter implements AutoCloseable { private static final Logger logger = LoggerFactory .getLogger(AsyncSshHandlerWriter.class); @@ -116,7 +116,7 @@ final class AsyncSshHandlerWriter implements AutoCloseable { writeWithPendingDetection(pendingWrite.ctx, pendingWrite.promise, msg); } - private static String byteBufToString(final ByteBuf msg) { + public static String byteBufToString(final ByteBuf msg) { msg.resetReaderIndex(); final String s = msg.toString(Charsets.UTF_8); msg.resetReaderIndex(); diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java index 93475129d2..556bece43f 100644 --- a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java @@ -11,7 +11,6 @@ package org.opendaylight.controller.netconf.nettyutil.handler; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.doAnswer; - import com.google.common.collect.Lists; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -50,7 +49,7 @@ public class ChunkedFramingMechanismEncoderTest { @Test public void testEncode() throws Exception { final List chunks = Lists.newArrayList(); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { chunks.add((ByteBuf) invocation.getArguments()[0]); diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfEXIHandlersTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfEXIHandlersTest.java index 4a8db176fe..8bc0fb8e82 100644 --- a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfEXIHandlersTest.java +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfEXIHandlersTest.java @@ -8,15 +8,14 @@ package org.opendaylight.controller.netconf.nettyutil.handler; -import static org.junit.Assert.*; - +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; import com.google.common.collect.Lists; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.custommonkey.xmlunit.XMLUnit; diff --git a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java index d0fc43d04a..b4c9e1e950 100644 --- a/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java +++ b/opendaylight/netconf/netconf-netty-util/src/test/java/org/opendaylight/controller/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java @@ -22,10 +22,17 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; - +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.SettableFuture; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; import java.io.IOException; import java.net.SocketAddress; - import org.apache.sshd.ClientChannel; import org.apache.sshd.ClientSession; import org.apache.sshd.SshClient; @@ -52,17 +59,6 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.SettableFuture; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelPromise; - public class AsyncSshHandlerTest { @Mock @@ -126,7 +122,7 @@ public class AsyncSshHandlerTest { private > ListenableFuture> stubAddListener(final T future) { final SettableFuture> listenerSettableFuture = SettableFuture.create(); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { listenerSettableFuture.set((SshFutureListener) invocation.getArguments()[0]); @@ -459,6 +455,8 @@ public class AsyncSshHandlerTest { private ChannelSubsystem getMockedSubsystemChannel(final IoInputStream asyncOut, final IoOutputStream asyncIn) throws IOException { final ChannelSubsystem subsystemChannel = mock(ChannelSubsystem.class); + doReturn("subsystemChannel").when(subsystemChannel).toString(); + doNothing().when(subsystemChannel).setStreaming(any(ClientChannel.Streaming.class)); final OpenFuture openFuture = mock(OpenFuture.class); diff --git a/opendaylight/netconf/netconf-ssh/pom.xml b/opendaylight/netconf/netconf-ssh/pom.xml index 221626b741..e0c7dba4fa 100644 --- a/opendaylight/netconf/netconf-ssh/pom.xml +++ b/opendaylight/netconf/netconf-ssh/pom.xml @@ -36,10 +36,6 @@ org.bouncycastle bcprov-jdk15on - - org.opendaylight.controller.thirdparty - ganymed - org.apache.sshd sshd-core @@ -60,7 +56,6 @@ org.opendaylight.controller netconf-netty-util - test org.opendaylight.controller diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/NetconfSSHServer.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/NetconfSSHServer.java deleted file mode 100644 index 86206a7d5c..0000000000 --- a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/NetconfSSHServer.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.netconf.ssh; - -import com.google.common.base.Preconditions; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; - -import javax.annotation.concurrent.ThreadSafe; - -import org.opendaylight.controller.netconf.auth.AuthProvider; -import org.opendaylight.controller.netconf.ssh.threads.Handshaker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Optional; - -import io.netty.channel.EventLoopGroup; -import io.netty.channel.local.LocalAddress; - -/** - * Thread that accepts client connections. Accepted socket is forwarded to {@link org.opendaylight.controller.netconf.ssh.threads.Handshaker}, - * which is executed in {@link #handshakeExecutor}. - */ -@ThreadSafe -public final class NetconfSSHServer extends Thread implements AutoCloseable { - - private static final Logger logger = LoggerFactory.getLogger(NetconfSSHServer.class); - private static final AtomicLong sessionIdCounter = new AtomicLong(); - - private final ServerSocket serverSocket; - private final LocalAddress localAddress; - private final EventLoopGroup bossGroup; - private Optional authProvider = Optional.absent(); - private final ExecutorService handshakeExecutor; - private final char[] pem; - private volatile boolean up; - - private NetconfSSHServer(final int serverPort, final LocalAddress localAddress, final EventLoopGroup bossGroup, final char[] pem) throws IOException { - super(NetconfSSHServer.class.getSimpleName()); - this.bossGroup = bossGroup; - this.pem = pem; - logger.trace("Creating SSH server socket on port {}", serverPort); - this.serverSocket = new ServerSocket(serverPort); - if (serverSocket.isBound() == false) { - throw new IllegalStateException("Socket can't be bound to requested port :" + serverPort); - } - logger.trace("Server socket created."); - this.localAddress = localAddress; - this.up = true; - handshakeExecutor = Executors.newFixedThreadPool(10); - } - - public static NetconfSSHServer start(final int serverPort, final LocalAddress localAddress, final EventLoopGroup bossGroup, final char[] pemArray) throws IOException { - final NetconfSSHServer netconfSSHServer = new NetconfSSHServer(serverPort, localAddress, bossGroup, pemArray); - netconfSSHServer.start(); - return netconfSSHServer; - } - - public synchronized AuthProvider getAuthProvider() { - Preconditions.checkState(authProvider.isPresent(), "AuthenticationProvider is not set up, cannot authenticate user"); - return authProvider.get(); - } - - public synchronized void setAuthProvider(final AuthProvider authProvider) { - if(this.authProvider != null) { - logger.debug("Changing auth provider to {}", authProvider); - } - this.authProvider = Optional.fromNullable(authProvider); - } - - @Override - public void close() throws IOException { - up = false; - logger.trace("Closing SSH server socket."); - serverSocket.close(); - bossGroup.shutdownGracefully(); - logger.trace("SSH server socket closed."); - } - - @VisibleForTesting - public InetSocketAddress getLocalSocketAddress() { - return (InetSocketAddress) serverSocket.getLocalSocketAddress(); - } - - @Override - public void run() { - while (up) { - Socket acceptedSocket = null; - try { - acceptedSocket = serverSocket.accept(); - } catch (final IOException e) { - if (up == false) { - logger.trace("Exiting server thread", e); - } else { - logger.warn("Exception occurred during socket.accept", e); - } - } - if (acceptedSocket != null) { - try { - final Handshaker task = new Handshaker(acceptedSocket, localAddress, sessionIdCounter.incrementAndGet(), getAuthProvider(), bossGroup, pem); - handshakeExecutor.submit(task); - } catch (final IOException e) { - logger.warn("Cannot set PEMHostKey, closing connection", e); - closeSocket(acceptedSocket); - } catch (final IllegalStateException e) { - logger.warn("Cannot accept connection, closing", e); - closeSocket(acceptedSocket); - } - } - } - logger.debug("Server thread is exiting"); - } - - private void closeSocket(final Socket acceptedSocket) { - try { - acceptedSocket.close(); - } catch (final IOException e) { - logger.warn("Ignoring exception while closing socket", e); - } - } - -} diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/RemoteNetconfCommand.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/RemoteNetconfCommand.java new file mode 100644 index 0000000000..e642e073a3 --- /dev/null +++ b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/RemoteNetconfCommand.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.ssh; + +import com.google.common.base.Preconditions; +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.local.LocalAddress; +import io.netty.channel.local.LocalChannel; +import io.netty.util.concurrent.GenericFutureListener; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import org.apache.sshd.common.NamedFactory; +import org.apache.sshd.common.io.IoInputStream; +import org.apache.sshd.common.io.IoOutputStream; +import org.apache.sshd.server.AsyncCommand; +import org.apache.sshd.server.Command; +import org.apache.sshd.server.Environment; +import org.apache.sshd.server.ExitCallback; +import org.apache.sshd.server.SessionAware; +import org.apache.sshd.server.session.ServerSession; +import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This command handles all netconf related rpc and forwards to delegate server. + * Uses netty to make a local connection to delegate server. + * + * Command is Apache Mina SSH terminology for objects handling ssh data. + */ +public class RemoteNetconfCommand implements AsyncCommand, SessionAware { + + private static final Logger logger = LoggerFactory.getLogger(RemoteNetconfCommand.class); + + private final EventLoopGroup clientEventGroup; + private final LocalAddress localAddress; + + private IoInputStream in; + private IoOutputStream out; + private ExitCallback callback; + private NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader; + + private Channel clientChannel; + private ChannelFuture clientChannelFuture; + + public RemoteNetconfCommand(final EventLoopGroup clientEventGroup, final LocalAddress localAddress) { + this.clientEventGroup = clientEventGroup; + this.localAddress = localAddress; + } + + @Override + public void setIoInputStream(final IoInputStream in) { + this.in = in; + } + + @Override + public void setIoOutputStream(final IoOutputStream out) { + this.out = out; + } + + @Override + public void setIoErrorStream(final IoOutputStream err) { + // TODO do we want to use error stream in some way ? + } + + @Override + public void setInputStream(final InputStream in) { + throw new UnsupportedOperationException("Synchronous IO is unsupported"); + } + + @Override + public void setOutputStream(final OutputStream out) { + throw new UnsupportedOperationException("Synchronous IO is unsupported"); + + } + + @Override + public void setErrorStream(final OutputStream err) { + throw new UnsupportedOperationException("Synchronous IO is unsupported"); + + } + + @Override + public void setExitCallback(final ExitCallback callback) { + this.callback = callback; + } + + @Override + public void start(final Environment env) throws IOException { + logger.trace("Establishing internal connection to netconf server for client: {}", getClientAddress()); + + final Bootstrap clientBootstrap = new Bootstrap(); + clientBootstrap.group(clientEventGroup).channel(LocalChannel.class); + + clientBootstrap + .handler(new ChannelInitializer() { + @Override + public void initChannel(final LocalChannel ch) throws Exception { + ch.pipeline().addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback)); + } + }); + clientChannelFuture = clientBootstrap.connect(localAddress); + clientChannelFuture.addListener(new GenericFutureListener() { + + @Override + public void operationComplete(final ChannelFuture future) throws Exception { + if(future.isSuccess()) { + clientChannel = clientChannelFuture.channel(); + } else { + logger.warn("Unable to establish internal connection to netconf server for client: {}", getClientAddress()); + Preconditions.checkNotNull(callback, "Exit callback must be set"); + callback.onExit(1, "Unable to establish internal connection to netconf server for client: "+ getClientAddress()); + } + } + }); + } + + @Override + public void destroy() { + logger.trace("Releasing internal connection to netconf server for client: {} on channel: {}", + getClientAddress(), clientChannel); + + clientChannelFuture.cancel(true); + if(clientChannel != null) { + clientChannel.close().addListener(new GenericFutureListener() { + + @Override + public void operationComplete(final ChannelFuture future) throws Exception { + if (future.isSuccess() == false) { + logger.warn("Unable to release internal connection to netconf server on channel: {}", clientChannel); + } + } + }); + } + } + + private String getClientAddress() { + return netconfHelloMessageAdditionalHeader.getAddress(); + } + + @Override + public void setSession(final ServerSession session) { + final SocketAddress remoteAddress = session.getIoSession().getRemoteAddress(); + String hostName = ""; + String port = ""; + if(remoteAddress instanceof InetSocketAddress) { + hostName = ((InetSocketAddress) remoteAddress).getAddress().getHostAddress(); + port = Integer.toString(((InetSocketAddress) remoteAddress).getPort()); + } + netconfHelloMessageAdditionalHeader = new NetconfHelloMessageAdditionalHeader( + session.getUsername(), hostName, port, "ssh", "client"); + } + + public static class NetconfCommandFactory implements NamedFactory { + + public static final String NETCONF = "netconf"; + + private final EventLoopGroup clientBootstrap; + private final LocalAddress localAddress; + + public NetconfCommandFactory(final EventLoopGroup clientBootstrap, final LocalAddress localAddress) { + + this.clientBootstrap = clientBootstrap; + this.localAddress = localAddress; + } + + @Override + public String getName() { + return NETCONF; + } + + @Override + public RemoteNetconfCommand create() { + return new RemoteNetconfCommand(clientBootstrap, localAddress); + } + } + +} diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyClientHandler.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyClientHandler.java new file mode 100644 index 0000000000..2b2b3b3e81 --- /dev/null +++ b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyClientHandler.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.ssh; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import org.apache.sshd.common.io.IoInputStream; +import org.apache.sshd.common.io.IoOutputStream; +import org.apache.sshd.server.ExitCallback; +import org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerReader; +import org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter; +import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Netty handler that reads SSH from remote client and writes to delegate server and reads from delegate server and writes to remote client + */ +final class SshProxyClientHandler extends ChannelInboundHandlerAdapter { + + private static final Logger logger = LoggerFactory.getLogger(SshProxyClientHandler.class); + + private final IoInputStream in; + private final IoOutputStream out; + + private AsyncSshHandlerReader asyncSshHandlerReader; + private AsyncSshHandlerWriter asyncSshHandlerWriter; + + private final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader; + private final ExitCallback callback; + + public SshProxyClientHandler(final IoInputStream in, final IoOutputStream out, + final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader, + final ExitCallback callback) { + this.in = in; + this.out = out; + this.netconfHelloMessageAdditionalHeader = netconfHelloMessageAdditionalHeader; + this.callback = callback; + } + + @Override + public void channelActive(final ChannelHandlerContext ctx) throws Exception { + writeAdditionalHeader(ctx); + + asyncSshHandlerWriter = new AsyncSshHandlerWriter(out); + asyncSshHandlerReader = new AsyncSshHandlerReader(new AutoCloseable() { + @Override + public void close() throws Exception { + // Close both sessions (delegate server and remote client) + ctx.fireChannelInactive(); + ctx.disconnect(); + ctx.close(); + asyncSshHandlerReader.close(); + asyncSshHandlerWriter.close(); + } + }, new AsyncSshHandlerReader.ReadMsgHandler() { + @Override + public void onMessageRead(final ByteBuf msg) { + if(logger.isTraceEnabled()) { + logger.trace("Forwarding message for client: {} on channel: {}, message: {}", + netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(), AsyncSshHandlerWriter.byteBufToString(msg)); + } + // Just forward to delegate + ctx.writeAndFlush(msg); + } + }, "ssh" + netconfHelloMessageAdditionalHeader.getAddress(), in); + + + super.channelActive(ctx); + } + + private void writeAdditionalHeader(final ChannelHandlerContext ctx) { + ctx.writeAndFlush(Unpooled.copiedBuffer(netconfHelloMessageAdditionalHeader.toFormattedString().getBytes())); + } + + @Override + public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { + asyncSshHandlerWriter.write(ctx, msg, ctx.newPromise()); + } + + @Override + public void channelInactive(final ChannelHandlerContext ctx) throws Exception { + logger.debug("Internal connection to netconf server was dropped for client: {} on channel: ", + netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel()); + callback.onExit(1, "Internal connection to netconf server was dropped for client: " + + netconfHelloMessageAdditionalHeader.getAddress() + " on channel: " + ctx.channel()); + super.channelInactive(ctx); + } + + +} diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServer.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServer.java new file mode 100644 index 0000000000..8728f0c671 --- /dev/null +++ b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServer.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.ssh; + +import com.google.common.collect.Lists; +import io.netty.channel.EventLoopGroup; +import java.io.IOException; +import java.nio.channels.AsynchronousChannelGroup; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.apache.sshd.SshServer; +import org.apache.sshd.common.FactoryManager; +import org.apache.sshd.common.NamedFactory; +import org.apache.sshd.common.RuntimeSshException; +import org.apache.sshd.common.io.IoAcceptor; +import org.apache.sshd.common.io.IoConnector; +import org.apache.sshd.common.io.IoHandler; +import org.apache.sshd.common.io.IoServiceFactory; +import org.apache.sshd.common.io.IoServiceFactoryFactory; +import org.apache.sshd.common.io.nio2.Nio2Acceptor; +import org.apache.sshd.common.io.nio2.Nio2Connector; +import org.apache.sshd.common.io.nio2.Nio2ServiceFactoryFactory; +import org.apache.sshd.common.util.CloseableUtils; +import org.apache.sshd.server.Command; +import org.apache.sshd.server.ServerFactoryManager; + +/** + * Proxy SSH server that just delegates decrypted content to a delegate server within same VM. + * Implemented using Apache Mina SSH lib. + */ +public class SshProxyServer implements AutoCloseable { + + private final SshServer sshServer; + private final ScheduledExecutorService minaTimerExecutor; + private final EventLoopGroup clientGroup; + private final IoServiceFactoryFactory nioServiceWithPoolFactoryFactory; + + public SshProxyServer(final ScheduledExecutorService minaTimerExecutor, final EventLoopGroup clientGroup, final ExecutorService nioExecutor) { + this.minaTimerExecutor = minaTimerExecutor; + this.clientGroup = clientGroup; + this.nioServiceWithPoolFactoryFactory = new NioServiceWithPoolFactory.NioServiceWithPoolFactoryFactory(nioExecutor); + this.sshServer = SshServer.setUpDefaultServer(); + } + + public void bind(final SshProxyServerConfiguration sshProxyServerConfiguration) throws IOException { + sshServer.setHost(sshProxyServerConfiguration.getBindingAddress().getHostString()); + sshServer.setPort(sshProxyServerConfiguration.getBindingAddress().getPort()); + + sshServer.setPasswordAuthenticator(sshProxyServerConfiguration.getAuthenticator()); + sshServer.setKeyPairProvider(sshProxyServerConfiguration.getKeyPairProvider()); + + sshServer.setIoServiceFactoryFactory(nioServiceWithPoolFactoryFactory); + sshServer.setScheduledExecutorService(minaTimerExecutor); + sshServer.setProperties(getProperties(sshProxyServerConfiguration)); + + final RemoteNetconfCommand.NetconfCommandFactory netconfCommandFactory = + new RemoteNetconfCommand.NetconfCommandFactory(clientGroup, sshProxyServerConfiguration.getLocalAddress()); + sshServer.setSubsystemFactories(Lists.>newArrayList(netconfCommandFactory)); + sshServer.start(); + } + + private static Map getProperties(final SshProxyServerConfiguration sshProxyServerConfiguration) { + return new HashMap() + {{ + put(ServerFactoryManager.IDLE_TIMEOUT, String.valueOf(sshProxyServerConfiguration.getIdleTimeout())); + }}; + } + + @Override + public void close() { + try { + sshServer.stop(true); + } catch (final InterruptedException e) { + throw new RuntimeException("Interrupted while stopping sshServer", e); + } finally { + sshServer.close(true); + } + } + + /** + * Based on Nio2ServiceFactory with one addition: injectable executor + */ + private static final class NioServiceWithPoolFactory extends CloseableUtils.AbstractCloseable implements IoServiceFactory { + + private final FactoryManager manager; + private final AsynchronousChannelGroup group; + + public NioServiceWithPoolFactory(final FactoryManager manager, final ExecutorService executor) { + this.manager = manager; + try { + group = AsynchronousChannelGroup.withThreadPool(executor); + } catch (final IOException e) { + throw new RuntimeSshException(e); + } + } + + public IoConnector createConnector(final IoHandler handler) { + return new Nio2Connector(manager, handler, group); + } + + public IoAcceptor createAcceptor(final IoHandler handler) { + return new Nio2Acceptor(manager, handler, group); + } + + @Override + protected void doCloseImmediately() { + try { + group.shutdownNow(); + group.awaitTermination(5, TimeUnit.SECONDS); + } catch (final Exception e) { + log.debug("Exception caught while closing channel group", e); + } finally { + super.doCloseImmediately(); + } + } + + private static final class NioServiceWithPoolFactoryFactory extends Nio2ServiceFactoryFactory { + + private final ExecutorService nioExecutor; + + private NioServiceWithPoolFactoryFactory(final ExecutorService nioExecutor) { + this.nioExecutor = nioExecutor; + } + + @Override + public IoServiceFactory create(final FactoryManager manager) { + return new NioServiceWithPoolFactory(manager, nioExecutor); + } + } + } + +} diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServerConfiguration.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServerConfiguration.java new file mode 100644 index 0000000000..aee3c7b725 --- /dev/null +++ b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServerConfiguration.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.ssh; + +import com.google.common.base.Preconditions; +import io.netty.channel.local.LocalAddress; +import java.net.InetSocketAddress; +import org.apache.sshd.common.KeyPairProvider; +import org.apache.sshd.server.PasswordAuthenticator; + +public final class SshProxyServerConfiguration { + private final InetSocketAddress bindingAddress; + private final LocalAddress localAddress; + private final PasswordAuthenticator authenticator; + private final KeyPairProvider keyPairProvider; + private final int idleTimeout; + + SshProxyServerConfiguration(final InetSocketAddress bindingAddress, final LocalAddress localAddress, final PasswordAuthenticator authenticator, final KeyPairProvider keyPairProvider, final int idleTimeout) { + this.bindingAddress = Preconditions.checkNotNull(bindingAddress); + this.localAddress = Preconditions.checkNotNull(localAddress); + this.authenticator = Preconditions.checkNotNull(authenticator); + this.keyPairProvider = Preconditions.checkNotNull(keyPairProvider); + // Idle timeout cannot be disabled in the sshd by using =< 0 value + Preconditions.checkArgument(idleTimeout > 0, "Idle timeout has to be > 0"); + this.idleTimeout = idleTimeout; + } + + public InetSocketAddress getBindingAddress() { + return bindingAddress; + } + + public LocalAddress getLocalAddress() { + return localAddress; + } + + public PasswordAuthenticator getAuthenticator() { + return authenticator; + } + + public KeyPairProvider getKeyPairProvider() { + return keyPairProvider; + } + + public int getIdleTimeout() { + return idleTimeout; + } + + +} diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServerConfigurationBuilder.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServerConfigurationBuilder.java new file mode 100644 index 0000000000..fb8632b99e --- /dev/null +++ b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/SshProxyServerConfigurationBuilder.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.ssh; + +import io.netty.channel.local.LocalAddress; +import java.net.InetSocketAddress; +import org.apache.sshd.common.KeyPairProvider; +import org.apache.sshd.server.PasswordAuthenticator; + +public final class SshProxyServerConfigurationBuilder { + private InetSocketAddress bindingAddress; + private LocalAddress localAddress; + private PasswordAuthenticator authenticator; + private KeyPairProvider keyPairProvider; + private int idleTimeout; + + public SshProxyServerConfigurationBuilder setBindingAddress(final InetSocketAddress bindingAddress) { + this.bindingAddress = bindingAddress; + return this; + } + + public SshProxyServerConfigurationBuilder setLocalAddress(final LocalAddress localAddress) { + this.localAddress = localAddress; + return this; + } + + public SshProxyServerConfigurationBuilder setAuthenticator(final PasswordAuthenticator authenticator) { + this.authenticator = authenticator; + return this; + } + + public SshProxyServerConfigurationBuilder setKeyPairProvider(final KeyPairProvider keyPairProvider) { + this.keyPairProvider = keyPairProvider; + return this; + } + + public SshProxyServerConfigurationBuilder setIdleTimeout(final int idleTimeout) { + this.idleTimeout = idleTimeout; + return this; + } + + public SshProxyServerConfiguration createSshProxyServerConfiguration() { + return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, keyPairProvider, idleTimeout); + } + + public SshProxyServerConfigurationBuilder create () { + return new SshProxyServerConfigurationBuilder(); + } +} \ No newline at end of file diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/authentication/PEMGenerator.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/authentication/PEMGenerator.java deleted file mode 100644 index 53ab8219ee..0000000000 --- a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/authentication/PEMGenerator.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.netconf.ssh.authentication; - -import com.google.common.annotations.VisibleForTesting; -import java.io.FileInputStream; -import java.security.NoSuchAlgorithmException; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.bouncycastle.openssl.PEMWriter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.SecureRandom; - -public class PEMGenerator { - private static final Logger logger = LoggerFactory.getLogger(PEMGenerator.class); - private static final int KEY_SIZE = 4096; - - - public static String readOrGeneratePK(File privateKeyFile) throws IOException { - if (privateKeyFile.exists() == false) { - // generate & save to file - try { - return generateTo(privateKeyFile); - } catch (Exception e) { - logger.error("Exception occurred while generating PEM string to {}", privateKeyFile, e); - throw new IllegalStateException("Error generating RSA key from file " + privateKeyFile); - } - } else { - // read from file - try (FileInputStream fis = new FileInputStream(privateKeyFile)) { - return IOUtils.toString(fis); - } catch (final IOException e) { - logger.error("Error reading RSA key from file {}", privateKeyFile, e); - throw new IOException("Error reading RSA key from file " + privateKeyFile, e); - } - } - } - - /** - * Generate private key to a file and return its content as string. - * - * @param privateFile path where private key should be generated - * @return String representation of private key - * @throws IOException - * @throws NoSuchAlgorithmException - */ - @VisibleForTesting - public static String generateTo(File privateFile) throws IOException, NoSuchAlgorithmException { - logger.info("Generating private key to {}", privateFile.getAbsolutePath()); - String privatePEM = generate(); - FileUtils.write(privateFile, privatePEM); - return privatePEM; - } - - @VisibleForTesting - public static String generate() throws NoSuchAlgorithmException, IOException { - KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); - SecureRandom sr = new SecureRandom(); - keyGen.initialize(KEY_SIZE, sr); - KeyPair keypair = keyGen.generateKeyPair(); - return toString(keypair.getPrivate()); - } - - /** - * Get string representation of a key. - */ - private static String toString(Key key) throws IOException { - try (StringWriter writer = new StringWriter()) { - try (PEMWriter pemWriter = new PEMWriter(writer)) { - pemWriter.writeObject(key); - } - return writer.toString(); - } - } - -} diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/osgi/AuthProviderTracker.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/osgi/AuthProviderTracker.java new file mode 100644 index 0000000000..97e611c0d2 --- /dev/null +++ b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/osgi/AuthProviderTracker.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.controller.netconf.ssh.osgi; + +import com.google.common.base.Preconditions; +import org.apache.sshd.server.PasswordAuthenticator; +import org.apache.sshd.server.session.ServerSession; +import org.opendaylight.controller.netconf.auth.AuthConstants; +import org.opendaylight.controller.netconf.auth.AuthProvider; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.util.tracker.ServiceTracker; +import org.osgi.util.tracker.ServiceTrackerCustomizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +final class AuthProviderTracker implements ServiceTrackerCustomizer, PasswordAuthenticator { + private static final Logger logger = LoggerFactory.getLogger(AuthProviderTracker.class); + + private final BundleContext bundleContext; + + private Integer maxPreference; + private final ServiceTracker listenerTracker; + private AuthProvider authProvider; + + public AuthProviderTracker(final BundleContext bundleContext) { + this.bundleContext = bundleContext; + listenerTracker = new ServiceTracker<>(bundleContext, AuthProvider.class, this); + listenerTracker.open(); + } + + @Override + public AuthProvider addingService(final ServiceReference reference) { + logger.trace("Service {} added", reference); + final AuthProvider authService = bundleContext.getService(reference); + final Integer newServicePreference = getPreference(reference); + if(isBetter(newServicePreference)) { + maxPreference = newServicePreference; + this.authProvider = authService; + } + return authService; + } + + private Integer getPreference(final ServiceReference reference) { + final Object preferenceProperty = reference.getProperty(AuthConstants.SERVICE_PREFERENCE_KEY); + return preferenceProperty == null ? Integer.MIN_VALUE : Integer.valueOf(preferenceProperty.toString()); + } + + private boolean isBetter(final Integer newServicePreference) { + Preconditions.checkNotNull(newServicePreference); + if(maxPreference == null) { + return true; + } + + return newServicePreference > maxPreference; + } + + @Override + public void modifiedService(final ServiceReference reference, final AuthProvider service) { + final AuthProvider authService = bundleContext.getService(reference); + final Integer newServicePreference = getPreference(reference); + if(isBetter(newServicePreference)) { + logger.trace("Replacing modified service {} in netconf SSH.", reference); + this.authProvider = authService; + } + } + + @Override + public void removedService(final ServiceReference reference, final AuthProvider service) { + logger.trace("Removing service {} from netconf SSH. " + + "SSH won't authenticate users until AuthProvider service will be started.", reference); + maxPreference = null; + this.authProvider = null; + } + + public void stop() { + listenerTracker.close(); + // sshThread should finish normally since sshServer.close stops processing + } + + @Override + public boolean authenticate(final String username, final String password, final ServerSession session) { + return authProvider == null ? false : authProvider.authenticated(username, password); + } +} diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/osgi/NetconfSSHActivator.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/osgi/NetconfSSHActivator.java index 0d0f95c3cb..5fc04eee83 100644 --- a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/osgi/NetconfSSHActivator.java +++ b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/osgi/NetconfSSHActivator.java @@ -9,51 +9,54 @@ package org.opendaylight.controller.netconf.ssh.osgi; import static com.google.common.base.Preconditions.checkState; -import com.google.common.base.Preconditions; -import java.io.File; +import com.google.common.base.Optional; +import com.google.common.base.Strings; +import io.netty.channel.local.LocalAddress; +import io.netty.channel.nio.NioEventLoopGroup; import java.io.IOException; import java.net.InetSocketAddress; - +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; import org.apache.commons.io.FilenameUtils; -import org.opendaylight.controller.netconf.auth.AuthConstants; -import org.opendaylight.controller.netconf.auth.AuthProvider; -import org.opendaylight.controller.netconf.ssh.NetconfSSHServer; -import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator; +import org.apache.sshd.common.util.ThreadUtils; +import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.opendaylight.controller.netconf.ssh.SshProxyServer; +import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder; import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil; import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil.InfixProp; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.util.tracker.ServiceTracker; -import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.base.Optional; -import com.google.common.base.Strings; - -import io.netty.channel.EventLoopGroup; -import io.netty.channel.local.LocalAddress; -import io.netty.channel.nio.NioEventLoopGroup; - -/** - * Activator for netconf SSH bundle which creates SSH bridge between netconf client and netconf server. Activator - * starts SSH Server in its own thread. This thread is closed when activator calls stop() method. Server opens socket - * and listens for client connections. Each client connection creation is handled in separate - * {@link org.opendaylight.controller.netconf.ssh.threads.Handshaker} thread. - * This thread creates two additional threads {@link org.opendaylight.controller.netconf.ssh.threads.IOThread} - * forwarding data from/to client.IOThread closes servers session and server connection when it gets -1 on input stream. - * {@link org.opendaylight.controller.netconf.ssh.threads.IOThread}'s run method waits for -1 on input stream to finish. - * All threads are daemons. - */ public class NetconfSSHActivator implements BundleActivator { private static final Logger logger = LoggerFactory.getLogger(NetconfSSHActivator.class); - private static AuthProviderTracker authProviderTracker; - private NetconfSSHServer server; + private static final java.lang.String ALGORITHM = "RSA"; + private static final int KEY_SIZE = 4096; + public static final int POOL_SIZE = 8; + private static final int DEFAULT_IDLE_TIMEOUT = (int) TimeUnit.MINUTES.toMillis(20); + + private ScheduledExecutorService minaTimerExecutor; + private NioEventLoopGroup clientGroup; + private ExecutorService nioExecutor; + private AuthProviderTracker authProviderTracker; + + private SshProxyServer server; @Override public void start(final BundleContext bundleContext) throws IOException { + minaTimerExecutor = Executors.newScheduledThreadPool(POOL_SIZE, new ThreadFactory() { + @Override + public Thread newThread(final Runnable r) { + return new Thread(r, "netconf-ssh-server-mina-timers"); + } + }); + clientGroup = new NioEventLoopGroup(); + nioExecutor = ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", POOL_SIZE); server = startSSHServer(bundleContext); } @@ -66,11 +69,22 @@ public class NetconfSSHActivator implements BundleActivator { if(authProviderTracker != null) { authProviderTracker.stop(); } + + if(nioExecutor!=null) { + nioExecutor.shutdownNow(); + } + + if(clientGroup != null) { + clientGroup.shutdownGracefully(); + } + + if(minaTimerExecutor != null) { + minaTimerExecutor.shutdownNow(); + } } - private static NetconfSSHServer startSSHServer(final BundleContext bundleContext) throws IOException { - final Optional maybeSshSocketAddress = NetconfConfigUtil.extractNetconfServerAddress(bundleContext, - InfixProp.ssh); + private SshProxyServer startSSHServer(final BundleContext bundleContext) throws IOException { + final Optional maybeSshSocketAddress = NetconfConfigUtil.extractNetconfServerAddress(bundleContext, InfixProp.ssh); if (maybeSshSocketAddress.isPresent() == false) { logger.trace("SSH bridge not configured"); @@ -82,92 +96,22 @@ public class NetconfSSHActivator implements BundleActivator { final LocalAddress localAddress = NetconfConfigUtil.getNetconfLocalAddress(); - final String path = FilenameUtils.separatorsToSystem(NetconfConfigUtil.getPrivateKeyPath(bundleContext)); - checkState(!Strings.isNullOrEmpty(path), "Path to ssh private key is blank. Reconfigure %s", NetconfConfigUtil.getPrivateKeyKey()); - final String privateKeyPEMString = PEMGenerator.readOrGeneratePK(new File(path)); - - final EventLoopGroup bossGroup = new NioEventLoopGroup(); - final NetconfSSHServer server = NetconfSSHServer.start(sshSocketAddress.getPort(), localAddress, bossGroup, privateKeyPEMString.toCharArray()); - - authProviderTracker = new AuthProviderTracker(bundleContext, server); + authProviderTracker = new AuthProviderTracker(bundleContext); - return server; - } - - private static Thread runNetconfSshThread(final NetconfSSHServer server) { - final Thread serverThread = new Thread(server, "netconf SSH server thread"); - serverThread.setDaemon(true); - serverThread.start(); - logger.trace("Netconf SSH bridge up and running."); - return serverThread; + final String path = FilenameUtils.separatorsToSystem(NetconfConfigUtil.getPrivateKeyPath(bundleContext)); + checkState(!Strings.isNullOrEmpty(path), "Path to ssh private key is blank. Reconfigure %s", + NetconfConfigUtil.getPrivateKeyKey()); + + final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerExecutor, clientGroup, nioExecutor); + sshProxyServer.bind( + new SshProxyServerConfigurationBuilder() + .setBindingAddress(sshSocketAddress) + .setLocalAddress(localAddress) + .setAuthenticator(authProviderTracker) + .setKeyPairProvider(new PEMGeneratorHostKeyProvider(path, ALGORITHM, KEY_SIZE)) + .setIdleTimeout(DEFAULT_IDLE_TIMEOUT) + .createSshProxyServerConfiguration()); + return sshProxyServer; } - private static class AuthProviderTracker implements ServiceTrackerCustomizer { - private final BundleContext bundleContext; - private final NetconfSSHServer server; - - private Integer maxPreference; - private Thread sshThread; - private final ServiceTracker listenerTracker; - - public AuthProviderTracker(final BundleContext bundleContext, final NetconfSSHServer server) { - this.bundleContext = bundleContext; - this.server = server; - listenerTracker = new ServiceTracker<>(bundleContext, AuthProvider.class, this); - listenerTracker.open(); - } - - @Override - public AuthProvider addingService(final ServiceReference reference) { - logger.trace("Service {} added", reference); - final AuthProvider authService = bundleContext.getService(reference); - final Integer newServicePreference = getPreference(reference); - if(isBetter(newServicePreference)) { - maxPreference = newServicePreference; - server.setAuthProvider(authService); - if(sshThread == null) { - sshThread = runNetconfSshThread(server); - } - } - return authService; - } - - private Integer getPreference(final ServiceReference reference) { - final Object preferenceProperty = reference.getProperty(AuthConstants.SERVICE_PREFERENCE_KEY); - return preferenceProperty == null ? Integer.MIN_VALUE : Integer.valueOf(preferenceProperty.toString()); - } - - private boolean isBetter(final Integer newServicePreference) { - Preconditions.checkNotNull(newServicePreference); - if(maxPreference == null) { - return true; - } - - return newServicePreference > maxPreference; - } - - @Override - public void modifiedService(final ServiceReference reference, final AuthProvider service) { - final AuthProvider authService = bundleContext.getService(reference); - final Integer newServicePreference = getPreference(reference); - if(isBetter(newServicePreference)) { - logger.trace("Replacing modified service {} in netconf SSH.", reference); - server.setAuthProvider(authService); - } - } - - @Override - public void removedService(final ServiceReference reference, final AuthProvider service) { - logger.trace("Removing service {} from netconf SSH. " + - "SSH won't authenticate users until AuthProvider service will be started.", reference); - maxPreference = null; - server.setAuthProvider(null); - } - - public void stop() { - listenerTracker.close(); - // sshThread should finish normally since sshServer.close stops processing - } - - } } diff --git a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/threads/Handshaker.java b/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/threads/Handshaker.java deleted file mode 100644 index eec6c3a097..0000000000 --- a/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/threads/Handshaker.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.netconf.ssh.threads; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; - -import javax.annotation.concurrent.NotThreadSafe; -import javax.annotation.concurrent.ThreadSafe; - -import org.opendaylight.controller.netconf.auth.AuthProvider; -import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.ethz.ssh2.AuthenticationResult; -import ch.ethz.ssh2.PtySettings; -import ch.ethz.ssh2.ServerAuthenticationCallback; -import ch.ethz.ssh2.ServerConnection; -import ch.ethz.ssh2.ServerConnectionCallback; -import ch.ethz.ssh2.ServerSession; -import ch.ethz.ssh2.ServerSessionCallback; -import ch.ethz.ssh2.SimpleServerSessionCallback; - -import com.google.common.base.Supplier; - -import io.netty.bootstrap.Bootstrap; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufProcessor; -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.local.LocalAddress; -import io.netty.channel.local.LocalChannel; -import io.netty.handler.stream.ChunkedStream; - -/** - * One instance represents per connection, responsible for ssh handshake. - * Once auth succeeds and correct subsystem is chosen, backend connection with - * netty netconf server is made. This task finishes right after negotiation is done. - */ -@ThreadSafe -public class Handshaker implements Runnable { - private static final Logger logger = LoggerFactory.getLogger(Handshaker.class); - - private final ServerConnection ganymedConnection; - private final String session; - - - public Handshaker(Socket socket, LocalAddress localAddress, long sessionId, AuthProvider authProvider, - EventLoopGroup bossGroup, final char[] pem) throws IOException { - - this.session = "Session " + sessionId; - - String remoteAddressWithPort = socket.getRemoteSocketAddress().toString().replace("/", ""); - logger.debug("{} started with {}", session, remoteAddressWithPort); - String remoteAddress, remotePort; - if (remoteAddressWithPort.contains(":")) { - String[] split = remoteAddressWithPort.split(":"); - remoteAddress = split[0]; - remotePort = split[1]; - } else { - remoteAddress = remoteAddressWithPort; - remotePort = ""; - } - ServerAuthenticationCallbackImpl serverAuthenticationCallback = new ServerAuthenticationCallbackImpl( - authProvider, session); - - ganymedConnection = new ServerConnection(socket); - - ServerConnectionCallbackImpl serverConnectionCallback = new ServerConnectionCallbackImpl( - serverAuthenticationCallback, remoteAddress, remotePort, session, - getGanymedAutoCloseable(ganymedConnection), localAddress, bossGroup); - - // initialize ganymed - ganymedConnection.setPEMHostKey(pem, null); - ganymedConnection.setAuthenticationCallback(serverAuthenticationCallback); - ganymedConnection.setServerConnectionCallback(serverConnectionCallback); - } - - - private static AutoCloseable getGanymedAutoCloseable(final ServerConnection ganymedConnection) { - return new AutoCloseable() { - @Override - public void close() throws Exception { - ganymedConnection.close(); - } - }; - } - - @Override - public void run() { - // let ganymed process handshake - logger.trace("{} is started", session); - try { - // TODO this should be guarded with a timer to prevent resource exhaustion - ganymedConnection.connect(); - } catch (IOException e) { - logger.debug("{} connection error", session, e); - } - logger.trace("{} is exiting", session); - } -} - -/** - * Netty client handler that forwards bytes from backed server to supplied output stream. - * When backend server closes the connection, remoteConnection.close() is called to tear - * down ssh connection. - */ -class SSHClientHandler extends ChannelInboundHandlerAdapter { - private static final Logger logger = LoggerFactory.getLogger(SSHClientHandler.class); - private final AutoCloseable remoteConnection; - private final BufferedOutputStream remoteOutputStream; - private final String session; - private ChannelHandlerContext channelHandlerContext; - - public SSHClientHandler(AutoCloseable remoteConnection, OutputStream remoteOutputStream, - String session) { - this.remoteConnection = remoteConnection; - this.remoteOutputStream = new BufferedOutputStream(remoteOutputStream); - this.session = session; - } - - @Override - public void channelActive(ChannelHandlerContext ctx) { - this.channelHandlerContext = ctx; - logger.debug("{} Client active", session); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException { - ByteBuf bb = (ByteBuf) msg; - // we can block the server here so that slow client does not cause memory pressure - try { - bb.forEachByte(new ByteBufProcessor() { - @Override - public boolean process(byte value) throws Exception { - remoteOutputStream.write(value); - return true; - } - }); - } finally { - bb.release(); - } - } - - @Override - public void channelReadComplete(ChannelHandlerContext ctx) throws IOException { - logger.trace("{} Flushing", session); - remoteOutputStream.flush(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - // Close the connection when an exception is raised. - logger.warn("{} Unexpected exception from downstream", session, cause); - ctx.close(); - } - - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - logger.trace("{} channelInactive() called, closing remote client ctx", session); - remoteConnection.close();//this should close socket and all threads created for this client - this.channelHandlerContext = null; - } - - public ChannelHandlerContext getChannelHandlerContext() { - return checkNotNull(channelHandlerContext, "Channel is not active"); - } -} - -/** - * Ganymed handler that gets unencrypted input and output streams, connects them to netty. - * Checks that 'netconf' subsystem is chosen by user. - * Launches new ClientInputStreamPoolingThread thread once session is established. - * Writes custom header to netty server, to inform it about IP address and username. - */ -class ServerConnectionCallbackImpl implements ServerConnectionCallback { - private static final Logger logger = LoggerFactory.getLogger(ServerConnectionCallbackImpl.class); - public static final String NETCONF_SUBSYSTEM = "netconf"; - - private final Supplier currentUserSupplier; - private final String remoteAddress; - private final String remotePort; - private final String session; - private final AutoCloseable ganymedConnection; - private final LocalAddress localAddress; - private final EventLoopGroup bossGroup; - - ServerConnectionCallbackImpl(Supplier currentUserSupplier, String remoteAddress, String remotePort, String session, - AutoCloseable ganymedConnection, LocalAddress localAddress, EventLoopGroup bossGroup) { - this.currentUserSupplier = currentUserSupplier; - this.remoteAddress = remoteAddress; - this.remotePort = remotePort; - this.session = session; - this.ganymedConnection = ganymedConnection; - // initialize netty local connection - this.localAddress = localAddress; - this.bossGroup = bossGroup; - } - - private static ChannelFuture initializeNettyConnection(LocalAddress localAddress, EventLoopGroup bossGroup, - final SSHClientHandler sshClientHandler) { - Bootstrap clientBootstrap = new Bootstrap(); - clientBootstrap.group(bossGroup).channel(LocalChannel.class); - - clientBootstrap.handler(new ChannelInitializer() { - @Override - public void initChannel(LocalChannel ch) throws Exception { - ch.pipeline().addLast(sshClientHandler); - } - }); - // asynchronously initialize local connection to netconf server - return clientBootstrap.connect(localAddress); - } - - @Override - public ServerSessionCallback acceptSession(final ServerSession serverSession) { - String currentUser = currentUserSupplier.get(); - final String additionalHeader = new NetconfHelloMessageAdditionalHeader(currentUser, remoteAddress, - remotePort, "ssh", "client").toFormattedString(); - - - return new SimpleServerSessionCallback() { - @Override - public Runnable requestSubsystem(final ServerSession ss, final String subsystem) throws IOException { - return new Runnable() { - @Override - public void run() { - if (NETCONF_SUBSYSTEM.equals(subsystem)) { - // connect - final SSHClientHandler sshClientHandler = new SSHClientHandler(ganymedConnection, ss.getStdin(), session); - ChannelFuture clientChannelFuture = initializeNettyConnection(localAddress, bossGroup, sshClientHandler); - // get channel - final Channel channel = clientChannelFuture.awaitUninterruptibly().channel(); - - // write additional header before polling thread is started - // polling thread could process and forward data before additional header is written - // This will result into unexpected state: hello message without additional header and the next message with additional header - channel.writeAndFlush(Unpooled.copiedBuffer(additionalHeader.getBytes())); - - new ClientInputStreamPoolingThread(session, ss.getStdout(), channel, new AutoCloseable() { - @Override - public void close() throws Exception { - logger.trace("Closing both ganymed and local connection"); - try { - ganymedConnection.close(); - } catch (Exception e) { - logger.warn("Ignoring exception while closing ganymed", e); - } - try { - channel.close(); - } catch (Exception e) { - logger.warn("Ignoring exception while closing channel", e); - } - } - }, sshClientHandler.getChannelHandlerContext()).start(); - } else { - logger.debug("{} Wrong subsystem requested:'{}', closing ssh session", serverSession, subsystem); - String reason = "Only netconf subsystem is supported, requested:" + subsystem; - closeSession(ss, reason); - } - } - }; - } - - public void closeSession(ServerSession ss, String reason) { - logger.trace("{} Closing session - {}", serverSession, reason); - try { - ss.getStdin().write(reason.getBytes()); - } catch (IOException e) { - logger.warn("{} Exception while closing session", serverSession, e); - } - ss.close(); - } - - @Override - public Runnable requestPtyReq(final ServerSession ss, final PtySettings pty) throws IOException { - return new Runnable() { - @Override - public void run() { - closeSession(ss, "PTY request not supported"); - } - }; - } - - @Override - public Runnable requestShell(final ServerSession ss) throws IOException { - return new Runnable() { - @Override - public void run() { - closeSession(ss, "Shell not supported"); - } - }; - } - }; - } -} - -/** - * Only thread that is required during ssh session, forwards client's input to netty. - * When user closes connection, onEndOfInput.close() is called to tear down the local channel. - */ -class ClientInputStreamPoolingThread extends Thread { - private static final Logger logger = LoggerFactory.getLogger(ClientInputStreamPoolingThread.class); - - private final InputStream fromClientIS; - private final Channel serverChannel; - private final AutoCloseable onEndOfInput; - private final ChannelHandlerContext channelHandlerContext; - - ClientInputStreamPoolingThread(String session, InputStream fromClientIS, Channel serverChannel, AutoCloseable onEndOfInput, - ChannelHandlerContext channelHandlerContext) { - super(ClientInputStreamPoolingThread.class.getSimpleName() + " " + session); - this.fromClientIS = fromClientIS; - this.serverChannel = serverChannel; - this.onEndOfInput = onEndOfInput; - this.channelHandlerContext = channelHandlerContext; - } - - @Override - public void run() { - ChunkedStream chunkedStream = new ChunkedStream(fromClientIS); - try { - ByteBuf byteBuf; - while ((byteBuf = chunkedStream.readChunk(channelHandlerContext/*only needed for ByteBuf alloc */)) != null) { - serverChannel.writeAndFlush(byteBuf); - } - } catch (Exception e) { - logger.warn("Exception", e); - } finally { - logger.trace("End of input"); - // tear down connection - try { - onEndOfInput.close(); - } catch (Exception e) { - logger.warn("Ignoring exception while closing socket", e); - } - } - } -} - -/** - * Authentication handler for ganymed. - * Provides current user name after authenticating using supplied AuthProvider. - */ -@NotThreadSafe -class ServerAuthenticationCallbackImpl implements ServerAuthenticationCallback, Supplier { - private static final Logger logger = LoggerFactory.getLogger(ServerAuthenticationCallbackImpl.class); - private final AuthProvider authProvider; - private final String session; - private String currentUser; - - ServerAuthenticationCallbackImpl(AuthProvider authProvider, String session) { - this.authProvider = authProvider; - this.session = session; - } - - @Override - public String initAuthentication(ServerConnection sc) { - logger.trace("{} Established connection", session); - return "Established connection" + "\r\n"; - } - - @Override - public String[] getRemainingAuthMethods(ServerConnection sc) { - return new String[]{ServerAuthenticationCallback.METHOD_PASSWORD}; - } - - @Override - public AuthenticationResult authenticateWithNone(ServerConnection sc, String username) { - return AuthenticationResult.FAILURE; - } - - @Override - public AuthenticationResult authenticateWithPassword(ServerConnection sc, String username, String password) { - checkState(currentUser == null); - try { - if (authProvider.authenticated(username, password)) { - currentUser = username; - logger.trace("{} user {} authenticated", session, currentUser); - return AuthenticationResult.SUCCESS; - } - } catch (Exception e) { - logger.warn("{} Authentication failed", session, e); - } - return AuthenticationResult.FAILURE; - } - - @Override - public AuthenticationResult authenticateWithPublicKey(ServerConnection sc, String username, String algorithm, - byte[] publicKey, byte[] signature) { - return AuthenticationResult.FAILURE; - } - - @Override - public String get() { - return currentUser; - } -} diff --git a/opendaylight/netconf/netconf-ssh/src/test/java/org/opendaylight/controller/netconf/netty/SSHTest.java b/opendaylight/netconf/netconf-ssh/src/test/java/org/opendaylight/controller/netconf/netty/SSHTest.java index eb2b644cbc..34b236b461 100644 --- a/opendaylight/netconf/netconf-ssh/src/test/java/org/opendaylight/controller/netconf/netty/SSHTest.java +++ b/opendaylight/netconf/netconf-ssh/src/test/java/org/opendaylight/controller/netconf/netty/SSHTest.java @@ -11,9 +11,6 @@ package org.opendaylight.controller.netconf.netty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; import com.google.common.base.Stopwatch; import io.netty.bootstrap.Bootstrap; @@ -23,16 +20,22 @@ import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.HashedWheelTimer; import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Before; +import org.apache.sshd.server.PasswordAuthenticator; +import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.server.session.ServerSession; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; -import org.opendaylight.controller.netconf.auth.AuthProvider; import org.opendaylight.controller.netconf.netty.EchoClientHandler.State; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandler; -import org.opendaylight.controller.netconf.ssh.NetconfSSHServer; -import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator; +import org.opendaylight.controller.netconf.ssh.SshProxyServer; +import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder; import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,68 +43,77 @@ import org.slf4j.LoggerFactory; public class SSHTest { public static final Logger logger = LoggerFactory.getLogger(SSHTest.class); public static final String AHOJ = "ahoj\n"; - private EventLoopGroup nettyGroup; - HashedWheelTimer hashedWheelTimer; - @Before - public void setUp() throws Exception { + private static EventLoopGroup nettyGroup; + private static HashedWheelTimer hashedWheelTimer; + private static ExecutorService nioExec; + private static ScheduledExecutorService minaTimerEx; + + @BeforeClass + public static void setUp() throws Exception { hashedWheelTimer = new HashedWheelTimer(); nettyGroup = new NioEventLoopGroup(); + nioExec = Executors.newFixedThreadPool(1); + minaTimerEx = Executors.newScheduledThreadPool(1); } - @After - public void tearDown() throws Exception { + @AfterClass + public static void tearDown() throws Exception { hashedWheelTimer.stop(); - nettyGroup.shutdownGracefully(); + nettyGroup.shutdownGracefully().await(); + minaTimerEx.shutdownNow(); + nioExec.shutdownNow(); } @Test public void test() throws Exception { new Thread(new EchoServer(), "EchoServer").start(); - AuthProvider authProvider = mock(AuthProvider.class); - doReturn(true).when(authProvider).authenticated(anyString(), anyString()); - doReturn("auth").when(authProvider).toString(); - - NetconfSSHServer netconfSSHServer = NetconfSSHServer.start(10831, NetconfConfigUtil.getNetconfLocalAddress(), - new NioEventLoopGroup(), PEMGenerator.generate().toCharArray()); - netconfSSHServer.setAuthProvider(authProvider); - InetSocketAddress address = netconfSSHServer.getLocalSocketAddress(); + final InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10831); + final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerEx, nettyGroup, nioExec); + sshProxyServer.bind( + new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress()).setAuthenticator(new PasswordAuthenticator() { + @Override + public boolean authenticate(final String username, final String password, final ServerSession session) { + return true; + } + }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration()); - final EchoClientHandler echoClientHandler = connectClient(new InetSocketAddress("localhost", address.getPort())); + final EchoClientHandler echoClientHandler = connectClient(addr); Stopwatch stopwatch = new Stopwatch().start(); - while(echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 5) { - Thread.sleep(100); + while(echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) { + Thread.sleep(500); } assertTrue(echoClientHandler.isConnected()); logger.info("connected, writing to client"); echoClientHandler.write(AHOJ); + // check that server sent back the same string stopwatch = stopwatch.reset().start(); - while (echoClientHandler.read().endsWith(AHOJ) == false && stopwatch.elapsed(TimeUnit.SECONDS) < 5) { - Thread.sleep(100); + while (echoClientHandler.read().endsWith(AHOJ) == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) { + Thread.sleep(500); } + try { - String read = echoClientHandler.read(); + final String read = echoClientHandler.read(); assertTrue(read + " should end with " + AHOJ, read.endsWith(AHOJ)); } finally { logger.info("Closing socket"); - netconfSSHServer.close(); - netconfSSHServer.join(); + sshProxyServer.close(); } } - public EchoClientHandler connectClient(InetSocketAddress address) { + public EchoClientHandler connectClient(final InetSocketAddress address) { final EchoClientHandler echoClientHandler = new EchoClientHandler(); - ChannelInitializer channelInitializer = new ChannelInitializer() { + final ChannelInitializer channelInitializer = new ChannelInitializer() { @Override - public void initChannel(NioSocketChannel ch) throws Exception { + public void initChannel(final NioSocketChannel ch) throws Exception { ch.pipeline().addFirst(AsyncSshHandler.createForNetconfSubsystem(new LoginPassword("a", "a"))); ch.pipeline().addLast(echoClientHandler); } }; - Bootstrap b = new Bootstrap(); + final Bootstrap b = new Bootstrap(); b.group(nettyGroup) .channel(NioSocketChannel.class) @@ -114,9 +126,9 @@ public class SSHTest { @Test public void testClientWithoutServer() throws Exception { - InetSocketAddress address = new InetSocketAddress(12345); + final InetSocketAddress address = new InetSocketAddress(12345); final EchoClientHandler echoClientHandler = connectClient(address); - Stopwatch stopwatch = new Stopwatch().start(); + final Stopwatch stopwatch = new Stopwatch().start(); while(echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) { Thread.sleep(100); } diff --git a/opendaylight/netconf/netconf-ssh/src/test/java/org/opendaylight/controller/netconf/ssh/authentication/SSHServerTest.java b/opendaylight/netconf/netconf-ssh/src/test/java/org/opendaylight/controller/netconf/ssh/authentication/SSHServerTest.java index 1151abcdf2..38aa2e71ac 100644 --- a/opendaylight/netconf/netconf-ssh/src/test/java/org/opendaylight/controller/netconf/ssh/authentication/SSHServerTest.java +++ b/opendaylight/netconf/netconf-ssh/src/test/java/org/opendaylight/controller/netconf/ssh/authentication/SSHServerTest.java @@ -12,19 +12,27 @@ import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; -import ch.ethz.ssh2.Connection; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; -import java.io.InputStream; import java.net.InetSocketAddress; -import junit.framework.Assert; -import org.apache.commons.io.IOUtils; +import java.nio.file.Files; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.apache.sshd.ClientSession; +import org.apache.sshd.SshClient; +import org.apache.sshd.client.future.AuthFuture; +import org.apache.sshd.client.future.ConnectFuture; +import org.apache.sshd.server.PasswordAuthenticator; +import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.server.session.ServerSession; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.opendaylight.controller.netconf.auth.AuthProvider; -import org.opendaylight.controller.netconf.ssh.NetconfSSHServer; +import org.opendaylight.controller.netconf.ssh.SshProxyServer; +import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder; import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceListener; @@ -39,13 +47,15 @@ public class SSHServerTest { private static final String PASSWORD = "netconf"; private static final String HOST = "127.0.0.1"; private static final int PORT = 1830; - private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 8383); private static final Logger logger = LoggerFactory.getLogger(SSHServerTest.class); - private Thread sshServerThread; + + private SshProxyServer server; @Mock private BundleContext mockedContext; - + private final ExecutorService nioExec = Executors.newFixedThreadPool(1); + private final EventLoopGroup clientGroup = new NioEventLoopGroup(); + private final ScheduledExecutorService minaTimerEx = Executors.newScheduledThreadPool(1); @Before public void setUp() throws Exception { @@ -55,42 +65,39 @@ public class SSHServerTest { doReturn(new ServiceReference[0]).when(mockedContext).getServiceReferences(anyString(), anyString()); logger.info("Creating SSH server"); - String pem; - try (InputStream is = getClass().getResourceAsStream("/RSA.pk")) { - pem = IOUtils.toString(is); - } - - EventLoopGroup bossGroup = new NioEventLoopGroup(); - NetconfSSHServer server = NetconfSSHServer.start(PORT, NetconfConfigUtil.getNetconfLocalAddress(), - bossGroup, pem.toCharArray()); - server.setAuthProvider(new AuthProvider() { - @Override - public boolean authenticated(final String username, final String password) { - return true; - } - }); - - sshServerThread = new Thread(server); - sshServerThread.setDaemon(true); - sshServerThread.start(); - logger.info("SSH server on " + PORT); + final InetSocketAddress addr = InetSocketAddress.createUnresolved(HOST, PORT); + server = new SshProxyServer(minaTimerEx, clientGroup, nioExec); + server.bind( + new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress()).setAuthenticator(new PasswordAuthenticator() { + @Override + public boolean authenticate(final String username, final String password, final ServerSession session) { + return true; + } + }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration()); + logger.info("SSH server started on " + PORT); } @Test - public void connect() { + public void connect() throws Exception { + final SshClient sshClient = SshClient.setUpDefaultClient(); + sshClient.start(); try { - Connection conn = new Connection(HOST, PORT); - Assert.assertNotNull(conn); - logger.info("connecting to SSH server"); - conn.connect(); - logger.info("authenticating ..."); - boolean isAuthenticated = conn.authenticateWithPassword(USER, PASSWORD); - Assert.assertTrue(isAuthenticated); - } catch (Exception e) { - logger.error("Error while starting SSH server.", e); + final ConnectFuture connect = sshClient.connect(USER, HOST, PORT); + connect.await(30, TimeUnit.SECONDS); + org.junit.Assert.assertTrue(connect.isConnected()); + final ClientSession session = connect.getSession(); + session.addPasswordIdentity(PASSWORD); + final AuthFuture auth = session.auth(); + auth.await(30, TimeUnit.SECONDS); + org.junit.Assert.assertTrue(auth.isSuccess()); + } finally { + sshClient.close(true); + server.close(); + clientGroup.shutdownGracefully().await(); + minaTimerEx.shutdownNow(); + nioExec.shutdownNow(); } - } } diff --git a/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/Main.java b/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/Main.java index 681b9a6a2d..e36d58591e 100644 --- a/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/Main.java +++ b/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/Main.java @@ -219,7 +219,7 @@ public final class Main { private final File configDir; private final List openDevices; - private final File ncFeatureFile; + private final List ncFeatureFiles; private final File etcDir; private final File loadOrderCfgFile; @@ -227,7 +227,7 @@ public final class Main { this.configDir = new File(directory, ETC_OPENDAYLIGHT_KARAF_PATH); this.etcDir = new File(directory, ETC_KARAF_PATH); this.loadOrderCfgFile = new File(etcDir, ORG_OPS4J_PAX_URL_MVN_CFG); - this.ncFeatureFile = getFeatureFile(directory, "features-netconf-connector"); + this.ncFeatureFiles = getFeatureFile(directory, "features-netconf-connector", "xml"); this.openDevices = openDevices; } @@ -309,37 +309,49 @@ public final class Main { public void updateFeatureFile(final List generated) { - // TODO karaf core contains jaxb for feature files, use that for modification + // TODO karaf core contains jaxb for feature files, use that for + // modification try { - final Document document = XmlUtil.readXmlToDocument(Files.toString(ncFeatureFile, Charsets.UTF_8)); - final NodeList childNodes = document.getDocumentElement().getChildNodes(); - - for (int i = 0; i < childNodes.getLength(); i++) { - final Node item = childNodes.item(i); - if(item instanceof Element == false) { - continue; - } - if(item.getLocalName().equals("feature") ==false) { - continue; - } - - if(NETCONF_CONNECTOR_ALL_FEATURE.equals(((Element) item).getAttribute("name"))) { - final Element ncAllFeatureDefinition = (Element) item; - // Clean previous generated files - for (final XmlElement configfile : XmlElement.fromDomElement(ncAllFeatureDefinition).getChildElements("configfile")) { - ncAllFeatureDefinition.removeChild(configfile.getDomElement()); + for (final File featureFile : ncFeatureFiles) { + final Document document = XmlUtil.readXmlToDocument(Files + .toString(featureFile, Charsets.UTF_8)); + final NodeList childNodes = document.getDocumentElement().getChildNodes(); + + for (int i = 0; i < childNodes.getLength(); i++) { + final Node item = childNodes.item(i); + if (item instanceof Element == false) { + continue; } - for (final File file : generated) { - final Element configfile = document.createElement("configfile"); - configfile.setTextContent("file:" + ETC_OPENDAYLIGHT_KARAF_PATH + file.getName()); - configfile.setAttribute("finalname", ETC_OPENDAYLIGHT_KARAF_PATH + file.getName()); - ncAllFeatureDefinition.appendChild(configfile); + if (item.getLocalName().equals("feature") == false) { + continue; + } + + if (NETCONF_CONNECTOR_ALL_FEATURE + .equals(((Element) item).getAttribute("name"))) { + final Element ncAllFeatureDefinition = (Element) item; + // Clean previous generated files + for (final XmlElement configfile : XmlElement + .fromDomElement(ncAllFeatureDefinition) + .getChildElements("configfile")) { + ncAllFeatureDefinition.removeChild(configfile.getDomElement()); + } + for (final File file : generated) { + final Element configfile = document.createElement("configfile"); + configfile.setTextContent("file:" + + ETC_OPENDAYLIGHT_KARAF_PATH + + file.getName()); + configfile.setAttribute( + "finalname", + ETC_OPENDAYLIGHT_KARAF_PATH + + file.getName()); + ncAllFeatureDefinition.appendChild(configfile); + } } } - } - Files.write(XmlUtil.toString(document), ncFeatureFile, Charsets.UTF_8); - LOG.info("Feature file {} updated", ncFeatureFile); + Files.write(XmlUtil.toString(document), featureFile,Charsets.UTF_8); + LOG.info("Feature file {} updated", featureFile); + } } catch (final IOException e) { throw new RuntimeException("Unable to load features file as a resource"); } catch (final SAXException e) { @@ -348,7 +360,7 @@ public final class Main { } - private static File getFeatureFile(final File distroFolder, final String featureName) { + private static List getFeatureFile(final File distroFolder, final String featureName, final String suffix) { checkExistingDir(distroFolder, String.format("Folder %s does not exist", distroFolder)); final File systemDir = checkExistingDir(new File(distroFolder, "system"), String.format("Folder %s does not contain a karaf distro, folder system is missing", distroFolder)); @@ -368,12 +380,13 @@ public final class Main { } }); - return newestVersionDir.listFiles(new FileFilter() { + return Lists.newArrayList(newestVersionDir.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { - return pathname.getName().contains(featureName); + return pathname.getName().contains(featureName) + && Files.getFileExtension(pathname.getName()).equals(suffix); } - })[0]; + })); } private static File checkExistingDir(final File folder, final String msg) { diff --git a/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/NetconfDeviceSimulator.java b/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/NetconfDeviceSimulator.java index d0939a288f..de68c31d29 100644 --- a/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/NetconfDeviceSimulator.java +++ b/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/NetconfDeviceSimulator.java @@ -19,13 +19,13 @@ import com.google.common.collect.Sets; import com.google.common.io.CharStreams; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.local.LocalAddress; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.HashedWheelTimer; import java.io.Closeable; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -34,6 +34,8 @@ import java.net.Inet4Address; import java.net.InetSocketAddress; import java.net.URI; import java.net.UnknownHostException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.AbstractMap; import java.util.Date; import java.util.HashMap; @@ -42,8 +44,15 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.apache.sshd.common.util.ThreadUtils; +import org.apache.sshd.server.PasswordAuthenticator; +import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; +import org.apache.sshd.server.session.ServerSession; import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession; import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer; @@ -58,8 +67,9 @@ import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot; import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService; -import org.opendaylight.controller.netconf.ssh.NetconfSSHServer; -import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator; +import org.opendaylight.controller.netconf.ssh.SshProxyServer; +import org.opendaylight.controller.netconf.ssh.SshProxyServerConfiguration; +import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; @@ -85,14 +95,22 @@ public class NetconfDeviceSimulator implements Closeable { private final NioEventLoopGroup nettyThreadgroup; private final HashedWheelTimer hashedWheelTimer; private final List devicesChannels = Lists.newArrayList(); + private final List sshWrappers = Lists.newArrayList(); + private final ScheduledExecutorService minaTimerExecutor; + private final ExecutorService nioExecutor; public NetconfDeviceSimulator() { - this(new NioEventLoopGroup(), new HashedWheelTimer()); + // TODO make pool size configurable + this(new NioEventLoopGroup(), new HashedWheelTimer(), + Executors.newScheduledThreadPool(8, new ThreadFactoryBuilder().setNameFormat("netconf-ssh-server-mina-timers-%d").build()), + ThreadUtils.newFixedThreadPool("netconf-ssh-server-nio-group", 8)); } - public NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer) { + private NetconfDeviceSimulator(final NioEventLoopGroup eventExecutors, final HashedWheelTimer hashedWheelTimer, final ScheduledExecutorService minaTimerExecutor, final ExecutorService nioExecutor) { this.nettyThreadgroup = eventExecutors; this.hashedWheelTimer = hashedWheelTimer; + this.minaTimerExecutor = minaTimerExecutor; + this.nioExecutor = nioExecutor; } private NetconfServerDispatcher createDispatcher(final Map moduleBuilders, final boolean exi, final int generateConfigsTimeout) { @@ -162,17 +180,23 @@ public class NetconfDeviceSimulator implements Closeable { int currentPort = params.startingPort; final List openDevices = Lists.newArrayList(); + + // Generate key to temp folder + final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider(); + for (int i = 0; i < params.deviceCount; i++) { final InetSocketAddress address = getAddress(currentPort); final ChannelFuture server; if(params.ssh) { + final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort); final LocalAddress tcpLocalAddress = new LocalAddress(address.toString()); server = dispatcher.createLocalServer(tcpLocalAddress); try { - final NetconfSSHServer sshServer = NetconfSSHServer.start(currentPort, tcpLocalAddress, nettyThreadgroup, getPemArray()); - sshServer.setAuthProvider(new AcceptingAuthProvider()); + final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup, nioExecutor); + sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress)); + sshWrappers.add(sshServer); } catch (final Exception e) { LOG.warn("Cannot start simulated device on {}, skipping", address, e); // Close local server and continue @@ -225,10 +249,27 @@ public class NetconfDeviceSimulator implements Closeable { return openDevices; } - private char[] getPemArray() { + private SshProxyServerConfiguration getSshConfiguration(final InetSocketAddress bindingAddress, final LocalAddress tcpLocalAddress) throws IOException { + return new SshProxyServerConfigurationBuilder() + .setBindingAddress(bindingAddress) + .setLocalAddress(tcpLocalAddress) + .setAuthenticator(new PasswordAuthenticator() { + @Override + public boolean authenticate(final String username, final String password, final ServerSession session) { + return true; + } + }) + .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString())) + .setIdleTimeout(Integer.MAX_VALUE) + .createSshProxyServerConfiguration(); + } + + private PEMGeneratorHostKeyProvider getPemGeneratorHostKeyProvider() { try { - return PEMGenerator.readOrGeneratePK(new File("PK")).toCharArray(); + final Path tempFile = Files.createTempFile("tempKeyNetconfTest", "suffix"); + return new PEMGeneratorHostKeyProvider(tempFile.toAbsolutePath().toString()); } catch (final IOException e) { + LOG.error("Unable to generate PEM key", e); throw new RuntimeException(e); } } @@ -317,10 +358,15 @@ public class NetconfDeviceSimulator implements Closeable { @Override public void close() { + for (final SshProxyServer sshWrapper : sshWrappers) { + sshWrapper.close(); + } for (final Channel deviceCh : devicesChannels) { deviceCh.close(); } nettyThreadgroup.shutdownGracefully(); + minaTimerExecutor.shutdownNow(); + nioExecutor.shutdownNow(); // close Everything } diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/mapping/AbstractNetconfOperation.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/mapping/AbstractNetconfOperation.java index b6f5854aa3..b7ebc51b70 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/mapping/AbstractNetconfOperation.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/mapping/AbstractNetconfOperation.java @@ -8,8 +8,8 @@ package org.opendaylight.controller.netconf.util.mapping; +import com.google.common.base.Optional; import java.util.Map; - import org.opendaylight.controller.netconf.api.NetconfDocumentedException; import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; import org.opendaylight.controller.netconf.mapping.api.HandlingPriority; @@ -17,20 +17,15 @@ import org.opendaylight.controller.netconf.mapping.api.NetconfOperation; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution; import org.opendaylight.controller.netconf.util.xml.XmlElement; import org.opendaylight.controller.netconf.util.xml.XmlUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import com.google.common.base.Optional; - public abstract class AbstractNetconfOperation implements NetconfOperation { private final String netconfSessionIdForReporting; - private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfOperation.class); - protected AbstractNetconfOperation(String netconfSessionIdForReporting) { + protected AbstractNetconfOperation(final String netconfSessionIdForReporting) { this.netconfSessionIdForReporting = netconfSessionIdForReporting; } @@ -39,7 +34,7 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { } @Override - public HandlingPriority canHandle(Document message) throws NetconfDocumentedException { + public HandlingPriority canHandle(final Document message) throws NetconfDocumentedException { OperationNameAndNamespace operationNameAndNamespace = null; operationNameAndNamespace = new OperationNameAndNamespace(message); return canHandle(operationNameAndNamespace.getOperationName(), operationNameAndNamespace.getNamespace()); @@ -49,7 +44,7 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { private final String operationName, namespace; private final XmlElement operationElement; - public OperationNameAndNamespace(Document message) throws NetconfDocumentedException { + public OperationNameAndNamespace(final Document message) throws NetconfDocumentedException { XmlElement requestElement = null; requestElement = getRequestElementWithCheck(message); operationElement = requestElement.getOnlyChildElement(); @@ -70,12 +65,12 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { } } - protected static XmlElement getRequestElementWithCheck(Document message) throws NetconfDocumentedException { + protected static XmlElement getRequestElementWithCheck(final Document message) throws NetconfDocumentedException { return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); } - protected HandlingPriority canHandle(String operationName, String operationNamespace) { + protected HandlingPriority canHandle(final String operationName, final String operationNamespace) { return operationName.equals(getOperationName()) && operationNamespace.equals(getOperationNamespace()) ? getHandlingPriority() : HandlingPriority.CANNOT_HANDLE; @@ -92,8 +87,8 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { protected abstract String getOperationName(); @Override - public Document handle(Document requestMessage, - NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException { + public Document handle(final Document requestMessage, + final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException { XmlElement requestElement = getRequestElementWithCheck(requestMessage); diff --git a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java index 78efe7e972..3c63204881 100644 --- a/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java +++ b/opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java @@ -37,6 +37,8 @@ import org.xml.sax.SAXException; public final class XmlElement { + public static final String DEFAULT_NAMESPACE_PREFIX = ""; + private final Element element; private static final Logger logger = LoggerFactory.getLogger(XmlElement.class); @@ -72,16 +74,16 @@ public final class XmlElement { return xmlElement; } - private static Map extractNamespaces(Element typeElement) throws NetconfDocumentedException { + private Map extractNamespaces() throws NetconfDocumentedException { Map namespaces = new HashMap<>(); - NamedNodeMap attributes = typeElement.getAttributes(); + NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); String attribKey = attribute.getNodeName(); if (attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY)) { String prefix; if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) { - prefix = ""; + prefix = DEFAULT_NAMESPACE_PREFIX; } else { if (!attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":")){ throw new NetconfDocumentedException("Attribute doesn't start with :", @@ -94,6 +96,15 @@ public final class XmlElement { namespaces.put(prefix, attribute.getNodeValue()); } } + + // namespace does not have to be defined on this element but inherited + if(!namespaces.containsKey(DEFAULT_NAMESPACE_PREFIX)) { + Optional namespaceOptionally = getNamespaceOptionally(); + if(namespaceOptionally.isPresent()) { + namespaces.put(DEFAULT_NAMESPACE_PREFIX, namespaceOptionally.get()); + } + } + return namespaces; } @@ -132,7 +143,7 @@ public final class XmlElement { } public String getName() { - if (element.getLocalName()!=null && !element.getLocalName().equals("")){ + if (element.getLocalName()!=null && !element.getLocalName().equals(DEFAULT_NAMESPACE_PREFIX)){ return element.getLocalName(); } return element.getTagName(); @@ -327,7 +338,7 @@ public final class XmlElement { public String getTextContent() throws NetconfDocumentedException { NodeList childNodes = element.getChildNodes(); if (childNodes.getLength() == 0) { - return ""; + return DEFAULT_NAMESPACE_PREFIX; } for(int i = 0; i < childNodes.getLength(); i++) { Node textChild = childNodes.item(i); @@ -356,7 +367,7 @@ public final class XmlElement { public String getNamespaceAttribute() throws MissingNameSpaceException { String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY); - if (attribute == null || attribute.equals("")){ + if (attribute == null || attribute.equals(DEFAULT_NAMESPACE_PREFIX)){ throw new MissingNameSpaceException(String.format("Element %s must specify namespace", toString()), NetconfDocumentedException.ErrorType.application, @@ -415,14 +426,14 @@ public final class XmlElement { * is found value will be null. */ public Map.Entry findNamespaceOfTextContent() throws NetconfDocumentedException { - Map namespaces = extractNamespaces(element); + Map namespaces = extractNamespaces(); String textContent = getTextContent(); int indexOfColon = textContent.indexOf(':'); String prefix; if (indexOfColon > -1) { prefix = textContent.substring(0, indexOfColon); } else { - prefix = ""; + prefix = DEFAULT_NAMESPACE_PREFIX; } if (!namespaces.containsKey(prefix)) { throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element) + ". Prefix from content is " diff --git a/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/NetconfUtilTest.java b/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/NetconfUtilTest.java index b8605d8230..47d0d4c7cc 100644 --- a/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/NetconfUtilTest.java +++ b/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/NetconfUtilTest.java @@ -7,14 +7,13 @@ */ package org.opendaylight.controller.netconf.util; +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; import org.junit.Test; import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.w3c.dom.Document; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.matchers.JUnitMatchers.containsString; - public class NetconfUtilTest { @Test diff --git a/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageTest.java b/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageTest.java index c39ac8eb10..5a9d07f6b1 100644 --- a/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageTest.java +++ b/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageTest.java @@ -9,32 +9,32 @@ package org.opendaylight.controller.netconf.util.messages; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import com.google.common.base.Optional; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.mockito.internal.util.collections.Sets; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.opendaylight.controller.netconf.api.NetconfDocumentedException; public class NetconfHelloMessageTest { Set caps; @Before - public void setUp() throws Exception { + public void setUp() { caps = Sets.newSet("cap1"); } @Test - public void testConstructor() throws Exception { + public void testConstructor() throws NetconfDocumentedException { NetconfHelloMessageAdditionalHeader additionalHeader = new NetconfHelloMessageAdditionalHeader("name","host","1","transp","id"); NetconfHelloMessage message = NetconfHelloMessage.createClientHello(caps, Optional.of(additionalHeader)); - assertTrue(message.isHelloMessage(message)); + assertTrue(NetconfHelloMessage.isHelloMessage(message)); assertEquals(Optional.of(additionalHeader), message.getAdditionalHeader()); NetconfHelloMessage serverMessage = NetconfHelloMessage.createServerHello(caps, 100L); - assertTrue(serverMessage.isHelloMessage(serverMessage)); + assertTrue(NetconfHelloMessage.isHelloMessage(serverMessage)); } } diff --git a/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageHeaderTest.java b/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageHeaderTest.java index cca89aed59..d5ff3380d2 100644 --- a/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageHeaderTest.java +++ b/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageHeaderTest.java @@ -8,13 +8,12 @@ package org.opendaylight.controller.netconf.util.messages; -import com.google.common.base.Charsets; -import java.util.Arrays; -import org.junit.Test; - import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import com.google.common.base.Charsets; +import org.junit.Test; +@Deprecated public class NetconfMessageHeaderTest { @Test public void testGet() throws Exception { diff --git a/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtilTest.java b/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtilTest.java index 741d0d2452..ebee41145a 100644 --- a/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtilTest.java +++ b/opendaylight/netconf/netconf-util/src/test/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtilTest.java @@ -8,20 +8,18 @@ package org.opendaylight.controller.netconf.util.osgi; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; import com.google.common.base.Optional; import io.netty.channel.local.LocalAddress; import java.net.InetSocketAddress; import org.junit.Before; import org.junit.Test; -import org.opendaylight.controller.netconf.util.NetconfUtil; import org.osgi.framework.BundleContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - public class NetconfConfigUtilTest { private BundleContext bundleContext; diff --git a/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/startExi.xml b/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/startExi.xml index e7a483e405..5e94ac6110 100644 --- a/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/startExi.xml +++ b/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/startExi.xml @@ -1,9 +1,9 @@ - - -pre-compression - - - - - - \ No newline at end of file + + +pre-compression + + + + + + diff --git a/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/stopExi.xml b/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/stopExi.xml index 6c0524a4fc..170c753993 100644 --- a/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/stopExi.xml +++ b/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/stopExi.xml @@ -1,3 +1,3 @@ - - - \ No newline at end of file + + + diff --git a/opendaylight/netconf/pom.xml b/opendaylight/netconf/pom.xml index 361f4cfa08..0a3a77cc60 100644 --- a/opendaylight/netconf/pom.xml +++ b/opendaylight/netconf/pom.xml @@ -38,6 +38,8 @@ netconf-auth netconf-usermanager netconf-testtool + + netconf-artifacts @@ -110,7 +112,6 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.12 false false diff --git a/opendaylight/northbound/networkconfiguration/neutron/enunciate.xml b/opendaylight/networkconfiguration/neutron/northbound/enunciate.xml similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/enunciate.xml rename to opendaylight/networkconfiguration/neutron/northbound/enunciate.xml diff --git a/opendaylight/northbound/networkconfiguration/neutron/pom.xml b/opendaylight/networkconfiguration/neutron/northbound/pom.xml similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/pom.xml rename to opendaylight/networkconfiguration/neutron/northbound/pom.xml diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java similarity index 99% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java index bfe2c922bd..cc45d6de5d 100644 --- a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java +++ b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java @@ -79,7 +79,7 @@ public class NeutronFirewallPolicyNorthbound { @QueryParam("name") String queryFirewallPolicyName, @QueryParam("description") String querySecurityPolicyDescription, @QueryParam("shared") String querySecurityPolicyIsShared, - @QueryParam("firewall_rules") List querySecurityPolicyFirewallRules, + @QueryParam("firewall_rules") List querySecurityPolicyFirewallRules, @QueryParam("audited") Boolean querySecurityPolicyIsAudited, // pagination @QueryParam("limit") String limit, diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFloatingIPRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFloatingIPRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFloatingIPRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFloatingIPRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFloatingIPsNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFloatingIPsNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFloatingIPsNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFloatingIPsNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerHealthMonitorNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerHealthMonitorNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerHealthMonitorNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerHealthMonitorNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerHealthMonitorRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerHealthMonitorRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerHealthMonitorRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerHealthMonitorRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerListenerNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerListenerNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerListenerNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerListenerNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerListenerRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerListenerRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerListenerRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerListenerRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolMemberRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolMemberRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolMemberRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolMemberRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolMembersNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolMembersNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolMembersNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolMembersNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerPoolRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronLoadBalancerRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworkRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworkRequest.java similarity index 93% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworkRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworkRequest.java index a4c113c2c1..2001fb758a 100644 --- a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworkRequest.java +++ b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworkRequest.java @@ -9,17 +9,15 @@ package org.opendaylight.controller.networkconfig.neutron.northbound; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; - import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) -public class NeutronNetworkRequest implements INeutronRequest { +public class NeutronNetworkRequest implements INeutronRequest { // See OpenStack Network API v2.0 Reference for description of // annotated attributes @@ -50,14 +48,17 @@ public class NeutronNetworkRequest implements INeutronRequest { singletonNetwork = net; } + @Override public NeutronNetwork getSingleton() { return singletonNetwork; } + @Override public boolean isSingleton() { return (singletonNetwork != null); } + @Override public List getBulk() { return bulkRequest; } diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworksNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworksNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworksNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworksNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPageLink.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPageLink.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPageLink.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPageLink.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortRequest.java similarity index 93% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortRequest.java index 12b58aa2ab..3bfac8a4fd 100644 --- a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortRequest.java +++ b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortRequest.java @@ -9,17 +9,15 @@ package org.opendaylight.controller.networkconfig.neutron.northbound; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; - import org.opendaylight.controller.networkconfig.neutron.NeutronPort; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) -public class NeutronPortRequest implements INeutronRequest { +public class NeutronPortRequest implements INeutronRequest { // See OpenStack Network API v2.0 Reference for description of // annotated attributes @@ -50,14 +48,17 @@ public class NeutronPortRequest implements INeutronRequest { singletonPort = port; } + @Override public NeutronPort getSingleton() { return singletonPort; } + @Override public boolean isSingleton() { return (singletonPort != null); } + @Override public List getBulk() { return bulkRequest; } diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortsNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortsNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortsNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortsNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronRouterRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronRouterRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronRouterRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronRouterRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronRoutersNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronRoutersNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronRoutersNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronRoutersNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityGroupRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityGroupRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityGroupRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityGroupRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityGroupsNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityGroupsNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityGroupsNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityGroupsNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityRuleRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityRuleRequest.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityRuleRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityRuleRequest.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityRulesNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityRulesNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityRulesNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSecurityRulesNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetRequest.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetRequest.java similarity index 93% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetRequest.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetRequest.java index 57a724c1cc..4c230c525b 100644 --- a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetRequest.java +++ b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetRequest.java @@ -9,18 +9,15 @@ package org.opendaylight.controller.networkconfig.neutron.northbound; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; - import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) - -public class NeutronSubnetRequest implements INeutronRequest { +public class NeutronSubnetRequest implements INeutronRequest { // See OpenStack Network API v2.0 Reference for description of // annotated attributes @@ -54,14 +51,17 @@ public class NeutronSubnetRequest implements INeutronRequest { links = null; } + @Override public NeutronSubnet getSingleton() { return singletonSubnet; } + @Override public List getBulk() { return bulkRequest; } + @Override public boolean isSingleton() { return (singletonSubnet != null); } diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetsNorthbound.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetsNorthbound.java similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetsNorthbound.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetsNorthbound.java diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java similarity index 63% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java rename to opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java index 8f05e76e18..7f6c296d98 100644 --- a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java +++ b/opendaylight/networkconfiguration/neutron/northbound/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java @@ -10,6 +10,11 @@ package org.opendaylight.controller.networkconfig.neutron.northbound; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import javax.ws.rs.core.UriInfo; import org.opendaylight.controller.networkconfig.neutron.INeutronObject; import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork; import org.opendaylight.controller.networkconfig.neutron.NeutronPort; @@ -17,13 +22,13 @@ import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet; import org.opendaylight.controller.northbound.commons.exception.BadRequestException; import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import javax.ws.rs.core.UriInfo; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - public class PaginatedRequestFactory { + private static final Comparator NEUTRON_OBJECT_COMPARATOR = new Comparator() { + @Override + public int compare(INeutronObject o1, INeutronObject o2) { + return o1.getID().compareTo(o2.getID()); + } + }; public static class PaginationResults { List collection; @@ -35,77 +40,75 @@ public class PaginatedRequestFactory { } } - public static INeutronRequest createRequest(Integer limit, String marker, + private static final class MarkerObject implements INeutronObject { + private final String id; + + MarkerObject(String id) { + this.id = id; + } + + @Override + public String getID() { + return id; + } + + @Override + public void setID(String id) { + throw new UnsupportedOperationException("Marker has constant ID"); + } + } + + /* + * SuppressWarnings is needed because the compiler does not understand that we + * are actually safe here. + * + * FIXME: the only caller performs a cast back, so this is not actually necessary. + */ + @SuppressWarnings("unchecked") + public static INeutronRequest createRequest(Integer limit, String marker, Boolean pageReverse, UriInfo uriInfo, List collection, Class clazz) { - PaginationResults results = _paginate(limit, marker, pageReverse, uriInfo, collection); + PaginationResults results = _paginate(limit, marker, pageReverse, uriInfo, collection); if (clazz.equals(NeutronNetwork.class)){ - return new NeutronNetworkRequest(results.collection, results.links); + return (INeutronRequest) new NeutronNetworkRequest((List) results.collection, results.links); } if (clazz.equals(NeutronSubnet.class)){ - return new NeutronSubnetRequest(results.collection, results.links); + return (INeutronRequest) new NeutronSubnetRequest((List) results.collection, results.links); } if (clazz.equals(NeutronPort.class)){ - return new NeutronPortRequest(results.collection, results.links); + return (INeutronRequest) new NeutronPortRequest((List) results.collection, results.links); } return null; } - private static PaginationResults _paginate(Integer limit, String marker, Boolean pageReverse, UriInfo uriInfo, List collection) { + private static PaginationResults _paginate(Integer limit, String marker, Boolean pageReverse, UriInfo uriInfo, List collection) { List links = new ArrayList<>(); - Integer startPos = null; + final int startPos; String startMarker; String endMarker; Boolean firstPage = false; Boolean lastPage = false; - Comparator neutronObjectComparator = new Comparator() { - @Override - public int compare(INeutronObject o1, INeutronObject o2) { - return o1.getID().compareTo(o2.getID()); - } - }; - - Collections.sort(collection, neutronObjectComparator); - - if (marker == null) { - startPos = 0; - } - - else { - - class MarkerObject implements INeutronObject { - private String id; - - public String getID() { - return id; - } + Collections.sort(collection, NEUTRON_OBJECT_COMPARATOR); - public void setID(String id) { - this.id = id; - } + if (marker != null) { + int offset = Collections.binarySearch(collection, new MarkerObject(marker), NEUTRON_OBJECT_COMPARATOR); + if (offset < 0) { + throw new ResourceNotFoundException("UUID for marker: " + marker + " could not be found"); } - INeutronObject markerObject = new MarkerObject(); - - markerObject.setID(marker); - - startPos = Collections.binarySearch(collection, markerObject, neutronObjectComparator); - - if (!pageReverse){ - startPos = startPos + 1; + if (!pageReverse) { + startPos = offset + 1; } else { - startPos = startPos - limit; + startPos = offset - limit; } - } - - if (startPos == null) { - throw new ResourceNotFoundException("UUID for marker:" + marker + " could not be found"); + else { + startPos = 0; } if (startPos == 0){ @@ -149,6 +152,6 @@ public class PaginatedRequestFactory { links.add(previous); } - return new PaginationResults(collection, links); + return new PaginationResults(collection, links); } } diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/resources/WEB-INF/web.xml b/opendaylight/networkconfiguration/neutron/northbound/src/main/resources/WEB-INF/web.xml similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/resources/WEB-INF/web.xml rename to opendaylight/networkconfiguration/neutron/northbound/src/main/resources/WEB-INF/web.xml diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/resources/org/opendaylight/controller/networkconfig/neutron/northbound/jaxb.properties b/opendaylight/networkconfiguration/neutron/northbound/src/main/resources/org/opendaylight/controller/networkconfig/neutron/northbound/jaxb.properties similarity index 100% rename from opendaylight/northbound/networkconfiguration/neutron/src/main/resources/org/opendaylight/controller/networkconfig/neutron/northbound/jaxb.properties rename to opendaylight/networkconfiguration/neutron/northbound/src/main/resources/org/opendaylight/controller/networkconfig/neutron/northbound/jaxb.properties diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronSubnet.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronSubnet.java index 1f10b39513..b0d9bf46d4 100644 --- a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronSubnet.java +++ b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronSubnet.java @@ -9,6 +9,8 @@ package org.opendaylight.controller.networkconfig.neutron; import java.io.Serializable; +import java.net.InetAddress; +import java.net.Inet6Address; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -255,16 +257,45 @@ public class NeutronSubnet extends ConfigurationObject implements Serializable, * a new subnet) */ public boolean isValidCIDR() { - try { - SubnetUtils util = new SubnetUtils(cidr); - SubnetInfo info = util.getInfo(); - if (!info.getNetworkAddress().equals(info.getAddress())) { + // fix for Bug 2290 - need to wrap the existing test as + // IPv4 because SubnetUtils doesn't support IPv6 + if (ipVersion == 4) { + try { + SubnetUtils util = new SubnetUtils(cidr); + SubnetInfo info = util.getInfo(); + if (!info.getNetworkAddress().equals(info.getAddress())) { + return false; + } + } catch (Exception e) { return false; } - } catch (Exception e) { - return false; + return true; } - return true; + if (ipVersion == 6) { + // fix for Bug2290 - this is custom code because no classes + // with ODL-friendly licenses have been found + // extract address (in front of /) and length (after /) + String[] parts = cidr.split("/"); + if (parts.length != 2) { + return false; + } + try { + int length = Integer.parseInt(parts[1]); + //TODO?: limit check on length + // convert to byte array + byte[] addrBytes = ((Inet6Address) InetAddress.getByName(parts[0])).getAddress(); + int i; + for (i=length; i<128; i++) { // offset is to ensure proper comparison + if (((((int) addrBytes[i/8]) & 0x000000FF) & (1 << (7-(i%8)))) != 0) { + return(false); + } + } + return(true); + } catch (Exception e) { + return(false); + } + } + return false; } /* test to see if the gateway IP specified overlaps with specified diff --git a/pom.xml b/pom.xml index bb8ad1dbeb..87a69e00c9 100644 --- a/pom.xml +++ b/pom.xml @@ -14,58 +14,6 @@ 3.0 - opendaylight/distribution/opendaylight - opendaylight/forwarding/staticrouting - opendaylight/clustering/services - opendaylight/clustering/services_implementation - opendaylight/clustering/stub - opendaylight/clustering/test - opendaylight/configuration/api - opendaylight/configuration/implementation - opendaylight/routing/dijkstra_implementation - opendaylight/arphandler - opendaylight/forwardingrulesmanager/api - opendaylight/forwardingrulesmanager/implementation - opendaylight/hosttracker/api - opendaylight/hosttracker/implementation - opendaylight/hosttracker/shell - opendaylight/hosttracker_new/api - opendaylight/hosttracker_new/implementation - opendaylight/containermanager/api - opendaylight/containermanager/implementation - opendaylight/containermanager/shell - opendaylight/appauth - opendaylight/switchmanager/api - opendaylight/switchmanager/implementation - opendaylight/statisticsmanager/api - opendaylight/statisticsmanager/implementation - opendaylight/topologymanager/implementation - opendaylight/topologymanager/shell - opendaylight/usermanager/api - opendaylight/usermanager/implementation - opendaylight/connectionmanager/api - opendaylight/connectionmanager/implementation - opendaylight/security - opendaylight/karaf-tomcat-security - - - - - - - third-party/ganymed - - third-party/commons/thirdparty - - - opendaylight/sal/api - opendaylight/sal/implementation - - - opendaylight/sal/connection/api - opendaylight/sal/connection/implementation - opendaylight/sal/networkconfiguration/api - opendaylight/sal/networkconfiguration/implementation opendaylight/md-sal @@ -74,54 +22,17 @@ opendaylight/netconf - - opendaylight/web/root - opendaylight/web/flows - opendaylight/web/devices - opendaylight/web/troubleshoot - opendaylight/web/topology - opendaylight/web/osgi-brandfragment + + opendaylight/adsal opendaylight/networkconfiguration/neutron opendaylight/networkconfiguration/neutron/implementation - opendaylight/northbound/networkconfiguration/neutron - - - opendaylight/northbound/commons - opendaylight/northbound/bundlescanner/api - opendaylight/northbound/bundlescanner/implementation - opendaylight/northbound/topology - opendaylight/northbound/staticrouting - opendaylight/northbound/statistics - opendaylight/northbound/flowprogrammer - opendaylight/northbound/hosttracker - opendaylight/northbound/subnets - opendaylight/northbound/switchmanager - opendaylight/northbound/containermanager - opendaylight/northbound/networkconfiguration/bridgedomain - opendaylight/northbound/httpservice-bridge - opendaylight/northbound/jolokia - opendaylight/northbound/connectionmanager - opendaylight/northbound/usermanager - opendaylight/northbound/controllermanager - - - opendaylight/logging/bridge - - - opendaylight/protocol_plugins/openflow - opendaylight/protocol_plugins/stub - - - opendaylight/samples/simpleforwarding - opendaylight/samples/loadbalancer - opendaylight/samples/northbound/loadbalancer + opendaylight/networkconfiguration/neutron/northbound opendaylight/commons/concepts opendaylight/commons/protocol-framework - opendaylight/commons/httpclient opendaylight/commons/checkstyle opendaylight/commons/opendaylight opendaylight/commons/parent @@ -130,7 +41,6 @@ opendaylight/commons/liblldp - opendaylight/dummy-console opendaylight/karaf-branding opendaylight/distribution/opendaylight-karaf-empty opendaylight/distribution/opendaylight-karaf @@ -146,37 +56,4 @@ HEAD https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - - - integrationtests - - false - - - opendaylight/clustering/integrationtest - opendaylight/configuration/integrationtest - opendaylight/forwardingrulesmanager/integrationtest - opendaylight/hosttracker/integrationtest - opendaylight/switchmanager/integrationtest - opendaylight/topologymanager/integrationtest - - opendaylight/northbound/integrationtest - opendaylight/statisticsmanager/integrationtest - opendaylight/commons/integrationtest - opendaylight/containermanager/it.implementation - opendaylight/distribution/sanitytest/ - - - - docs - - false - - - opendaylight/northbound/java-client - opendaylight/northbound/swagger-ui - - - diff --git a/third-party/commons/thirdparty/pom.xml b/third-party/commons/thirdparty/pom.xml deleted file mode 100644 index ad3c27523e..0000000000 --- a/third-party/commons/thirdparty/pom.xml +++ /dev/null @@ -1,230 +0,0 @@ - - - 4.0.0 - - 3.0 - - org.opendaylight.controller - commons.thirdparty - 1.2.0-SNAPSHOT - pom - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - HEAD - - - - https://sonar.opendaylight.org/ - http://nexus.opendaylight.org/content - opendaylight.release - opendaylight.snapshot - dav:http://nexus.opendaylight.org/content/sites/site - 3.2 - 2.6 - UTF-8 - 2.3.2 - 2.13 - 2.3.2 - 1.3.1 - 2.3.7 - - - - - central2 - central2 - http://repo2.maven.org/maven2 - - - - - - fastreassembly - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.4 - - - copyfastreassembly - install - - copy - - - - - ${project.groupId} - ${project.artifactId} - ${project.version} - ${project.groupId}.${project.artifactId}-${project.version}.jar - - - ${fastreassembly.directory} - - - - - - - - - - - - - com.googlecode.maven-java-formatter-plugin - maven-java-formatter-plugin - 0.3.1 - - - **/* - - - - - - - - org.apache.maven.plugins - maven-release-plugin - ${releaseplugin.version} - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - org.apache.maven.plugins - maven-site-plugin - ${siteplugin} - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - ${projectinfo} - - false - false - - - index - project-team - license - mailing-list - plugin-management - cim - issue-tracking - scm - summary - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.10 - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8.1 - - org.jboss.apiviz.APIviz - - org.jboss.apiviz - apiviz - 1.3.2.GA - - ${project.artifactId}-${build.suffix} - true - UTF-8 - UTF-8 - UTF-8 - true - true - true - true - net.sf.jnetlib.*:cern.*:corejava - - - - org.apache.maven.plugins - maven-jxr-plugin - 2.3 - - true - true - - - - - - - - - - - - central2 - central2 - http://repo2.maven.org/maven2 - - false - - - never - true - - - - central - central - http://repo1.maven.org/maven2 - - false - - - never - true - - - - - thirdparty - thirdparty - ${nexusproxy}/repositories/thirdparty - - false - - - never - true - - - - - - - opendaylight-release - ${nexusproxy}/repositories/${nexus.repository.release}/ - - - - opendaylight-snapshot - ${nexusproxy}/repositories/${nexus.repository.snapshot}/ - - - - website - ${sitedeploy} - - - diff --git a/third-party/ganymed/pom.xml b/third-party/ganymed/pom.xml deleted file mode 100644 index 676e2a24f1..0000000000 --- a/third-party/ganymed/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - 4.0.0 - - - org.opendaylight.controller - commons.thirdparty - 1.2.0-SNAPSHOT - ../commons/thirdparty - - - org.opendaylight.controller.thirdparty - ganymed - 1.2.0-SNAPSHOT - bundle - - - - org.osgi - org.osgi.core - 5.0.0 - - - ch.ethz.ganymed - ganymed-ssh2 - 261 - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ch.ethz.ssh2.* - ganymed-ssh2;scope=compile - true - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${enforcer.version} - - - enforce-no-snapshots - - enforce - - - - - - ch.ethz.ganymed:ganymed-ssh2:* - - - ch.ethz.ganymed:ganymed-ssh2:[261] - - - - - - - - - - - - diff --git a/third-party/ganymed/src/main/java/ch/ethz/ssh2/Connection.java b/third-party/ganymed/src/main/java/ch/ethz/ssh2/Connection.java deleted file mode 100644 index aa13c40d9d..0000000000 --- a/third-party/ganymed/src/main/java/ch/ethz/ssh2/Connection.java +++ /dev/null @@ -1,1424 +0,0 @@ -/* - * Copyright (c) 2006-2011 Christian Plattner. All rights reserved. - * Please refer to the LICENSE.txt for licensing details. - */ - -package ch.ethz.ssh2; - -import java.io.CharArrayWriter; -import java.io.File; -import java.net.Socket; -import java.io.FileReader; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketTimeoutException; -import java.security.SecureRandom; -import java.util.List; -import java.util.Vector; - -import ch.ethz.ssh2.auth.AuthenticationManager; -import ch.ethz.ssh2.channel.ChannelManager; -import ch.ethz.ssh2.crypto.CryptoWishList; -import ch.ethz.ssh2.crypto.cipher.BlockCipherFactory; -import ch.ethz.ssh2.crypto.digest.MAC; -import ch.ethz.ssh2.packets.PacketIgnore; -import ch.ethz.ssh2.transport.KexManager; -import ch.ethz.ssh2.transport.TransportManager; -import ch.ethz.ssh2.util.TimeoutService; -import ch.ethz.ssh2.util.TimeoutService.TimeoutToken; - -/** - * A Connection is used to establish an encrypted TCP/IP - * connection to a SSH-2 server. - *

      - * Typically, one - *

        - *
      1. creates a {@link #Connection(String) Connection} object.
      2. - *
      3. calls the {@link #connect() connect()} method.
      4. - *
      5. calls some of the authentication methods (e.g., {@link #authenticateWithPublicKey(String, File, String) authenticateWithPublicKey()}).
      6. - *
      7. calls one or several times the {@link #openSession() openSession()} method.
      8. - *
      9. finally, one must close the connection and release resources with the {@link #close() close()} method.
      10. - *
      - * - * @author Christian Plattner - * @version $Id: Connection.java 69 2013-08-09 06:39:56Z dkocher@sudo.ch $ - */ - -public class Connection -{ - /** - * The identifier presented to the SSH-2 server. This is the same - * as the "softwareversion" defined in RFC 4253. - *

      - * NOTE: As per the RFC, the "softwareversion" string MUST consist of printable - * US-ASCII characters, with the exception of whitespace characters and the minus sign (-). - */ - private String softwareversion = String.format("Ganymed_%s", Version.getSpecification()); - - /* Will be used to generate all random data needed for the current connection. - * Note: SecureRandom.nextBytes() is thread safe. - */ - - private SecureRandom generator; - - private Socket precreatedSocket; - - public Connection(Socket socket) { - this.precreatedSocket = socket; - this.hostname = socket.getInetAddress().getHostName(); - this.port = socket.getPort(); - } - - /** - * Unless you know what you are doing, you will never need this. - * - * @return The list of supported cipher algorithms by this implementation. - */ - public static synchronized String[] getAvailableCiphers() - { - return BlockCipherFactory.getDefaultCipherList(); - } - - /** - * Unless you know what you are doing, you will never need this. - * - * @return The list of supported MAC algorthims by this implementation. - */ - public static synchronized String[] getAvailableMACs() - { - return MAC.getMacList(); - } - - /** - * Unless you know what you are doing, you will never need this. - * - * @return The list of supported server host key algorthims by this implementation. - */ - public static synchronized String[] getAvailableServerHostKeyAlgorithms() - { - return KexManager.getDefaultServerHostkeyAlgorithmList(); - } - - private AuthenticationManager am; - - private boolean authenticated = false; - private ChannelManager cm; - - private CryptoWishList cryptoWishList = new CryptoWishList(); - - private DHGexParameters dhgexpara = new DHGexParameters(); - - private final String hostname; - - private final int port; - - private TransportManager tm; - - private boolean tcpNoDelay = false; - - private ProxyData proxyData = null; - - private List connectionMonitors = new Vector(); - - /** - * Prepares a fresh Connection object which can then be used - * to establish a connection to the specified SSH-2 server. - *

      - * Same as {@link #Connection(String, int) Connection(hostname, 22)}. - * - * @param hostname the hostname of the SSH-2 server. - */ - public Connection(String hostname) - { - this(hostname, 22); - } - - /** - * Prepares a fresh Connection object which can then be used - * to establish a connection to the specified SSH-2 server. - * - * @param hostname - * the host where we later want to connect to. - * @param port - * port on the server, normally 22. - */ - public Connection(String hostname, int port) - { - this.hostname = hostname; - this.port = port; - } - - /** - * Prepares a fresh Connection object which can then be used - * to establish a connection to the specified SSH-2 server. - * - * @param hostname - * the host where we later want to connect to. - * @param port - * port on the server, normally 22. - * @param softwareversion - * Allows you to set a custom "softwareversion" string as defined in RFC 4253. - * NOTE: As per the RFC, the "softwareversion" string MUST consist of printable - * US-ASCII characters, with the exception of whitespace characters and the minus sign (-). - */ - public Connection(String hostname, int port, String softwareversion) - { - this.hostname = hostname; - this.port = port; - this.softwareversion = softwareversion; - } - - /** - * After a successful connect, one has to authenticate oneself. This method - * is based on DSA (it uses DSA to sign a challenge sent by the server). - *

      - * If the authentication phase is complete, true will be - * returned. If the server does not accept the request (or if further - * authentication steps are needed), false is returned and - * one can retry either by using this or any other authentication method - * (use the getRemainingAuthMethods method to get a list of - * the remaining possible methods). - * - * @param user - * A String holding the username. - * @param pem - * A String containing the DSA private key of the - * user in OpenSSH key format (PEM, you can't miss the - * "-----BEGIN DSA PRIVATE KEY-----" tag). The string may contain - * linefeeds. - * @param password - * If the PEM string is 3DES encrypted ("DES-EDE3-CBC"), then you - * must specify the password. Otherwise, this argument will be - * ignored and can be set to null. - * - * @return whether the connection is now authenticated. - * @throws IOException - * - * @deprecated You should use one of the {@link #authenticateWithPublicKey(String, File, String) authenticateWithPublicKey()} - * methods, this method is just a wrapper for it and will - * disappear in future builds. - * - */ - public synchronized boolean authenticateWithDSA(String user, String pem, String password) throws IOException - { - if (tm == null) - throw new IllegalStateException("Connection is not established!"); - - if (authenticated) - throw new IllegalStateException("Connection is already authenticated!"); - - if (am == null) - am = new AuthenticationManager(tm); - - if (cm == null) - cm = new ChannelManager(tm); - - if (user == null) - throw new IllegalArgumentException("user argument is null"); - - if (pem == null) - throw new IllegalArgumentException("pem argument is null"); - - authenticated = am.authenticatePublicKey(user, pem.toCharArray(), password, getOrCreateSecureRND()); - - return authenticated; - } - - /** - * A wrapper that calls {@link #authenticateWithKeyboardInteractive(String, String[], InteractiveCallback) - * authenticateWithKeyboardInteractivewith} a null submethod list. - * - * @param user - * A String holding the username. - * @param cb - * An InteractiveCallback which will be used to - * determine the responses to the questions asked by the server. - * @return whether the connection is now authenticated. - * @throws IOException - */ - public synchronized boolean authenticateWithKeyboardInteractive(String user, InteractiveCallback cb) - throws IOException - { - return authenticateWithKeyboardInteractive(user, null, cb); - } - - /** - * After a successful connect, one has to authenticate oneself. This method - * is based on "keyboard-interactive", specified in - * draft-ietf-secsh-auth-kbdinteract-XX. Basically, you have to define a - * callback object which will be feeded with challenges generated by the - * server. Answers are then sent back to the server. It is possible that the - * callback will be called several times during the invocation of this - * method (e.g., if the server replies to the callback's answer(s) with - * another challenge...) - *

      - * If the authentication phase is complete, true will be - * returned. If the server does not accept the request (or if further - * authentication steps are needed), false is returned and - * one can retry either by using this or any other authentication method - * (use the getRemainingAuthMethods method to get a list of - * the remaining possible methods). - *

      - * Note: some SSH servers advertise "keyboard-interactive", however, any - * interactive request will be denied (without having sent any challenge to - * the client). - * - * @param user - * A String holding the username. - * @param submethods - * An array of submethod names, see - * draft-ietf-secsh-auth-kbdinteract-XX. May be null - * to indicate an empty list. - * @param cb - * An InteractiveCallback which will be used to - * determine the responses to the questions asked by the server. - * - * @return whether the connection is now authenticated. - * @throws IOException - */ - public synchronized boolean authenticateWithKeyboardInteractive(String user, String[] submethods, - InteractiveCallback cb) throws IOException - { - if (cb == null) - throw new IllegalArgumentException("Callback may not ne NULL!"); - - if (tm == null) - throw new IllegalStateException("Connection is not established!"); - - if (authenticated) - throw new IllegalStateException("Connection is already authenticated!"); - - if (am == null) - am = new AuthenticationManager(tm); - - if (cm == null) - cm = new ChannelManager(tm); - - if (user == null) - throw new IllegalArgumentException("user argument is null"); - - authenticated = am.authenticateInteractive(user, submethods, cb); - - return authenticated; - } - - /** - * After a successful connect, one has to authenticate oneself. This method - * sends username and password to the server. - *

      - * If the authentication phase is complete, true will be - * returned. If the server does not accept the request (or if further - * authentication steps are needed), false is returned and - * one can retry either by using this or any other authentication method - * (use the getRemainingAuthMethods method to get a list of - * the remaining possible methods). - *

      - * Note: if this method fails, then please double-check that it is actually - * offered by the server (use {@link #getRemainingAuthMethods(String) getRemainingAuthMethods()}. - *

      - * Often, password authentication is disabled, but users are not aware of it. - * Many servers only offer "publickey" and "keyboard-interactive". However, - * even though "keyboard-interactive" *feels* like password authentication - * (e.g., when using the putty or openssh clients) it is *not* the same mechanism. - * - * @param user - * @param password - * @return if the connection is now authenticated. - * @throws IOException - */ - public synchronized boolean authenticateWithPassword(String user, String password) throws IOException - { - if (tm == null) - throw new IllegalStateException("Connection is not established!"); - - if (authenticated) - throw new IllegalStateException("Connection is already authenticated!"); - - if (am == null) - am = new AuthenticationManager(tm); - - if (cm == null) - cm = new ChannelManager(tm); - - if (user == null) - throw new IllegalArgumentException("user argument is null"); - - if (password == null) - throw new IllegalArgumentException("password argument is null"); - - authenticated = am.authenticatePassword(user, password); - - return authenticated; - } - - /** - * After a successful connect, one has to authenticate oneself. - * This method can be used to explicitly use the special "none" - * authentication method (where only a username has to be specified). - *

      - * Note 1: The "none" method may always be tried by clients, however as by - * the specs, the server will not explicitly announce it. In other words, - * the "none" token will never show up in the list returned by - * {@link #getRemainingAuthMethods(String)}. - *

      - * Note 2: no matter which one of the authenticateWithXXX() methods - * you call, the library will always issue exactly one initial "none" - * authentication request to retrieve the initially allowed list of - * authentication methods by the server. Please read RFC 4252 for the - * details. - *

      - * If the authentication phase is complete, true will be - * returned. If further authentication steps are needed, false - * is returned and one can retry by any other authentication method - * (use the getRemainingAuthMethods method to get a list of - * the remaining possible methods). - * - * @param user - * @return if the connection is now authenticated. - * @throws IOException - */ - public synchronized boolean authenticateWithNone(String user) throws IOException - { - if (tm == null) - throw new IllegalStateException("Connection is not established!"); - - if (authenticated) - throw new IllegalStateException("Connection is already authenticated!"); - - if (am == null) - am = new AuthenticationManager(tm); - - if (cm == null) - cm = new ChannelManager(tm); - - if (user == null) - throw new IllegalArgumentException("user argument is null"); - - /* Trigger the sending of the PacketUserauthRequestNone packet */ - /* (if not already done) */ - - authenticated = am.authenticateNone(user); - - return authenticated; - } - - /** - * After a successful connect, one has to authenticate oneself. - * The authentication method "publickey" works by signing a challenge - * sent by the server. The signature is either DSA or RSA based - it - * just depends on the type of private key you specify, either a DSA - * or RSA private key in PEM format. And yes, this is may seem to be a - * little confusing, the method is called "publickey" in the SSH-2 protocol - * specification, however since we need to generate a signature, you - * actually have to supply a private key =). - *

      - * The private key contained in the PEM file may also be encrypted ("Proc-Type: 4,ENCRYPTED"). - * The library supports DES-CBC and DES-EDE3-CBC encryption, as well - * as the more exotic PEM encrpytions AES-128-CBC, AES-192-CBC and AES-256-CBC. - *

      - * If the authentication phase is complete, true will be - * returned. If the server does not accept the request (or if further - * authentication steps are needed), false is returned and - * one can retry either by using this or any other authentication method - * (use the getRemainingAuthMethods method to get a list of - * the remaining possible methods). - *

      - * NOTE PUTTY USERS: Event though your key file may start with "-----BEGIN..." - * it is not in the expected format. You have to convert it to the OpenSSH - * key format by using the "puttygen" tool (can be downloaded from the Putty - * website). Simply load your key and then use the "Conversions/Export OpenSSH key" - * functionality to get a proper PEM file. - * - * @param user - * A String holding the username. - * @param pemPrivateKey - * A char[] containing a DSA or RSA private key of the - * user in OpenSSH key format (PEM, you can't miss the - * "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----" - * tag). The char array may contain linebreaks/linefeeds. - * @param password - * If the PEM structure is encrypted ("Proc-Type: 4,ENCRYPTED") then - * you must specify a password. Otherwise, this argument will be ignored - * and can be set to null. - * - * @return whether the connection is now authenticated. - * @throws IOException - */ - public synchronized boolean authenticateWithPublicKey(String user, char[] pemPrivateKey, String password) - throws IOException - { - if (tm == null) - throw new IllegalStateException("Connection is not established!"); - - if (authenticated) - throw new IllegalStateException("Connection is already authenticated!"); - - if (am == null) - am = new AuthenticationManager(tm); - - if (cm == null) - cm = new ChannelManager(tm); - - if (user == null) - throw new IllegalArgumentException("user argument is null"); - - if (pemPrivateKey == null) - throw new IllegalArgumentException("pemPrivateKey argument is null"); - - authenticated = am.authenticatePublicKey(user, pemPrivateKey, password, getOrCreateSecureRND()); - - return authenticated; - } - - /** - * A convenience wrapper function which reads in a private key (PEM format, either DSA or RSA) - * and then calls authenticateWithPublicKey(String, char[], String). - *

      - * NOTE PUTTY USERS: Event though your key file may start with "-----BEGIN..." - * it is not in the expected format. You have to convert it to the OpenSSH - * key format by using the "puttygen" tool (can be downloaded from the Putty - * website). Simply load your key and then use the "Conversions/Export OpenSSH key" - * functionality to get a proper PEM file. - * - * @param user - * A String holding the username. - * @param pemFile - * A File object pointing to a file containing a DSA or RSA - * private key of the user in OpenSSH key format (PEM, you can't miss the - * "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----" - * tag). - * @param password - * If the PEM file is encrypted then you must specify the password. - * Otherwise, this argument will be ignored and can be set to null. - * - * @return whether the connection is now authenticated. - * @throws IOException - */ - public synchronized boolean authenticateWithPublicKey(String user, File pemFile, String password) - throws IOException - { - if (pemFile == null) - throw new IllegalArgumentException("pemFile argument is null"); - - char[] buff = new char[256]; - - CharArrayWriter cw = new CharArrayWriter(); - - FileReader fr = new FileReader(pemFile); - - while (true) - { - int len = fr.read(buff); - if (len < 0) - break; - cw.write(buff, 0, len); - } - - fr.close(); - - return authenticateWithPublicKey(user, cw.toCharArray(), password); - } - - /** - * Add a {@link ConnectionMonitor} to this connection. Can be invoked at any time, - * but it is best to add connection monitors before invoking - * connect() to avoid glitches (e.g., you add a connection monitor after - * a successful connect(), but the connection has died in the mean time. Then, - * your connection monitor won't be notified.) - *

      - * You can add as many monitors as you like. If a monitor has already been added, then - * this method does nothing. - * - * @see ConnectionMonitor - * - * @param cmon An object implementing the {@link ConnectionMonitor} interface. - */ - public synchronized void addConnectionMonitor(ConnectionMonitor cmon) - { - if (cmon == null) - throw new IllegalArgumentException("cmon argument is null"); - - if (!connectionMonitors.contains(cmon)) - { - connectionMonitors.add(cmon); - - if (tm != null) - tm.setConnectionMonitors(connectionMonitors); - } - } - - /** - * Remove a {@link ConnectionMonitor} from this connection. - * - * @param cmon - * @return whether the monitor could be removed - */ - public synchronized boolean removeConnectionMonitor(ConnectionMonitor cmon) - { - if (cmon == null) - throw new IllegalArgumentException("cmon argument is null"); - - boolean existed = connectionMonitors.remove(cmon); - - if (tm != null) - tm.setConnectionMonitors(connectionMonitors); - - return existed; - } - - /** - * Close the connection to the SSH-2 server. All assigned sessions will be - * closed, too. Can be called at any time. Don't forget to call this once - * you don't need a connection anymore - otherwise the receiver thread may - * run forever. - */ - public synchronized void close() - { - Throwable t = new Throwable("Closed due to user request."); - close(t, false); - } - - public synchronized void close(Throwable t, boolean hard) - { - if (cm != null) - cm.closeAllChannels(); - - if (tm != null) - { - tm.close(t, hard == false); - tm = null; - } - am = null; - cm = null; - authenticated = false; - } - - /** - * Same as {@link #connect(ServerHostKeyVerifier, int, int) connect(null, 0, 0)}. - * - * @return see comments for the {@link #connect(ServerHostKeyVerifier, int, int) connect(ServerHostKeyVerifier, int, int)} method. - * @throws IOException - */ - public synchronized ConnectionInfo connect() throws IOException - { - return connect(null, 0, 0); - } - - /** - * Same as {@link #connect(ServerHostKeyVerifier, int, int) connect(verifier, 0, 0)}. - * - * @return see comments for the {@link #connect(ServerHostKeyVerifier, int, int) connect(ServerHostKeyVerifier, int, int)} method. - * @throws IOException - */ - public synchronized ConnectionInfo connect(ServerHostKeyVerifier verifier) throws IOException - { - return connect(verifier, 0, 0); - } - - /** - * Connect to the SSH-2 server and, as soon as the server has presented its - * host key, use the {@link ServerHostKeyVerifier#verifyServerHostKey(String, - * int, String, byte[]) ServerHostKeyVerifier.verifyServerHostKey()} - * method of the verifier to ask for permission to proceed. - * If verifier is null, then any host key will be - * accepted - this is NOT recommended, since it makes man-in-the-middle attackes - * VERY easy (somebody could put a proxy SSH server between you and the real server). - *

      - * Note: The verifier will be called before doing any crypto calculations - * (i.e., diffie-hellman). Therefore, if you don't like the presented host key then - * no CPU cycles are wasted (and the evil server has less information about us). - *

      - * However, it is still possible that the server presented a fake host key: the server - * cheated (typically a sign for a man-in-the-middle attack) and is not able to generate - * a signature that matches its host key. Don't worry, the library will detect such - * a scenario later when checking the signature (the signature cannot be checked before - * having completed the diffie-hellman exchange). - *

      - * Note 2: The {@link ServerHostKeyVerifier#verifyServerHostKey(String, - * int, String, byte[]) ServerHostKeyVerifier.verifyServerHostKey()} method - * will *NOT* be called from the current thread, the call is being made from a - * background thread (there is a background dispatcher thread for every - * established connection). - *

      - * Note 3: This method will block as long as the key exchange of the underlying connection - * has not been completed (and you have not specified any timeouts). - *

      - * Note 4: If you want to re-use a connection object that was successfully connected, - * then you must call the {@link #close()} method before invoking connect() again. - * - * @param verifier - * An object that implements the - * {@link ServerHostKeyVerifier} interface. Pass null - * to accept any server host key - NOT recommended. - * - * @param connectTimeout - * Connect the underlying TCP socket to the server with the given timeout - * value (non-negative, in milliseconds). Zero means no timeout. If a proxy is being - * used (see {@link #setProxyData(ProxyData)}), then this timeout is used for the - * connection establishment to the proxy. - * - * @param kexTimeout - * Timeout for complete connection establishment (non-negative, - * in milliseconds). Zero means no timeout. The timeout counts from the - * moment you invoke the connect() method and is cancelled as soon as the - * first key-exchange round has finished. It is possible that - * the timeout event will be fired during the invocation of the - * verifier callback, but it will only have an effect after - * the verifier returns. - * - * @return A {@link ConnectionInfo} object containing the details of - * the established connection. - * - * @throws IOException - * If any problem occurs, e.g., the server's host key is not - * accepted by the verifier or there is problem during - * the initial crypto setup (e.g., the signature sent by the server is wrong). - *

      - * In case of a timeout (either connectTimeout or kexTimeout) - * a SocketTimeoutException is thrown. - *

      - * An exception may also be thrown if the connection was already successfully - * connected (no matter if the connection broke in the mean time) and you invoke - * connect() again without having called {@link #close()} first. - *

      - * If a HTTP proxy is being used and the proxy refuses the connection, - * then a {@link HTTPProxyException} may be thrown, which - * contains the details returned by the proxy. If the proxy is buggy and does - * not return a proper HTTP response, then a normal IOException is thrown instead. - */ - public synchronized ConnectionInfo connect(ServerHostKeyVerifier verifier, int connectTimeout, int kexTimeout) - throws IOException - { - final class TimeoutState - { - boolean isCancelled = false; - boolean timeoutSocketClosed = false; - } - - if (tm != null) - throw new IOException("Connection to " + hostname + " is already in connected state!"); - - if (connectTimeout < 0) - throw new IllegalArgumentException("connectTimeout must be non-negative!"); - - if (kexTimeout < 0) - throw new IllegalArgumentException("kexTimeout must be non-negative!"); - - final TimeoutState state = new TimeoutState(); - - tm = new TransportManager(); - tm.setSoTimeout(connectTimeout); - tm.setConnectionMonitors(connectionMonitors); - - /* Make sure that the runnable below will observe the new value of "tm" - * and "state" (the runnable will be executed in a different thread, which - * may be already running, that is why we need a memory barrier here). - * See also the comment in Channel.java if you - * are interested in the details. - * - * OKOK, this is paranoid since adding the runnable to the todo list - * of the TimeoutService will ensure that all writes have been flushed - * before the Runnable reads anything - * (there is a synchronized block in TimeoutService.addTimeoutHandler). - */ - - synchronized (tm) - { - /* We could actually synchronize on anything. */ - } - - try - { - TimeoutToken token = null; - - if (kexTimeout > 0) - { - final Runnable timeoutHandler = new Runnable() - { - public void run() - { - synchronized (state) - { - if (state.isCancelled) - return; - state.timeoutSocketClosed = true; - tm.close(new SocketTimeoutException("The connect timeout expired"), false); - } - } - }; - - long timeoutHorizont = System.currentTimeMillis() + kexTimeout; - - token = TimeoutService.addTimeoutHandler(timeoutHorizont, timeoutHandler); - } - - try - { - - if (precreatedSocket != null) { - tm.clientInit(precreatedSocket, softwareversion, cryptoWishList, verifier, dhgexpara, - getOrCreateSecureRND()); - } else { - tm.clientInit(hostname, port, softwareversion, cryptoWishList, verifier, dhgexpara, connectTimeout, - getOrCreateSecureRND(), proxyData); - } - } - catch (SocketTimeoutException se) - { - throw (SocketTimeoutException) new SocketTimeoutException( - "The connect() operation on the socket timed out.").initCause(se); - } - - tm.setTcpNoDelay(tcpNoDelay); - - /* Wait until first KEX has finished */ - - ConnectionInfo ci = tm.getConnectionInfo(1); - - /* Now try to cancel the timeout, if needed */ - - if (token != null) - { - TimeoutService.cancelTimeoutHandler(token); - - /* Were we too late? */ - - synchronized (state) - { - if (state.timeoutSocketClosed) - throw new IOException("This exception will be replaced by the one below =)"); - /* Just in case the "cancelTimeoutHandler" invocation came just a little bit - * too late but the handler did not enter the semaphore yet - we can - * still stop it. - */ - state.isCancelled = true; - } - } - - return ci; - } - catch (SocketTimeoutException ste) - { - throw ste; - } - catch (IOException e1) - { - /* This will also invoke any registered connection monitors */ - close(new Throwable("There was a problem during connect."), false); - - synchronized (state) - { - /* Show a clean exception, not something like "the socket is closed!?!" */ - if (state.timeoutSocketClosed) - throw new SocketTimeoutException("The kexTimeout (" + kexTimeout + " ms) expired."); - } - - /* Do not wrap a HTTPProxyException */ - if (e1 instanceof HTTPProxyException) - throw e1; - - throw (IOException) new IOException("There was a problem while connecting to " + hostname + ":" + port) - .initCause(e1); - } - } - - /** - * Creates a new {@link LocalPortForwarder}. - * A LocalPortForwarder forwards TCP/IP connections that arrive at a local - * port via the secure tunnel to another host (which may or may not be - * identical to the remote SSH-2 server). - *

      - * This method must only be called after one has passed successfully the authentication step. - * There is no limit on the number of concurrent forwardings. - * - * @param local_port the local port the LocalPortForwarder shall bind to. - * @param host_to_connect target address (IP or hostname) - * @param port_to_connect target port - * @return A {@link LocalPortForwarder} object. - * @throws IOException - */ - public synchronized LocalPortForwarder createLocalPortForwarder(int local_port, String host_to_connect, - int port_to_connect) throws IOException - { - if (tm == null) - throw new IllegalStateException("Cannot forward ports, you need to establish a connection first."); - - if (!authenticated) - throw new IllegalStateException("Cannot forward ports, connection is not authenticated."); - - return new LocalPortForwarder(cm, local_port, host_to_connect, port_to_connect); - } - - /** - * Creates a new {@link LocalPortForwarder}. - * A LocalPortForwarder forwards TCP/IP connections that arrive at a local - * port via the secure tunnel to another host (which may or may not be - * identical to the remote SSH-2 server). - *

      - * This method must only be called after one has passed successfully the authentication step. - * There is no limit on the number of concurrent forwardings. - * - * @param addr specifies the InetSocketAddress where the local socket shall be bound to. - * @param host_to_connect target address (IP or hostname) - * @param port_to_connect target port - * @return A {@link LocalPortForwarder} object. - * @throws IOException - */ - public synchronized LocalPortForwarder createLocalPortForwarder(InetSocketAddress addr, String host_to_connect, - int port_to_connect) throws IOException - { - if (tm == null) - throw new IllegalStateException("Cannot forward ports, you need to establish a connection first."); - - if (!authenticated) - throw new IllegalStateException("Cannot forward ports, connection is not authenticated."); - - return new LocalPortForwarder(cm, addr, host_to_connect, port_to_connect); - } - - /** - * Creates a new {@link LocalStreamForwarder}. - * A LocalStreamForwarder manages an Input/Outputstream pair - * that is being forwarded via the secure tunnel into a TCP/IP connection to another host - * (which may or may not be identical to the remote SSH-2 server). - * - * @param host_to_connect - * @param port_to_connect - * @return A {@link LocalStreamForwarder} object. - * @throws IOException - */ - public synchronized LocalStreamForwarder createLocalStreamForwarder(String host_to_connect, int port_to_connect) - throws IOException - { - if (tm == null) - throw new IllegalStateException("Cannot forward, you need to establish a connection first."); - - if (!authenticated) - throw new IllegalStateException("Cannot forward, connection is not authenticated."); - - return new LocalStreamForwarder(cm, host_to_connect, port_to_connect); - } - - /** - * Create a very basic {@link SCPClient} that can be used to copy - * files from/to the SSH-2 server. - *

      - * Works only after one has passed successfully the authentication step. - * There is no limit on the number of concurrent SCP clients. - *

      - * Note: This factory method will probably disappear in the future. - * - * @return A {@link SCPClient} object. - * @throws IOException - */ - public synchronized SCPClient createSCPClient() throws IOException - { - if (tm == null) - throw new IllegalStateException("Cannot create SCP client, you need to establish a connection first."); - - if (!authenticated) - throw new IllegalStateException("Cannot create SCP client, connection is not authenticated."); - - return new SCPClient(this); - } - - /** - * Force an asynchronous key re-exchange (the call does not block). The - * latest values set for MAC, Cipher and DH group exchange parameters will - * be used. If a key exchange is currently in progress, then this method has - * the only effect that the so far specified parameters will be used for the - * next (server driven) key exchange. - *

      - * Note: This implementation will never start a key exchange (other than the initial one) - * unless you or the SSH-2 server ask for it. - * - * @throws IOException - * In case of any failure behind the scenes. - */ - public synchronized void forceKeyExchange() throws IOException - { - if (tm == null) - throw new IllegalStateException("You need to establish a connection first."); - - tm.forceKeyExchange(cryptoWishList, dhgexpara, null, null); - } - - /** - * Returns the hostname that was passed to the constructor. - * - * @return the hostname - */ - public synchronized String getHostname() - { - return hostname; - } - - /** - * Returns the port that was passed to the constructor. - * - * @return the TCP port - */ - public synchronized int getPort() - { - return port; - } - - /** - * Returns a {@link ConnectionInfo} object containing the details of - * the connection. Can be called as soon as the connection has been - * established (successfully connected). - * - * @return A {@link ConnectionInfo} object. - * @throws IOException - * In case of any failure behind the scenes. - */ - public synchronized ConnectionInfo getConnectionInfo() throws IOException - { - if (tm == null) - throw new IllegalStateException( - "Cannot get details of connection, you need to establish a connection first."); - return tm.getConnectionInfo(1); - } - - /** - * After a successful connect, one has to authenticate oneself. This method - * can be used to tell which authentication methods are supported by the - * server at a certain stage of the authentication process (for the given - * username). - *

      - * Note 1: the username will only be used if no authentication step was done - * so far (it will be used to ask the server for a list of possible - * authentication methods by sending the initial "none" request). Otherwise, - * this method ignores the user name and returns a cached method list - * (which is based on the information contained in the last negative server response). - *

      - * Note 2: the server may return method names that are not supported by this - * implementation. - *

      - * After a successful authentication, this method must not be called - * anymore. - * - * @param user - * A String holding the username. - * - * @return a (possibly emtpy) array holding authentication method names. - * @throws IOException - */ - public synchronized String[] getRemainingAuthMethods(String user) throws IOException - { - if (user == null) - throw new IllegalArgumentException("user argument may not be NULL!"); - - if (tm == null) - throw new IllegalStateException("Connection is not established!"); - - if (authenticated) - throw new IllegalStateException("Connection is already authenticated!"); - - if (am == null) - am = new AuthenticationManager(tm); - - if (cm == null) - cm = new ChannelManager(tm); - - return am.getRemainingMethods(user); - } - - /** - * Determines if the authentication phase is complete. Can be called at any - * time. - * - * @return true if no further authentication steps are - * needed. - */ - public synchronized boolean isAuthenticationComplete() - { - return authenticated; - } - - /** - * Returns true if there was at least one failed authentication request and - * the last failed authentication request was marked with "partial success" - * by the server. This is only needed in the rare case of SSH-2 server setups - * that cannot be satisfied with a single successful authentication request - * (i.e., multiple authentication steps are needed.) - *

      - * If you are interested in the details, then have a look at RFC4252. - * - * @return if the there was a failed authentication step and the last one - * was marked as a "partial success". - */ - public synchronized boolean isAuthenticationPartialSuccess() - { - if (am == null) - return false; - - return am.getPartialSuccess(); - } - - /** - * Checks if a specified authentication method is available. This method is - * actually just a wrapper for {@link #getRemainingAuthMethods(String) - * getRemainingAuthMethods()}. - * - * @param user - * A String holding the username. - * @param method - * An authentication method name (e.g., "publickey", "password", - * "keyboard-interactive") as specified by the SSH-2 standard. - * @return if the specified authentication method is currently available. - * @throws IOException - */ - public synchronized boolean isAuthMethodAvailable(String user, String method) throws IOException - { - if (method == null) - throw new IllegalArgumentException("method argument may not be NULL!"); - - String methods[] = getRemainingAuthMethods(user); - - for (int i = 0; i < methods.length; i++) - { - if (methods[i].compareTo(method) == 0) - return true; - } - - return false; - } - - private SecureRandom getOrCreateSecureRND() - { - if (generator == null) - generator = new SecureRandom(); - - return generator; - } - - /** - * Open a new {@link Session} on this connection. Works only after one has passed - * successfully the authentication step. There is no limit on the number of - * concurrent sessions. - * - * @return A {@link Session} object. - * @throws IOException - */ - public synchronized Session openSession() throws IOException - { - if (tm == null) - throw new IllegalStateException("Cannot open session, you need to establish a connection first."); - - if (!authenticated) - throw new IllegalStateException("Cannot open session, connection is not authenticated."); - - return new Session(cm, getOrCreateSecureRND()); - } - - /** - * Send an SSH_MSG_IGNORE packet. This method will generate a random data attribute - * (length between 0 (invlusive) and 16 (exclusive) bytes, contents are random bytes). - *

      - * This method must only be called once the connection is established. - * - * @throws IOException - */ - public synchronized void sendIgnorePacket() throws IOException - { - SecureRandom rnd = getOrCreateSecureRND(); - - byte[] data = new byte[rnd.nextInt(16)]; - rnd.nextBytes(data); - - sendIgnorePacket(data); - } - - /** - * Send an SSH_MSG_IGNORE packet with the given data attribute. - *

      - * This method must only be called once the connection is established. - * - * @throws IOException - */ - public synchronized void sendIgnorePacket(byte[] data) throws IOException - { - if (data == null) - throw new IllegalArgumentException("data argument must not be null."); - - if (tm == null) - throw new IllegalStateException( - "Cannot send SSH_MSG_IGNORE packet, you need to establish a connection first."); - - PacketIgnore pi = new PacketIgnore(); - pi.setData(data); - - tm.sendMessage(pi.getPayload()); - } - - /** - * Removes duplicates from a String array, keeps only first occurence - * of each element. Does not destroy order of elements; can handle nulls. - * Uses a very efficient O(N^2) algorithm =) - * - * @param list a String array. - * @return a cleaned String array. - */ - private String[] removeDuplicates(String[] list) - { - if ((list == null) || (list.length < 2)) - return list; - - String[] list2 = new String[list.length]; - - int count = 0; - - for (int i = 0; i < list.length; i++) - { - boolean duplicate = false; - - String element = list[i]; - - for (int j = 0; j < count; j++) - { - if (((element == null) && (list2[j] == null)) || ((element != null) && (element.equals(list2[j])))) - { - duplicate = true; - break; - } - } - - if (duplicate) - continue; - - list2[count++] = list[i]; - } - - if (count == list2.length) - return list2; - - String[] tmp = new String[count]; - System.arraycopy(list2, 0, tmp, 0, count); - - return tmp; - } - - /** - * Unless you know what you are doing, you will never need this. - * - * @param ciphers - */ - public synchronized void setClient2ServerCiphers(String[] ciphers) - { - if ((ciphers == null) || (ciphers.length == 0)) - throw new IllegalArgumentException(); - ciphers = removeDuplicates(ciphers); - BlockCipherFactory.checkCipherList(ciphers); - cryptoWishList.c2s_enc_algos = ciphers; - } - - /** - * Unless you know what you are doing, you will never need this. - * - * @param macs - */ - public synchronized void setClient2ServerMACs(String[] macs) - { - if ((macs == null) || (macs.length == 0)) - throw new IllegalArgumentException(); - macs = removeDuplicates(macs); - MAC.checkMacList(macs); - cryptoWishList.c2s_mac_algos = macs; - } - - /** - * Sets the parameters for the diffie-hellman group exchange. Unless you - * know what you are doing, you will never need this. Default values are - * defined in the {@link DHGexParameters} class. - * - * @param dgp {@link DHGexParameters}, non null. - * - */ - public synchronized void setDHGexParameters(DHGexParameters dgp) - { - if (dgp == null) - throw new IllegalArgumentException(); - - dhgexpara = dgp; - } - - /** - * Unless you know what you are doing, you will never need this. - * - * @param ciphers - */ - public synchronized void setServer2ClientCiphers(String[] ciphers) - { - if ((ciphers == null) || (ciphers.length == 0)) - throw new IllegalArgumentException(); - ciphers = removeDuplicates(ciphers); - BlockCipherFactory.checkCipherList(ciphers); - cryptoWishList.s2c_enc_algos = ciphers; - } - - /** - * Unless you know what you are doing, you will never need this. - * - * @param macs - */ - public synchronized void setServer2ClientMACs(String[] macs) - { - if ((macs == null) || (macs.length == 0)) - throw new IllegalArgumentException(); - - macs = removeDuplicates(macs); - MAC.checkMacList(macs); - cryptoWishList.s2c_mac_algos = macs; - } - - /** - * Define the set of allowed server host key algorithms to be used for - * the following key exchange operations. - *

      - * Unless you know what you are doing, you will never need this. - * - * @param algos An array of allowed server host key algorithms. - * SSH-2 defines ssh-dss and ssh-rsa. - * The entries of the array must be ordered after preference, i.e., - * the entry at index 0 is the most preferred one. You must specify - * at least one entry. - */ - public synchronized void setServerHostKeyAlgorithms(String[] algos) - { - if ((algos == null) || (algos.length == 0)) - throw new IllegalArgumentException(); - - algos = removeDuplicates(algos); - KexManager.checkServerHostkeyAlgorithmsList(algos); - cryptoWishList.serverHostKeyAlgorithms = algos; - } - - /** - * Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm) on the underlying socket. - *

      - * Can be called at any time. If the connection has not yet been established - * then the passed value will be stored and set after the socket has been set up. - * The default value that will be used is false. - * - * @param enable the argument passed to the Socket.setTCPNoDelay() method. - * @throws IOException - */ - public synchronized void setTCPNoDelay(boolean enable) throws IOException - { - tcpNoDelay = enable; - - if (tm != null) - tm.setTcpNoDelay(enable); - } - - /** - * Used to tell the library that the connection shall be established through a proxy server. - * It only makes sense to call this method before calling the {@link #connect() connect()} - * method. - *

      - * At the moment, only HTTP proxies are supported. - *

      - * Note: This method can be called any number of times. The {@link #connect() connect()} - * method will use the value set in the last preceding invocation of this method. - * - * @see HTTPProxyData - * - * @param proxyData Connection information about the proxy. If null, then - * no proxy will be used (non surprisingly, this is also the default). - */ - public synchronized void setProxyData(ProxyData proxyData) - { - this.proxyData = proxyData; - } - - /** - * Request a remote port forwarding. - * If successful, then forwarded connections will be redirected to the given target address. - * You can cancle a requested remote port forwarding by calling - * {@link #cancelRemotePortForwarding(int) cancelRemotePortForwarding()}. - *

      - * A call of this method will block until the peer either agreed or disagreed to your request- - *

      - * Note 1: this method typically fails if you - *

        - *
      • pass a port number for which the used remote user has not enough permissions (i.e., port - * < 1024)
      • - *
      • or pass a port number that is already in use on the remote server
      • - *
      • or if remote port forwarding is disabled on the server.
      • - *
      - *

      - * Note 2: (from the openssh man page): By default, the listening socket on the server will be - * bound to the loopback interface only. This may be overriden by specifying a bind address. - * Specifying a remote bind address will only succeed if the server's GatewayPorts option - * is enabled (see sshd_config(5)). - * - * @param bindAddress address to bind to on the server: - *

        - *
      • "" means that connections are to be accepted on all protocol families - * supported by the SSH implementation
      • - *
      • "0.0.0.0" means to listen on all IPv4 addresses
      • - *
      • "::" means to listen on all IPv6 addresses
      • - *
      • "localhost" means to listen on all protocol families supported by the SSH - * implementation on loopback addresses only, [RFC3330] and RFC3513]
      • - *
      • "127.0.0.1" and "::1" indicate listening on the loopback interfaces for - * IPv4 and IPv6 respectively
      • - *
      - * @param bindPort port number to bind on the server (must be > 0) - * @param targetAddress the target address (IP or hostname) - * @param targetPort the target port - * @throws IOException - */ - public synchronized void requestRemotePortForwarding(String bindAddress, int bindPort, String targetAddress, - int targetPort) throws IOException - { - if (tm == null) - throw new IllegalStateException("You need to establish a connection first."); - - if (!authenticated) - throw new IllegalStateException("The connection is not authenticated."); - - if ((bindAddress == null) || (targetAddress == null) || (bindPort <= 0) || (targetPort <= 0)) - throw new IllegalArgumentException(); - - cm.requestGlobalForward(bindAddress, bindPort, targetAddress, targetPort); - } - - /** - * Cancel an earlier requested remote port forwarding. - * Currently active forwardings will not be affected (e.g., disrupted). - * Note that further connection forwarding requests may be received until - * this method has returned. - * - * @param bindPort the allocated port number on the server - * @throws IOException if the remote side refuses the cancel request or another low - * level error occurs (e.g., the underlying connection is closed) - */ - public synchronized void cancelRemotePortForwarding(int bindPort) throws IOException - { - if (tm == null) - throw new IllegalStateException("You need to establish a connection first."); - - if (!authenticated) - throw new IllegalStateException("The connection is not authenticated."); - - cm.requestCancelGlobalForward(bindPort); - } - - /** - * Provide your own instance of SecureRandom. Can be used, e.g., if you - * want to seed the used SecureRandom generator manually. - *

      - * The SecureRandom instance is used during key exchanges, public key authentication, - * x11 cookie generation and the like. - * - * @param rnd a SecureRandom instance - */ - public synchronized void setSecureRandom(SecureRandom rnd) - { - if (rnd == null) - throw new IllegalArgumentException(); - - this.generator = rnd; - } -} diff --git a/third-party/ganymed/src/main/java/ch/ethz/ssh2/channel/ChannelManager.java b/third-party/ganymed/src/main/java/ch/ethz/ssh2/channel/ChannelManager.java deleted file mode 100644 index 8fec9a0f54..0000000000 --- a/third-party/ganymed/src/main/java/ch/ethz/ssh2/channel/ChannelManager.java +++ /dev/null @@ -1,1845 +0,0 @@ -/* - * Copyright (c) 2006-2013 Christian Plattner. All rights reserved. - * Please refer to the LICENSE.txt for licensing details. - */ - -package ch.ethz.ssh2.channel; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Vector; - -import ch.ethz.ssh2.ChannelCondition; -import ch.ethz.ssh2.PtySettings; -import ch.ethz.ssh2.ServerConnectionCallback; -import ch.ethz.ssh2.ServerSessionCallback; -import ch.ethz.ssh2.log.Logger; -import ch.ethz.ssh2.packets.PacketChannelFailure; -import ch.ethz.ssh2.packets.PacketChannelOpenConfirmation; -import ch.ethz.ssh2.packets.PacketChannelOpenFailure; -import ch.ethz.ssh2.packets.PacketChannelSuccess; -import ch.ethz.ssh2.packets.PacketGlobalCancelForwardRequest; -import ch.ethz.ssh2.packets.PacketGlobalForwardRequest; -import ch.ethz.ssh2.packets.PacketOpenDirectTCPIPChannel; -import ch.ethz.ssh2.packets.PacketOpenSessionChannel; -import ch.ethz.ssh2.packets.PacketSessionExecCommand; -import ch.ethz.ssh2.packets.PacketSessionPtyRequest; -import ch.ethz.ssh2.packets.PacketSessionStartShell; -import ch.ethz.ssh2.packets.PacketSessionSubsystemRequest; -import ch.ethz.ssh2.packets.PacketSessionX11Request; -import ch.ethz.ssh2.packets.Packets; -import ch.ethz.ssh2.packets.TypesReader; -import ch.ethz.ssh2.server.ServerConnectionState; -import ch.ethz.ssh2.transport.MessageHandler; -import ch.ethz.ssh2.transport.TransportManager; - -/** - * ChannelManager. Please read the comments in Channel.java. - *

      - * Besides the crypto part, this is the core of the library. - * - * @author Christian Plattner - * @version $Id: ChannelManager.java 48 2013-08-01 12:22:33Z cleondris@gmail.com $ - */ -public class ChannelManager implements MessageHandler -{ - private static final Logger log = Logger.getLogger(ChannelManager.class); - - private final ServerConnectionState server_state; - private final TransportManager tm; - - private final HashMap x11_magic_cookies = new HashMap(); - - private final List channels = new Vector(); - private int nextLocalChannel = 100; - private boolean shutdown = false; - private int globalSuccessCounter = 0; - private int globalFailedCounter = 0; - - private final HashMap remoteForwardings = new HashMap(); - - private final List listenerThreads = new Vector(); - - private boolean listenerThreadsAllowed = true; - - /** - * Constructor for client-mode. - * @param tm - */ - public ChannelManager(TransportManager tm) - { - this.server_state = null; - this.tm = tm; - tm.registerMessageHandler(this, 80, 100); - } - - /** - * Constructor for server-mode. - * @param state - */ - public ChannelManager(ServerConnectionState state) - { - this.server_state = state; - this.tm = state.tm; - tm.registerMessageHandler(this, 80, 100); - } - - private Channel getChannel(int id) - { - synchronized (channels) - { - for (Channel c : channels) - { - if (c.localID == id) - return c; - } - } - return null; - } - - private void removeChannel(int id) - { - synchronized (channels) - { - for (Channel c : channels) - { - if (c.localID == id) - { - channels.remove(c); - break; - } - } - } - } - - private int addChannel(Channel c) - { - synchronized (channels) - { - channels.add(c); - return nextLocalChannel++; - } - } - - private void waitUntilChannelOpen(Channel c) throws IOException - { - boolean wasInterrupted = false; - - synchronized (c) - { - while (c.state == Channel.STATE_OPENING) - { - try - { - c.wait(); - } - catch (InterruptedException ignore) - { - wasInterrupted = true; - } - } - - if (c.state != Channel.STATE_OPEN) - { - removeChannel(c.localID); - - String detail = c.getReasonClosed(); - - if (detail == null) - detail = "state: " + c.state; - - throw new IOException("Could not open channel (" + detail + ")"); - } - } - - if (wasInterrupted) - Thread.currentThread().interrupt(); - } - - private void waitForGlobalSuccessOrFailure() throws IOException - { - boolean wasInterrupted = false; - - try - { - synchronized (channels) - { - while ((globalSuccessCounter == 0) && (globalFailedCounter == 0)) - { - if (shutdown) - { - throw new IOException("The connection is being shutdown"); - } - - try - { - channels.wait(); - } - catch (InterruptedException ignore) - { - wasInterrupted = true; - } - } - - if (globalFailedCounter != 0) - { - throw new IOException("The server denied the request (did you enable port forwarding?)"); - } - - if (globalSuccessCounter == 0) - { - throw new IOException("Illegal state."); - } - } - } - finally - { - if (wasInterrupted) - Thread.currentThread().interrupt(); - } - } - - private void waitForChannelSuccessOrFailure(Channel c) throws IOException - { - boolean wasInterrupted = false; - - try - { - synchronized (c) - { - while ((c.successCounter == 0) && (c.failedCounter == 0)) - { - if (c.state != Channel.STATE_OPEN) - { - String detail = c.getReasonClosed(); - - if (detail == null) - detail = "state: " + c.state; - - throw new IOException("This SSH2 channel is not open (" + detail + ")"); - } - - try - { - c.wait(); - } - catch (InterruptedException ignore) - { - wasInterrupted = true; - } - } - - if (c.failedCounter != 0) - { - throw new IOException("The server denied the request."); - } - } - } - finally - { - if (wasInterrupted) - Thread.currentThread().interrupt(); - } - } - - public void registerX11Cookie(String hexFakeCookie, X11ServerData data) - { - synchronized (x11_magic_cookies) - { - x11_magic_cookies.put(hexFakeCookie, data); - } - } - - public void unRegisterX11Cookie(String hexFakeCookie, boolean killChannels) - { - if (hexFakeCookie == null) - throw new IllegalStateException("hexFakeCookie may not be null"); - - synchronized (x11_magic_cookies) - { - x11_magic_cookies.remove(hexFakeCookie); - } - - if (killChannels == false) - return; - - log.debug("Closing all X11 channels for the given fake cookie"); - - List channel_copy = new Vector(); - - synchronized (channels) - { - channel_copy.addAll(channels); - } - - for (Channel c : channel_copy) - { - synchronized (c) - { - if (hexFakeCookie.equals(c.hexX11FakeCookie) == false) - continue; - } - - try - { - closeChannel(c, "Closing X11 channel since the corresponding session is closing", true); - } - catch (IOException ignored) - { - } - } - } - - public X11ServerData checkX11Cookie(String hexFakeCookie) - { - synchronized (x11_magic_cookies) - { - if (hexFakeCookie != null) - return x11_magic_cookies.get(hexFakeCookie); - } - return null; - } - - public void closeAllChannels() - { - log.debug("Closing all channels"); - - List channel_copy = new Vector(); - - synchronized (channels) - { - channel_copy.addAll(channels); - } - - for (Channel c : channel_copy) - { - try - { - closeChannel(c, "Closing all channels", true); - } - catch (IOException ignored) - { - } - } - } - - public void closeChannel(Channel c, String reason, boolean force) throws IOException - { - byte msg[] = new byte[5]; - - synchronized (c) - { - if (force) - { - c.state = Channel.STATE_CLOSED; - c.EOF = true; - } - - c.setReasonClosed(reason); - - msg[0] = Packets.SSH_MSG_CHANNEL_CLOSE; - msg[1] = (byte) (c.remoteID >> 24); - msg[2] = (byte) (c.remoteID >> 16); - msg[3] = (byte) (c.remoteID >> 8); - msg[4] = (byte) (c.remoteID); - - c.notifyAll(); - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent == true) - return; - tm.sendMessage(msg); - c.closeMessageSent = true; - } - - log.debug("Sent SSH_MSG_CHANNEL_CLOSE (channel " + c.localID + ")"); - } - - public void sendEOF(Channel c) throws IOException - { - byte[] msg = new byte[5]; - - synchronized (c) - { - if (c.state != Channel.STATE_OPEN) - return; - - msg[0] = Packets.SSH_MSG_CHANNEL_EOF; - msg[1] = (byte) (c.remoteID >> 24); - msg[2] = (byte) (c.remoteID >> 16); - msg[3] = (byte) (c.remoteID >> 8); - msg[4] = (byte) (c.remoteID); - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent == true) - return; - tm.sendMessage(msg); - } - - - log.debug("Sent EOF (Channel " + c.localID + "/" + c.remoteID + ")"); - } - - public void sendOpenConfirmation(Channel c) throws IOException - { - PacketChannelOpenConfirmation pcoc = null; - - synchronized (c) - { - if (c.state != Channel.STATE_OPENING) - return; - - c.state = Channel.STATE_OPEN; - - pcoc = new PacketChannelOpenConfirmation(c.remoteID, c.localID, c.localWindow, c.localMaxPacketSize); - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent == true) - return; - tm.sendMessage(pcoc.getPayload()); - } - } - - public void sendData(Channel c, byte[] buffer, int pos, int len) throws IOException - { - boolean wasInterrupted = false; - - try - { - while (len > 0) - { - int thislen = 0; - byte[] msg; - - synchronized (c) - { - while (true) - { - if (c.state == Channel.STATE_CLOSED) - throw new ChannelClosedException("SSH channel is closed. (" + c.getReasonClosed() + ")"); - - if (c.state != Channel.STATE_OPEN) - throw new ChannelClosedException("SSH channel in strange state. (" + c.state + ")"); - - if (c.remoteWindow != 0) - break; - - try - { - c.wait(); - } - catch (InterruptedException ignore) - { - wasInterrupted = true; - } - } - - /* len > 0, no sign extension can happen when comparing */ - - thislen = (c.remoteWindow >= len) ? len : (int) c.remoteWindow; - - int estimatedMaxDataLen = c.remoteMaxPacketSize - (tm.getPacketOverheadEstimate() + 9); - - /* The worst case scenario =) a true bottleneck */ - - if (estimatedMaxDataLen <= 0) - { - estimatedMaxDataLen = 1; - } - - if (thislen > estimatedMaxDataLen) - thislen = estimatedMaxDataLen; - - c.remoteWindow -= thislen; - - msg = new byte[1 + 8 + thislen]; - - msg[0] = Packets.SSH_MSG_CHANNEL_DATA; - msg[1] = (byte) (c.remoteID >> 24); - msg[2] = (byte) (c.remoteID >> 16); - msg[3] = (byte) (c.remoteID >> 8); - msg[4] = (byte) (c.remoteID); - msg[5] = (byte) (thislen >> 24); - msg[6] = (byte) (thislen >> 16); - msg[7] = (byte) (thislen >> 8); - msg[8] = (byte) (thislen); - - System.arraycopy(buffer, pos, msg, 9, thislen); - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent == true) - throw new ChannelClosedException("SSH channel is closed. (" + c.getReasonClosed() + ")"); - - tm.sendMessage(msg); - } - - pos += thislen; - len -= thislen; - } - } - finally - { - if (wasInterrupted) - Thread.currentThread().interrupt(); - } - } - - public int requestGlobalForward(String bindAddress, int bindPort, String targetAddress, int targetPort) - throws IOException - { - RemoteForwardingData rfd = new RemoteForwardingData(); - - rfd.bindAddress = bindAddress; - rfd.bindPort = bindPort; - rfd.targetAddress = targetAddress; - rfd.targetPort = targetPort; - - synchronized (remoteForwardings) - { - Integer key = new Integer(bindPort); - - if (remoteForwardings.get(key) != null) - { - throw new IOException("There is already a forwarding for remote port " + bindPort); - } - - remoteForwardings.put(key, rfd); - } - - synchronized (channels) - { - globalSuccessCounter = globalFailedCounter = 0; - } - - PacketGlobalForwardRequest pgf = new PacketGlobalForwardRequest(true, bindAddress, bindPort); - tm.sendMessage(pgf.getPayload()); - - log.debug("Requesting a remote forwarding ('" + bindAddress + "', " + bindPort + ")"); - - try - { - waitForGlobalSuccessOrFailure(); - } - catch (IOException e) - { - synchronized (remoteForwardings) - { - remoteForwardings.remove(rfd); - } - throw e; - } - - return bindPort; - } - - public void requestCancelGlobalForward(int bindPort) throws IOException - { - RemoteForwardingData rfd = null; - - synchronized (remoteForwardings) - { - rfd = remoteForwardings.get(new Integer(bindPort)); - - if (rfd == null) - throw new IOException("Sorry, there is no known remote forwarding for remote port " + bindPort); - } - - synchronized (channels) - { - globalSuccessCounter = globalFailedCounter = 0; - } - - PacketGlobalCancelForwardRequest pgcf = new PacketGlobalCancelForwardRequest(true, rfd.bindAddress, - rfd.bindPort); - tm.sendMessage(pgcf.getPayload()); - - log.debug("Requesting cancelation of remote forward ('" + rfd.bindAddress + "', " + rfd.bindPort + ")"); - - waitForGlobalSuccessOrFailure(); - - /* Only now we are sure that no more forwarded connections will arrive */ - - synchronized (remoteForwardings) - { - remoteForwardings.remove(rfd); - } - } - - public void registerThread(IChannelWorkerThread thr) throws IOException - { - synchronized (listenerThreads) - { - if (listenerThreadsAllowed == false) - throw new IOException("Too late, this connection is closed."); - listenerThreads.add(thr); - } - } - - public Channel openDirectTCPIPChannel(String host_to_connect, int port_to_connect, String originator_IP_address, - int originator_port) throws IOException - { - Channel c = new Channel(this); - - synchronized (c) - { - c.localID = addChannel(c); - // end of synchronized block forces writing out to main memory - } - - PacketOpenDirectTCPIPChannel dtc = new PacketOpenDirectTCPIPChannel(c.localID, c.localWindow, - c.localMaxPacketSize, host_to_connect, port_to_connect, originator_IP_address, originator_port); - - tm.sendMessage(dtc.getPayload()); - - waitUntilChannelOpen(c); - - return c; - } - - public Channel openSessionChannel() throws IOException - { - Channel c = new Channel(this); - - synchronized (c) - { - c.localID = addChannel(c); - // end of synchronized block forces the writing out to main memory - } - - log.debug("Sending SSH_MSG_CHANNEL_OPEN (Channel " + c.localID + ")"); - - PacketOpenSessionChannel smo = new PacketOpenSessionChannel(c.localID, c.localWindow, c.localMaxPacketSize); - tm.sendMessage(smo.getPayload()); - - waitUntilChannelOpen(c); - - return c; - } - - public void requestPTY(Channel c, String term, int term_width_characters, int term_height_characters, - int term_width_pixels, int term_height_pixels, byte[] terminal_modes) throws IOException - { - PacketSessionPtyRequest spr; - - synchronized (c) - { - if (c.state != Channel.STATE_OPEN) - throw new IOException("Cannot request PTY on this channel (" + c.getReasonClosed() + ")"); - - spr = new PacketSessionPtyRequest(c.remoteID, true, term, term_width_characters, term_height_characters, - term_width_pixels, term_height_pixels, terminal_modes); - - c.successCounter = c.failedCounter = 0; - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent) - throw new IOException("Cannot request PTY on this channel (" + c.getReasonClosed() + ")"); - tm.sendMessage(spr.getPayload()); - } - - try - { - waitForChannelSuccessOrFailure(c); - } - catch (IOException e) - { - throw (IOException) new IOException("PTY request failed").initCause(e); - } - } - - public void requestX11(Channel c, boolean singleConnection, String x11AuthenticationProtocol, - String x11AuthenticationCookie, int x11ScreenNumber) throws IOException - { - PacketSessionX11Request psr; - - synchronized (c) - { - if (c.state != Channel.STATE_OPEN) - throw new IOException("Cannot request X11 on this channel (" + c.getReasonClosed() + ")"); - - psr = new PacketSessionX11Request(c.remoteID, true, singleConnection, x11AuthenticationProtocol, - x11AuthenticationCookie, x11ScreenNumber); - - c.successCounter = c.failedCounter = 0; - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent) - throw new IOException("Cannot request X11 on this channel (" + c.getReasonClosed() + ")"); - tm.sendMessage(psr.getPayload()); - } - - log.debug("Requesting X11 forwarding (Channel " + c.localID + "/" + c.remoteID + ")"); - - try - { - waitForChannelSuccessOrFailure(c); - } - catch (IOException e) - { - throw (IOException) new IOException("The X11 request failed.").initCause(e); - } - } - - public void requestSubSystem(Channel c, String subSystemName) throws IOException - { - PacketSessionSubsystemRequest ssr; - - synchronized (c) - { - if (c.state != Channel.STATE_OPEN) - throw new IOException("Cannot request subsystem on this channel (" + c.getReasonClosed() + ")"); - - ssr = new PacketSessionSubsystemRequest(c.remoteID, true, subSystemName); - - c.successCounter = c.failedCounter = 0; - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent) - throw new IOException("Cannot request subsystem on this channel (" + c.getReasonClosed() + ")"); - tm.sendMessage(ssr.getPayload()); - } - - try - { - waitForChannelSuccessOrFailure(c); - } - catch (IOException e) - { - throw (IOException) new IOException("The subsystem request failed.").initCause(e); - } - } - - public void requestExecCommand(Channel c, String cmd) throws IOException - { - this.requestExecCommand(c, cmd, null); - } - - /** - * @param charsetName The charset used to convert between Java Unicode Strings and byte encodings - */ - public void requestExecCommand(Channel c, String cmd, String charsetName) throws IOException - { - PacketSessionExecCommand sm; - - synchronized (c) - { - if (c.state != Channel.STATE_OPEN) - throw new IOException("Cannot execute command on this channel (" + c.getReasonClosed() + ")"); - - sm = new PacketSessionExecCommand(c.remoteID, true, cmd); - - c.successCounter = c.failedCounter = 0; - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent) - throw new IOException("Cannot execute command on this channel (" + c.getReasonClosed() + ")"); - tm.sendMessage(sm.getPayload(charsetName)); - } - - log.debug("Executing command (channel " + c.localID + ", '" + cmd + "')"); - - try - { - waitForChannelSuccessOrFailure(c); - } - catch (IOException e) - { - throw (IOException) new IOException("The execute request failed.").initCause(e); - } - } - - public void requestShell(Channel c) throws IOException - { - PacketSessionStartShell sm; - - synchronized (c) - { - if (c.state != Channel.STATE_OPEN) - throw new IOException("Cannot start shell on this channel (" + c.getReasonClosed() + ")"); - - sm = new PacketSessionStartShell(c.remoteID, true); - - c.successCounter = c.failedCounter = 0; - } - - synchronized (c.channelSendLock) - { - if (c.closeMessageSent) - throw new IOException("Cannot start shell on this channel (" + c.getReasonClosed() + ")"); - tm.sendMessage(sm.getPayload()); - } - - try - { - waitForChannelSuccessOrFailure(c); - } - catch (IOException e) - { - throw (IOException) new IOException("The shell request failed.").initCause(e); - } - } - - public void msgChannelExtendedData(byte[] msg, int msglen) throws IOException - { - if (msglen <= 13) - throw new IOException("SSH_MSG_CHANNEL_EXTENDED_DATA message has wrong size (" + msglen + ")"); - - int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff); - int dataType = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16) | ((msg[7] & 0xff) << 8) | (msg[8] & 0xff); - int len = ((msg[9] & 0xff) << 24) | ((msg[10] & 0xff) << 16) | ((msg[11] & 0xff) << 8) | (msg[12] & 0xff); - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_EXTENDED_DATA message for non-existent channel " + id); - - if (dataType != Packets.SSH_EXTENDED_DATA_STDERR) - throw new IOException("SSH_MSG_CHANNEL_EXTENDED_DATA message has unknown type (" + dataType + ")"); - - if (len != (msglen - 13)) - throw new IOException("SSH_MSG_CHANNEL_EXTENDED_DATA message has wrong len (calculated " + (msglen - 13) - + ", got " + len + ")"); - - log.debug("Got SSH_MSG_CHANNEL_EXTENDED_DATA (channel " + id + ", " + len + ")"); - - synchronized (c) - { - if (c.state == Channel.STATE_CLOSED) - return; // ignore - - if (c.state != Channel.STATE_OPEN) - throw new IOException("Got SSH_MSG_CHANNEL_EXTENDED_DATA, but channel is not in correct state (" - + c.state + ")"); - - if (c.localWindow < len) - throw new IOException("Remote sent too much data, does not fit into window."); - - c.localWindow -= len; - - System.arraycopy(msg, 13, c.stderrBuffer, c.stderrWritepos, len); - c.stderrWritepos += len; - - c.notifyAll(); - } - } - - /** - * Wait until for a condition. - * - * @param c Channel - * @param timeout in ms, 0 means no timeout. - * @param condition_mask minimum event mask (at least one of the conditions must be fulfilled) - * @return all current events - */ - public int waitForCondition(Channel c, long timeout, int condition_mask) - { - boolean wasInterrupted = false; - - try - { - long end_time = 0; - boolean end_time_set = false; - - synchronized (c) - { - while (true) - { - int current_cond = 0; - - int stdoutAvail = c.stdoutWritepos - c.stdoutReadpos; - int stderrAvail = c.stderrWritepos - c.stderrReadpos; - - if (stdoutAvail > 0) - current_cond = current_cond | ChannelCondition.STDOUT_DATA; - - if (stderrAvail > 0) - current_cond = current_cond | ChannelCondition.STDERR_DATA; - - if (c.EOF) - current_cond = current_cond | ChannelCondition.EOF; - - if (c.getExitStatus() != null) - current_cond = current_cond | ChannelCondition.EXIT_STATUS; - - if (c.getExitSignal() != null) - current_cond = current_cond | ChannelCondition.EXIT_SIGNAL; - - if (c.state == Channel.STATE_CLOSED) - return current_cond | ChannelCondition.CLOSED | ChannelCondition.EOF; - - if ((current_cond & condition_mask) != 0) - return current_cond; - - if (timeout > 0) - { - if (!end_time_set) - { - end_time = System.currentTimeMillis() + timeout; - end_time_set = true; - } - else - { - timeout = end_time - System.currentTimeMillis(); - - if (timeout <= 0) - return current_cond | ChannelCondition.TIMEOUT; - } - } - - try - { - if (timeout > 0) - c.wait(timeout); - else - c.wait(); - } - catch (InterruptedException e) - { - wasInterrupted = true; - } - } - } - } - finally - { - if (wasInterrupted) - Thread.currentThread().interrupt(); - } - } - - public int getAvailable(Channel c, boolean extended) throws IOException - { - synchronized (c) - { - int avail; - - if (extended) - avail = c.stderrWritepos - c.stderrReadpos; - else - avail = c.stdoutWritepos - c.stdoutReadpos; - - return ((avail > 0) ? avail : (c.EOF ? -1 : 0)); - } - } - - public int getChannelData(Channel c, boolean extended, byte[] target, int off, int len) throws IOException - { - boolean wasInterrupted = false; - - try - { - int copylen = 0; - int increment = 0; - int remoteID = 0; - int localID = 0; - - synchronized (c) - { - int stdoutAvail = 0; - int stderrAvail = 0; - - while (true) - { - /* - * Data available? We have to return remaining data even if the - * channel is already closed. - */ - - stdoutAvail = c.stdoutWritepos - c.stdoutReadpos; - stderrAvail = c.stderrWritepos - c.stderrReadpos; - - if ((!extended) && (stdoutAvail != 0)) - break; - - if ((extended) && (stderrAvail != 0)) - break; - - /* Do not wait if more data will never arrive (EOF or CLOSED) */ - - if ((c.EOF) || (c.state != Channel.STATE_OPEN)) - return -1; - - try - { - c.wait(); - } - catch (InterruptedException ignore) - { - wasInterrupted = true; - } - } - - /* OK, there is some data. Return it. */ - - if (!extended) - { - copylen = (stdoutAvail > len) ? len : stdoutAvail; - System.arraycopy(c.stdoutBuffer, c.stdoutReadpos, target, off, copylen); - c.stdoutReadpos += copylen; - - if (c.stdoutReadpos != c.stdoutWritepos) - - System.arraycopy(c.stdoutBuffer, c.stdoutReadpos, c.stdoutBuffer, 0, c.stdoutWritepos - - c.stdoutReadpos); - - c.stdoutWritepos -= c.stdoutReadpos; - c.stdoutReadpos = 0; - } - else - { - copylen = (stderrAvail > len) ? len : stderrAvail; - System.arraycopy(c.stderrBuffer, c.stderrReadpos, target, off, copylen); - c.stderrReadpos += copylen; - - if (c.stderrReadpos != c.stderrWritepos) - - System.arraycopy(c.stderrBuffer, c.stderrReadpos, c.stderrBuffer, 0, c.stderrWritepos - - c.stderrReadpos); - - c.stderrWritepos -= c.stderrReadpos; - c.stderrReadpos = 0; - } - - if (c.state != Channel.STATE_OPEN) - return copylen; - - if (c.localWindow < ((Channel.CHANNEL_BUFFER_SIZE + 1) / 2)) - { - int minFreeSpace = Math.min(Channel.CHANNEL_BUFFER_SIZE - c.stdoutWritepos, - Channel.CHANNEL_BUFFER_SIZE - c.stderrWritepos); - - increment = minFreeSpace - c.localWindow; - c.localWindow = minFreeSpace; - } - - remoteID = c.remoteID; /* read while holding the lock */ - localID = c.localID; /* read while holding the lock */ - } - - /* - * If a consumer reads stdout and stdin in parallel, we may end up with - * sending two msgWindowAdjust messages. Luckily, it - * does not matter in which order they arrive at the server. - */ - - if (increment > 0) - { - log.debug("Sending SSH_MSG_CHANNEL_WINDOW_ADJUST (channel " + localID + ", " + increment + ")"); - - synchronized (c.channelSendLock) - { - byte[] msg = c.msgWindowAdjust; - - msg[0] = Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST; - msg[1] = (byte) (remoteID >> 24); - msg[2] = (byte) (remoteID >> 16); - msg[3] = (byte) (remoteID >> 8); - msg[4] = (byte) (remoteID); - msg[5] = (byte) (increment >> 24); - msg[6] = (byte) (increment >> 16); - msg[7] = (byte) (increment >> 8); - msg[8] = (byte) (increment); - - if (c.closeMessageSent == false) - tm.sendMessage(msg); - } - } - - return copylen; - } - finally - { - if (wasInterrupted) - Thread.currentThread().interrupt(); - } - - } - - public void msgChannelData(byte[] msg, int msglen) throws IOException - { - if (msglen <= 9) - throw new IOException("SSH_MSG_CHANNEL_DATA message has wrong size (" + msglen + ")"); - - int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff); - int len = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16) | ((msg[7] & 0xff) << 8) | (msg[8] & 0xff); - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_DATA message for non-existent channel " + id); - - if (len != (msglen - 9)) - throw new IOException("SSH_MSG_CHANNEL_DATA message has wrong len (calculated " + (msglen - 9) + ", got " - + len + ")"); - - log.debug("Got SSH_MSG_CHANNEL_DATA (channel " + id + ", " + len + ")"); - - synchronized (c) - { - if (c.state == Channel.STATE_CLOSED) - return; // ignore - - if (c.state != Channel.STATE_OPEN) - throw new IOException("Got SSH_MSG_CHANNEL_DATA, but channel is not in correct state (" + c.state + ")"); - - if (c.localWindow < len) - throw new IOException("Remote sent too much data, does not fit into window."); - - c.localWindow -= len; - - System.arraycopy(msg, 9, c.stdoutBuffer, c.stdoutWritepos, len); - c.stdoutWritepos += len; - - c.notifyAll(); - } - } - - public void msgChannelWindowAdjust(byte[] msg, int msglen) throws IOException - { - if (msglen != 9) - throw new IOException("SSH_MSG_CHANNEL_WINDOW_ADJUST message has wrong size (" + msglen + ")"); - - int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff); - int windowChange = ((msg[5] & 0xff) << 24) | ((msg[6] & 0xff) << 16) | ((msg[7] & 0xff) << 8) | (msg[8] & 0xff); - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_WINDOW_ADJUST message for non-existent channel " + id); - - synchronized (c) - { - final long huge = 0xFFFFffffL; /* 2^32 - 1 */ - - c.remoteWindow += (windowChange & huge); /* avoid sign extension */ - - /* TODO - is this a good heuristic? */ - - if ((c.remoteWindow > huge)) - c.remoteWindow = huge; - - c.notifyAll(); - } - - - log.debug("Got SSH_MSG_CHANNEL_WINDOW_ADJUST (channel " + id + ", " + windowChange + ")"); - } - - public void msgChannelOpen(byte[] msg, int msglen) throws IOException - { - TypesReader tr = new TypesReader(msg, 0, msglen); - - tr.readByte(); // skip packet type - String channelType = tr.readString(); - int remoteID = tr.readUINT32(); /* sender channel */ - int remoteWindow = tr.readUINT32(); /* initial window size */ - int remoteMaxPacketSize = tr.readUINT32(); /* maximum packet size */ - - if ("x11".equals(channelType)) - { - synchronized (x11_magic_cookies) - { - /* If we did not request X11 forwarding, then simply ignore this bogus request. */ - - if (x11_magic_cookies.size() == 0) - { - PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(remoteID, - Packets.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED, "X11 forwarding not activated", ""); - - tm.sendAsynchronousMessage(pcof.getPayload()); - - log.warning("Unexpected X11 request, denying it!"); - - return; - } - } - - String remoteOriginatorAddress = tr.readString(); - int remoteOriginatorPort = tr.readUINT32(); - - Channel c = new Channel(this); - - synchronized (c) - { - c.remoteID = remoteID; - c.remoteWindow = remoteWindow & 0xFFFFffffL; /* properly convert UINT32 to long */ - c.remoteMaxPacketSize = remoteMaxPacketSize; - c.localID = addChannel(c); - } - - /* - * The open confirmation message will be sent from another thread - */ - - RemoteX11AcceptThread rxat = new RemoteX11AcceptThread(c, remoteOriginatorAddress, remoteOriginatorPort); - rxat.setDaemon(true); - rxat.start(); - - return; - } - - if ("forwarded-tcpip".equals(channelType)) - { - String remoteConnectedAddress = tr.readString(); /* address that was connected */ - int remoteConnectedPort = tr.readUINT32(); /* port that was connected */ - String remoteOriginatorAddress = tr.readString(); /* originator IP address */ - int remoteOriginatorPort = tr.readUINT32(); /* originator port */ - - RemoteForwardingData rfd = null; - - synchronized (remoteForwardings) - { - rfd = remoteForwardings.get(new Integer(remoteConnectedPort)); - } - - if (rfd == null) - { - PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(remoteID, - Packets.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED, - "No thanks, unknown port in forwarded-tcpip request", ""); - - /* Always try to be polite. */ - - tm.sendAsynchronousMessage(pcof.getPayload()); - - log.debug("Unexpected forwarded-tcpip request, denying it!"); - - return; - } - - Channel c = new Channel(this); - - synchronized (c) - { - c.remoteID = remoteID; - c.remoteWindow = remoteWindow & 0xFFFFffffL; /* convert UINT32 to long */ - c.remoteMaxPacketSize = remoteMaxPacketSize; - c.localID = addChannel(c); - } - - /* - * The open confirmation message will be sent from another thread. - */ - - RemoteAcceptThread rat = new RemoteAcceptThread(c, remoteConnectedAddress, remoteConnectedPort, - remoteOriginatorAddress, remoteOriginatorPort, rfd.targetAddress, rfd.targetPort); - - rat.setDaemon(true); - rat.start(); - - return; - } - - if ((server_state != null) && ("session".equals(channelType))) - { - ServerConnectionCallback cb = null; - - synchronized (server_state) - { - cb = server_state.cb_conn; - } - - if (cb == null) - { - tm.sendAsynchronousMessage(new PacketChannelOpenFailure(remoteID, Packets.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED, - "Sessions are currently not enabled", "en").getPayload()); - - return; - } - - final Channel c = new Channel(this); - - synchronized (c) - { - c.remoteID = remoteID; - c.remoteWindow = remoteWindow & 0xFFFFffffL; /* convert UINT32 to long */ - c.remoteMaxPacketSize = remoteMaxPacketSize; - c.localID = addChannel(c); - c.state = Channel.STATE_OPEN; - c.ss = new ServerSessionImpl(c); - } - - PacketChannelOpenConfirmation pcoc = new PacketChannelOpenConfirmation(c.remoteID, c.localID, - c.localWindow, c.localMaxPacketSize); - - tm.sendAsynchronousMessage(pcoc.getPayload()); - - c.ss.sscb = cb.acceptSession(c.ss); - - return; - } - - /* Tell the server that we have no idea what it is talking about */ - - PacketChannelOpenFailure pcof = new PacketChannelOpenFailure(remoteID, Packets.SSH_OPEN_UNKNOWN_CHANNEL_TYPE, - "Unknown channel type", ""); - - tm.sendAsynchronousMessage(pcof.getPayload()); - - - log.warning("The peer tried to open an unsupported channel type (" + channelType + ")"); - } - - /* Starts the given runnable in a foreground (non-daemon) thread */ - private void runAsync(Runnable r) - { - Thread t = new Thread(r); - t.start(); - } - - public void msgChannelRequest(byte[] msg, int msglen) throws IOException - { - TypesReader tr = new TypesReader(msg, 0, msglen); - - tr.readByte(); // skip packet type - int id = tr.readUINT32(); - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_REQUEST message for non-existent channel " + id); - - ServerSessionImpl server_session = null; - - if (server_state != null) - { - synchronized (c) - { - server_session = c.ss; - } - } - - String type = tr.readString("US-ASCII"); - boolean wantReply = tr.readBoolean(); - - log.debug("Got SSH_MSG_CHANNEL_REQUEST (channel " + id + ", '" + type + "')"); - - if (type.equals("exit-status")) - { - if (wantReply != false) - throw new IOException( - "Badly formatted SSH_MSG_CHANNEL_REQUEST exit-status message, 'want reply' is true"); - - int exit_status = tr.readUINT32(); - - if (tr.remain() != 0) - throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message"); - - synchronized (c) - { - c.exit_status = new Integer(exit_status); - c.notifyAll(); - } - - log.debug("Got EXIT STATUS (channel " + id + ", status " + exit_status + ")"); - - return; - } - - if ((server_state == null) && (type.equals("exit-signal"))) - { - if (wantReply != false) - throw new IOException( - "Badly formatted SSH_MSG_CHANNEL_REQUEST exit-signal message, 'want reply' is true"); - - String signame = tr.readString("US-ASCII"); - tr.readBoolean(); - tr.readString(); - tr.readString(); - - if (tr.remain() != 0) - throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message"); - - synchronized (c) - { - c.exit_signal = signame; - c.notifyAll(); - } - - log.debug("Got EXIT SIGNAL (channel " + id + ", signal " + signame + ")"); - - return; - } - - if ((server_session != null) && (type.equals("pty-req"))) - { - PtySettings pty = new PtySettings(); - - pty.term = tr.readString(); - pty.term_width_characters = tr.readUINT32(); - pty.term_height_characters = tr.readUINT32(); - pty.term_width_pixels = tr.readUINT32(); - pty.term_height_pixels = tr.readUINT32(); - pty.terminal_modes = tr.readByteString(); - - if (tr.remain() != 0) - throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message"); - - Runnable run_after_sending_success = null; - - ServerSessionCallback sscb = server_session.getServerSessionCallback(); - - if (sscb != null) - run_after_sending_success = sscb.requestPtyReq(server_session, pty); - - if (wantReply) - { - if (run_after_sending_success != null) - { - tm.sendAsynchronousMessage(new PacketChannelSuccess(c.remoteID).getPayload()); - } - else - { - tm.sendAsynchronousMessage(new PacketChannelFailure(c.remoteID).getPayload()); - } - } - - if (run_after_sending_success != null) - { - runAsync(run_after_sending_success); - } - - return; - } - - if ((server_session != null) && (type.equals("subsystem"))) - { - String command = tr.readString(); - if (tr.remain() != 0) - throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message"); - - Runnable run_after_sending_success = null; - ServerSessionCallback sscb = server_session.getServerSessionCallback(); - - if (sscb != null) - run_after_sending_success = sscb.requestSubsystem(server_session, command); - - if (wantReply) - { - if (run_after_sending_success != null) - { - tm.sendAsynchronousMessage(new PacketChannelSuccess(c.remoteID).getPayload()); - } - else - { - tm.sendAsynchronousMessage(new PacketChannelFailure(c.remoteID).getPayload()); - } - } - - if (run_after_sending_success != null) - { - runAsync(run_after_sending_success); - } - - return; - } - - if ((server_session != null) && (type.equals("shell"))) - { - if (tr.remain() != 0) - throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message"); - - Runnable run_after_sending_success = null; - ServerSessionCallback sscb = server_session.getServerSessionCallback(); - - if (sscb != null) - run_after_sending_success = sscb.requestShell(server_session); - - if (wantReply) - { - if (run_after_sending_success != null) - { - tm.sendAsynchronousMessage(new PacketChannelSuccess(c.remoteID).getPayload()); - } - else - { - tm.sendAsynchronousMessage(new PacketChannelFailure(c.remoteID).getPayload()); - } - } - - if (run_after_sending_success != null) - { - runAsync(run_after_sending_success); - } - - return; - } - - if ((server_session != null) && (type.equals("exec"))) - { - String command = tr.readString(); - - if (tr.remain() != 0) - throw new IOException("Badly formatted SSH_MSG_CHANNEL_REQUEST message"); - - Runnable run_after_sending_success = null; - ServerSessionCallback sscb = server_session.getServerSessionCallback(); - - if (sscb != null) - run_after_sending_success = sscb.requestExec(server_session, command); - - if (wantReply) - { - if (run_after_sending_success != null) - { - tm.sendAsynchronousMessage(new PacketChannelSuccess(c.remoteID).getPayload()); - } - else - { - tm.sendAsynchronousMessage(new PacketChannelFailure(c.remoteID).getPayload()); - } - } - - if (run_after_sending_success != null) - { - runAsync(run_after_sending_success); - } - - return; - } - - /* We simply ignore unknown channel requests, however, if the server wants a reply, - * then we signal that we have no idea what it is about. - */ - - if (wantReply) - { - tm.sendAsynchronousMessage(new PacketChannelFailure(c.remoteID).getPayload()); - } - - log.debug("Channel request '" + type + "' is not known, ignoring it"); - } - - public void msgChannelEOF(byte[] msg, int msglen) throws IOException - { - if (msglen != 5) - throw new IOException("SSH_MSG_CHANNEL_EOF message has wrong size (" + msglen + ")"); - - int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff); - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_EOF message for non-existent channel " + id); - - synchronized (c) - { - c.EOF = true; - c.notifyAll(); - } - - log.debug("Got SSH_MSG_CHANNEL_EOF (channel " + id + ")"); - } - - public void msgChannelClose(byte[] msg, int msglen) throws IOException - { - if (msglen != 5) - throw new IOException("SSH_MSG_CHANNEL_CLOSE message has wrong size (" + msglen + ")"); - - int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff); - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_CLOSE message for non-existent channel " + id); - - synchronized (c) - { - c.EOF = true; - c.state = Channel.STATE_CLOSED; - c.setReasonClosed("Close requested by remote"); - c.closeMessageRecv = true; - - removeChannel(c.localID); - - c.notifyAll(); - } - - log.debug("Got SSH_MSG_CHANNEL_CLOSE (channel " + id + ")"); - } - - public void msgChannelSuccess(byte[] msg, int msglen) throws IOException - { - if (msglen != 5) - throw new IOException("SSH_MSG_CHANNEL_SUCCESS message has wrong size (" + msglen + ")"); - - int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff); - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_SUCCESS message for non-existent channel " + id); - - synchronized (c) - { - c.successCounter++; - c.notifyAll(); - } - - log.debug("Got SSH_MSG_CHANNEL_SUCCESS (channel " + id + ")"); - } - - public void msgChannelFailure(byte[] msg, int msglen) throws IOException - { - if (msglen != 5) - throw new IOException("SSH_MSG_CHANNEL_FAILURE message has wrong size (" + msglen + ")"); - - int id = ((msg[1] & 0xff) << 24) | ((msg[2] & 0xff) << 16) | ((msg[3] & 0xff) << 8) | (msg[4] & 0xff); - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_FAILURE message for non-existent channel " + id); - - synchronized (c) - { - c.failedCounter++; - c.notifyAll(); - } - - log.debug("Got SSH_MSG_CHANNEL_FAILURE (channel " + id + ")"); - } - - public void msgChannelOpenConfirmation(byte[] msg, int msglen) throws IOException - { - PacketChannelOpenConfirmation sm = new PacketChannelOpenConfirmation(msg, 0, msglen); - - Channel c = getChannel(sm.recipientChannelID); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION message for non-existent channel " - + sm.recipientChannelID); - - synchronized (c) - { - if (c.state != Channel.STATE_OPENING) - throw new IOException("Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION message for channel " - + sm.recipientChannelID); - - c.remoteID = sm.senderChannelID; - c.remoteWindow = sm.initialWindowSize & 0xFFFFffffL; /* convert UINT32 to long */ - c.remoteMaxPacketSize = sm.maxPacketSize; - c.state = Channel.STATE_OPEN; - c.notifyAll(); - } - - log.debug("Got SSH_MSG_CHANNEL_OPEN_CONFIRMATION (channel " + sm.recipientChannelID + " / remote: " - + sm.senderChannelID + ")"); - } - - public void msgChannelOpenFailure(byte[] msg, int msglen) throws IOException - { - if (msglen < 5) - throw new IOException("SSH_MSG_CHANNEL_OPEN_FAILURE message has wrong size (" + msglen + ")"); - - TypesReader tr = new TypesReader(msg, 0, msglen); - - tr.readByte(); // skip packet type - int id = tr.readUINT32(); /* sender channel */ - - Channel c = getChannel(id); - - if (c == null) - throw new IOException("Unexpected SSH_MSG_CHANNEL_OPEN_FAILURE message for non-existent channel " + id); - - int reasonCode = tr.readUINT32(); - String description = tr.readString("UTF-8"); - - String reasonCodeSymbolicName = null; - - switch (reasonCode) - { - case 1: - reasonCodeSymbolicName = "SSH_OPEN_ADMINISTRATIVELY_PROHIBITED"; - break; - case 2: - reasonCodeSymbolicName = "SSH_OPEN_CONNECT_FAILED"; - break; - case 3: - reasonCodeSymbolicName = "SSH_OPEN_UNKNOWN_CHANNEL_TYPE"; - break; - case 4: - reasonCodeSymbolicName = "SSH_OPEN_RESOURCE_SHORTAGE"; - break; - default: - reasonCodeSymbolicName = "UNKNOWN REASON CODE (" + reasonCode + ")"; - } - - StringBuilder descriptionBuffer = new StringBuilder(); - descriptionBuffer.append(description); - - for (int i = 0; i < descriptionBuffer.length(); i++) - { - char cc = descriptionBuffer.charAt(i); - - if ((cc >= 32) && (cc <= 126)) - continue; - descriptionBuffer.setCharAt(i, '\uFFFD'); - } - - synchronized (c) - { - c.EOF = true; - c.state = Channel.STATE_CLOSED; - c.setReasonClosed("The server refused to open the channel (" + reasonCodeSymbolicName + ", '" - + descriptionBuffer.toString() + "')"); - c.notifyAll(); - } - - log.debug("Got SSH_MSG_CHANNEL_OPEN_FAILURE (channel " + id + ")"); - } - - public void msgGlobalRequest(byte[] msg, int msglen) throws IOException - { - /* Currently we do not support any kind of global request */ - - TypesReader tr = new TypesReader(msg, 0, msglen); - - tr.readByte(); // skip packet type - String requestName = tr.readString(); - boolean wantReply = tr.readBoolean(); - - if (wantReply) - { - byte[] reply_failure = new byte[1]; - reply_failure[0] = Packets.SSH_MSG_REQUEST_FAILURE; - - tm.sendAsynchronousMessage(reply_failure); - } - - /* We do not clean up the requestName String - that is OK for debug */ - - log.debug("Got SSH_MSG_GLOBAL_REQUEST (" + requestName + ")"); - } - - public void msgGlobalSuccess() throws IOException - { - synchronized (channels) - { - globalSuccessCounter++; - channels.notifyAll(); - } - - log.debug("Got SSH_MSG_REQUEST_SUCCESS"); - } - - public void msgGlobalFailure() throws IOException - { - synchronized (channels) - { - globalFailedCounter++; - channels.notifyAll(); - } - - log.debug("Got SSH_MSG_REQUEST_FAILURE"); - } - - public void handleMessage(byte[] msg, int msglen) throws IOException - { - if (msg == null) - { - - log.debug("HandleMessage: got shutdown"); - - synchronized (listenerThreads) - { - for (IChannelWorkerThread lat : listenerThreads) - { - lat.stopWorking(); - } - listenerThreadsAllowed = false; - } - - synchronized (channels) - { - shutdown = true; - - for (Channel c : channels) - { - synchronized (c) - { - c.EOF = true; - c.state = Channel.STATE_CLOSED; - c.setReasonClosed("The connection is being shutdown"); - c.closeMessageRecv = true; /* - * You never know, perhaps - * we are waiting for a - * pending close message - * from the server... - */ - c.notifyAll(); - } - } - - channels.clear(); - channels.notifyAll(); /* Notify global response waiters */ - return; - } - } - - switch (msg[0]) - { - case Packets.SSH_MSG_CHANNEL_OPEN_CONFIRMATION: - msgChannelOpenConfirmation(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_WINDOW_ADJUST: - msgChannelWindowAdjust(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_DATA: - msgChannelData(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_EXTENDED_DATA: - msgChannelExtendedData(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_REQUEST: - msgChannelRequest(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_EOF: - msgChannelEOF(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_OPEN: - msgChannelOpen(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_CLOSE: - msgChannelClose(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_SUCCESS: - msgChannelSuccess(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_FAILURE: - msgChannelFailure(msg, msglen); - break; - case Packets.SSH_MSG_CHANNEL_OPEN_FAILURE: - msgChannelOpenFailure(msg, msglen); - break; - case Packets.SSH_MSG_GLOBAL_REQUEST: - msgGlobalRequest(msg, msglen); - break; - case Packets.SSH_MSG_REQUEST_SUCCESS: - msgGlobalSuccess(); - break; - case Packets.SSH_MSG_REQUEST_FAILURE: - msgGlobalFailure(); - break; - default: - throw new IOException("Cannot handle unknown channel message " + (msg[0] & 0xff)); - } - } -} diff --git a/third-party/ganymed/src/main/java/ch/ethz/ssh2/transport/TransportManager.java b/third-party/ganymed/src/main/java/ch/ethz/ssh2/transport/TransportManager.java deleted file mode 100644 index 963267082b..0000000000 --- a/third-party/ganymed/src/main/java/ch/ethz/ssh2/transport/TransportManager.java +++ /dev/null @@ -1,990 +0,0 @@ -/* - * Copyright (c) 2006-2013 Christian Plattner. All rights reserved. - * Please refer to the LICENSE.txt for licensing details. - */ - -package ch.ethz.ssh2.transport; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.security.SecureRandom; -import java.util.List; -import java.util.Vector; - -import ch.ethz.ssh2.ConnectionInfo; -import ch.ethz.ssh2.ConnectionMonitor; -import ch.ethz.ssh2.DHGexParameters; -import ch.ethz.ssh2.HTTPProxyData; -import ch.ethz.ssh2.HTTPProxyException; -import ch.ethz.ssh2.ProxyData; -import ch.ethz.ssh2.ServerHostKeyVerifier; -import ch.ethz.ssh2.crypto.Base64; -import ch.ethz.ssh2.crypto.CryptoWishList; -import ch.ethz.ssh2.crypto.cipher.BlockCipher; -import ch.ethz.ssh2.crypto.digest.MAC; -import ch.ethz.ssh2.log.Logger; -import ch.ethz.ssh2.packets.PacketDisconnect; -import ch.ethz.ssh2.packets.Packets; -import ch.ethz.ssh2.packets.TypesReader; -import ch.ethz.ssh2.server.ServerConnectionState; -import ch.ethz.ssh2.signature.DSAPrivateKey; -import ch.ethz.ssh2.signature.RSAPrivateKey; -import ch.ethz.ssh2.util.StringEncoder; -import ch.ethz.ssh2.util.Tokenizer; - -/* - * Yes, the "standard" is a big mess. On one side, the say that arbitary channel - * packets are allowed during kex exchange, on the other side we need to blindly - * ignore the next _packet_ if the KEX guess was wrong. Where do we know from that - * the next packet is not a channel data packet? Yes, we could check if it is in - * the KEX range. But the standard says nothing about this. The OpenSSH guys - * block local "normal" traffic during KEX. That's fine - however, they assume - * that the other side is doing the same. During re-key, if they receive traffic - * other than KEX, they become horribly irritated and kill the connection. Since - * we are very likely going to communicate with OpenSSH servers, we have to play - * the same game - even though we could do better. - * - * btw: having stdout and stderr on the same channel, with a shared window, is - * also a VERY good idea... =( - */ - -/** - * TransportManager. - * - * @author Christian Plattner - * @version $Id: TransportManager.java 47 2013-07-31 23:59:52Z cleondris@gmail.com $ - */ -public class TransportManager -{ - private static final Logger log = Logger.getLogger(TransportManager.class); - - private static class HandlerEntry - { - MessageHandler mh; - int low; - int high; - } - - private final List asynchronousQueue = new Vector(); - private Thread asynchronousThread = null; - private boolean asynchronousPending = false; - - class AsynchronousEntry - { - public byte[] msg; - public Runnable run; - - public AsynchronousEntry(byte[] msg, Runnable run) - { - this.msg = msg; - this.run = run; - } - } - - class AsynchronousWorker extends Thread - { - @Override - public void run() - { - while (true) - { - AsynchronousEntry item = null; - - synchronized (asynchronousQueue) - { - if (asynchronousQueue.size() == 0) - { - /* Only now we may reset the flag, since we are sure that all queued items - * have been sent (there is a slight delay between de-queuing and sending, - * this is why we need this flag! See code below. Sending takes place outside - * of this lock, this is why a test for size()==0 (from another thread) does not ensure - * that all messages have been sent. - */ - - asynchronousPending = false; - - /* Notify any senders that they can proceed, all async messages have been delivered */ - - asynchronousQueue.notifyAll(); - - /* After the queue is empty for about 2 seconds, stop this thread */ - - try - { - asynchronousQueue.wait(2000); - } - catch (InterruptedException ignore) - { - } - - if (asynchronousQueue.size() == 0) - { - asynchronousThread = null; - return; - } - } - - item = asynchronousQueue.remove(0); - } - - /* The following invocation may throw an IOException. - * There is no point in handling it - it simply means - * that the connection has a problem and we should stop - * sending asynchronously messages. We do not need to signal that - * we have exited (asynchronousThread = null): further - * messages in the queue cannot be sent by this or any - * other thread. - * Other threads will sooner or later (when receiving or - * sending the next message) get the same IOException and - * get to the same conclusion. - */ - - try - { - sendMessageImmediate(item.msg); - } - catch (IOException e) - { - return; - } - - if (item.run != null) - { - try - { - item.run.run(); - } - catch (Exception ignore) - { - } - - } - } - } - } - - private Socket sock = new Socket(); - - private final Object connectionSemaphore = new Object(); - - private boolean flagKexOngoing = false; - private boolean connectionClosed = false; - - private Throwable reasonClosedCause = null; - - private TransportConnection tc; - private KexManager km; - - private final List messageHandlers = new Vector(); - - private Thread receiveThread; - - private List connectionMonitors = new Vector(); - private boolean monitorsWereInformed = false; - - /** - * There were reports that there are JDKs which use - * the resolver even though one supplies a dotted IP - * address in the Socket constructor. That is why we - * try to generate the InetAdress "by hand". - * - * @param host - * @return the InetAddress - * @throws UnknownHostException - */ - private static InetAddress createInetAddress(String host) throws UnknownHostException - { - /* Check if it is a dotted IP4 address */ - - InetAddress addr = parseIPv4Address(host); - - if (addr != null) - { - return addr; - } - - return InetAddress.getByName(host); - } - - private static InetAddress parseIPv4Address(String host) throws UnknownHostException - { - if (host == null) - { - return null; - } - - String[] quad = Tokenizer.parseTokens(host, '.'); - - if ((quad == null) || (quad.length != 4)) - { - return null; - } - - byte[] addr = new byte[4]; - - for (int i = 0; i < 4; i++) - { - int part = 0; - - if ((quad[i].length() == 0) || (quad[i].length() > 3)) - { - return null; - } - - for (int k = 0; k < quad[i].length(); k++) - { - char c = quad[i].charAt(k); - - /* No, Character.isDigit is not the same */ - if ((c < '0') || (c > '9')) - { - return null; - } - - part = part * 10 + (c - '0'); - } - - if (part > 255) /* 300.1.2.3 is invalid =) */ - { - return null; - } - - addr[i] = (byte) part; - } - - return InetAddress.getByAddress(host, addr); - } - - public int getPacketOverheadEstimate() - { - return tc.getPacketOverheadEstimate(); - } - - public void setTcpNoDelay(boolean state) throws IOException - { - sock.setTcpNoDelay(state); - } - - public void setSoTimeout(int timeout) throws IOException - { - sock.setSoTimeout(timeout); - } - - public ConnectionInfo getConnectionInfo(int kexNumber) throws IOException - { - return km.getOrWaitForConnectionInfo(kexNumber); - } - - public Throwable getReasonClosedCause() - { - synchronized (connectionSemaphore) - { - return reasonClosedCause; - } - } - - public byte[] getSessionIdentifier() - { - return km.sessionId; - } - - public void close(Throwable cause, boolean useDisconnectPacket) - { - if (useDisconnectPacket == false) - { - /* OK, hard shutdown - do not aquire the semaphore, - * perhaps somebody is inside (and waits until the remote - * side is ready to accept new data). */ - - try - { - sock.close(); - } - catch (IOException ignore) - { - } - - /* OK, whoever tried to send data, should now agree that - * there is no point in further waiting =) - * It is safe now to aquire the semaphore. - */ - } - - synchronized (connectionSemaphore) - { - if (connectionClosed == false) - { - if (useDisconnectPacket == true) - { - try - { - byte[] msg = new PacketDisconnect(Packets.SSH_DISCONNECT_BY_APPLICATION, cause.getMessage(), "") - .getPayload(); - if (tc != null) - { - tc.sendMessage(msg); - } - } - catch (IOException ignore) - { - } - - try - { - sock.close(); - } - catch (IOException ignore) - { - } - } - - connectionClosed = true; - reasonClosedCause = cause; /* may be null */ - } - connectionSemaphore.notifyAll(); - } - - /* No check if we need to inform the monitors */ - - List monitors = new Vector(); - - synchronized (this) - { - /* Short term lock to protect "connectionMonitors" - * and "monitorsWereInformed" - * (they may be modified concurrently) - */ - - if (monitorsWereInformed == false) - { - monitorsWereInformed = true; - monitors.addAll(connectionMonitors); - } - } - - for (ConnectionMonitor cmon : monitors) - { - try - { - cmon.connectionLost(reasonClosedCause); - } - catch (Exception ignore) - { - } - } - } - - private static Socket establishConnection(String hostname, int port, ProxyData proxyData, int connectTimeout) - throws IOException - { - /* See the comment for createInetAddress() */ - - if (proxyData == null) - { - InetAddress addr = createInetAddress(hostname); - Socket s = new Socket(); - s.connect(new InetSocketAddress(addr, port), connectTimeout); - return s; - } - - if (proxyData instanceof HTTPProxyData) - { - HTTPProxyData pd = (HTTPProxyData) proxyData; - - /* At the moment, we only support HTTP proxies */ - - InetAddress addr = createInetAddress(pd.proxyHost); - Socket s = new Socket(); - s.connect(new InetSocketAddress(addr, pd.proxyPort), connectTimeout); - - /* OK, now tell the proxy where we actually want to connect to */ - - StringBuilder sb = new StringBuilder(); - - sb.append("CONNECT "); - sb.append(hostname); - sb.append(':'); - sb.append(port); - sb.append(" HTTP/1.0\r\n"); - - if ((pd.proxyUser != null) && (pd.proxyPass != null)) - { - String credentials = pd.proxyUser + ":" + pd.proxyPass; - char[] encoded = Base64.encode(StringEncoder.GetBytes(credentials)); - sb.append("Proxy-Authorization: Basic "); - sb.append(encoded); - sb.append("\r\n"); - } - - if (pd.requestHeaderLines != null) - { - for (int i = 0; i < pd.requestHeaderLines.length; i++) - { - if (pd.requestHeaderLines[i] != null) - { - sb.append(pd.requestHeaderLines[i]); - sb.append("\r\n"); - } - } - } - - sb.append("\r\n"); - - OutputStream out = s.getOutputStream(); - - out.write(StringEncoder.GetBytes(sb.toString())); - out.flush(); - - /* Now parse the HTTP response */ - - byte[] buffer = new byte[1024]; - InputStream in = s.getInputStream(); - - int len = ClientServerHello.readLineRN(in, buffer); - - String httpReponse = StringEncoder.GetString(buffer, 0, len); - - if (httpReponse.startsWith("HTTP/") == false) - { - throw new IOException("The proxy did not send back a valid HTTP response."); - } - - /* "HTTP/1.X XYZ X" => 14 characters minimum */ - - if ((httpReponse.length() < 14) || (httpReponse.charAt(8) != ' ') || (httpReponse.charAt(12) != ' ')) - { - throw new IOException("The proxy did not send back a valid HTTP response."); - } - - int errorCode = 0; - - try - { - errorCode = Integer.parseInt(httpReponse.substring(9, 12)); - } - catch (NumberFormatException ignore) - { - throw new IOException("The proxy did not send back a valid HTTP response."); - } - - if ((errorCode < 0) || (errorCode > 999)) - { - throw new IOException("The proxy did not send back a valid HTTP response."); - } - - if (errorCode != 200) - { - throw new HTTPProxyException(httpReponse.substring(13), errorCode); - } - - /* OK, read until empty line */ - - while (true) - { - len = ClientServerHello.readLineRN(in, buffer); - if (len == 0) - { - break; - } - } - return s; - } - - throw new IOException("Unsupported ProxyData"); - } - - private void startReceiver() throws IOException - { - receiveThread = new Thread(new Runnable() - { - public void run() - { - try - { - receiveLoop(); - } - catch (Exception e) - { - close(e, false); - - log.warning("Receive thread: error in receiveLoop: " + e.getMessage()); - } - - if (log.isDebugEnabled()) - { - log.debug("Receive thread: back from receiveLoop"); - } - - /* Tell all handlers that it is time to say goodbye */ - - if (km != null) - { - try - { - km.handleMessage(null, 0); - } - catch (IOException ignored) - { - } - } - - for (HandlerEntry he : messageHandlers) - { - try - { - he.mh.handleMessage(null, 0); - } - catch (Exception ignore) - { - } - } - } - }); - - receiveThread.setDaemon(true); - receiveThread.start(); - } - - public void clientInit(Socket socket, String softwareversion, CryptoWishList cwl, - ServerHostKeyVerifier verifier, DHGexParameters dhgex, SecureRandom rnd) throws IOException - { - /* First, establish the TCP connection to the SSH-2 server */ - - sock = socket; - - /* Parse the server line and say hello - important: this information is later needed for the - * key exchange (to stop man-in-the-middle attacks) - that is why we wrap it into an object - * for later use. - */ - - ClientServerHello csh = ClientServerHello.clientHello(softwareversion, sock.getInputStream(), - sock.getOutputStream()); - - tc = new TransportConnection(sock.getInputStream(), sock.getOutputStream(), rnd); - String hostname = sock.getInetAddress().getHostName(); - int port = sock.getPort(); - - km = new ClientKexManager(this, csh, cwl, hostname, port, verifier, rnd); - km.initiateKEX(cwl, dhgex, null, null); - - startReceiver(); - } - - public void clientInit(String hostname, int port, String softwareversion, CryptoWishList cwl, - ServerHostKeyVerifier verifier, DHGexParameters dhgex, int connectTimeout, SecureRandom rnd, - ProxyData proxyData) throws IOException - { - /* First, establish the TCP connection to the SSH-2 server */ - - sock = establishConnection(hostname, port, proxyData, connectTimeout); - - /* Parse the server line and say hello - important: this information is later needed for the - * key exchange (to stop man-in-the-middle attacks) - that is why we wrap it into an object - * for later use. - */ - - ClientServerHello csh = ClientServerHello.clientHello(softwareversion, sock.getInputStream(), - sock.getOutputStream()); - - tc = new TransportConnection(sock.getInputStream(), sock.getOutputStream(), rnd); - - km = new ClientKexManager(this, csh, cwl, hostname, port, verifier, rnd); - km.initiateKEX(cwl, dhgex, null, null); - - startReceiver(); - } - - public void serverInit(ServerConnectionState state) throws IOException - { - /* TCP connection is already established */ - - this.sock = state.s; - - /* Parse the client line and say hello - important: this information is later needed for the - * key exchange (to stop man-in-the-middle attacks) - that is why we wrap it into an object - * for later use. - */ - - state.csh = ClientServerHello.serverHello(state.softwareversion, sock.getInputStream(), sock.getOutputStream()); - - tc = new TransportConnection(sock.getInputStream(), sock.getOutputStream(), state.generator); - - km = new ServerKexManager(state); - km.initiateKEX(state.next_cryptoWishList, null, state.next_dsa_key, state.next_rsa_key); - - startReceiver(); - } - - public void registerMessageHandler(MessageHandler mh, int low, int high) - { - HandlerEntry he = new HandlerEntry(); - he.mh = mh; - he.low = low; - he.high = high; - - synchronized (messageHandlers) - { - messageHandlers.add(he); - } - } - - public void removeMessageHandler(MessageHandler mh, int low, int high) - { - synchronized (messageHandlers) - { - for (int i = 0; i < messageHandlers.size(); i++) - { - HandlerEntry he = messageHandlers.get(i); - if ((he.mh == mh) && (he.low == low) && (he.high == high)) - { - messageHandlers.remove(i); - break; - } - } - } - } - - public void sendKexMessage(byte[] msg) throws IOException - { - synchronized (connectionSemaphore) - { - if (connectionClosed) - { - throw (IOException) new IOException("Sorry, this connection is closed.").initCause(reasonClosedCause); - } - - flagKexOngoing = true; - - try - { - tc.sendMessage(msg); - } - catch (IOException e) - { - close(e, false); - throw e; - } - } - } - - public void kexFinished() throws IOException - { - synchronized (connectionSemaphore) - { - flagKexOngoing = false; - connectionSemaphore.notifyAll(); - } - } - - /** - * - * @param cwl - * @param dhgex - * @param dsa may be null if this is a client connection - * @param rsa may be null if this is a client connection - * @throws IOException - */ - public void forceKeyExchange(CryptoWishList cwl, DHGexParameters dhgex, DSAPrivateKey dsa, RSAPrivateKey rsa) - throws IOException - { - synchronized (connectionSemaphore) - { - if (connectionClosed) - /* Inform the caller that there is no point in triggering a new kex */ - throw (IOException) new IOException("Sorry, this connection is closed.").initCause(reasonClosedCause); - } - - km.initiateKEX(cwl, dhgex, dsa, rsa); - } - - public void changeRecvCipher(BlockCipher bc, MAC mac) - { - tc.changeRecvCipher(bc, mac); - } - - public void changeSendCipher(BlockCipher bc, MAC mac) - { - tc.changeSendCipher(bc, mac); - } - - public void sendAsynchronousMessage(byte[] msg) throws IOException - { - sendAsynchronousMessage(msg, null); - } - - public void sendAsynchronousMessage(byte[] msg, Runnable run) throws IOException - { - synchronized (asynchronousQueue) - { - asynchronousQueue.add(new AsynchronousEntry(msg, run)); - asynchronousPending = true; - - /* This limit should be flexible enough. We need this, otherwise the peer - * can flood us with global requests (and other stuff where we have to reply - * with an asynchronous message) and (if the server just sends data and does not - * read what we send) this will probably put us in a low memory situation - * (our send queue would grow and grow and...) */ - - if (asynchronousQueue.size() > 100) - { - throw new IOException("Error: the peer is not consuming our asynchronous replies."); - } - - /* Check if we have an asynchronous sending thread */ - - if (asynchronousThread == null) - { - asynchronousThread = new AsynchronousWorker(); - asynchronousThread.setDaemon(true); - asynchronousThread.start(); - - /* The thread will stop after 2 seconds of inactivity (i.e., empty queue) */ - } - - asynchronousQueue.notifyAll(); - } - } - - public void setConnectionMonitors(List monitors) - { - synchronized (this) - { - connectionMonitors = new Vector(); - connectionMonitors.addAll(monitors); - } - } - - /** - * True if no response message expected. - */ - private boolean idle; - - /** - * Send a message but ensure that all queued messages are being sent first. - * - * @param msg - * @throws IOException - */ - public void sendMessage(byte[] msg) throws IOException - { - synchronized (asynchronousQueue) - { - while (asynchronousPending) - { - try - { - asynchronousQueue.wait(1000); - } - catch (InterruptedException e) - { - } - } - } - - sendMessageImmediate(msg); - } - - /** - * Send message, ignore queued async messages that have not been delivered yet. - * Will be called directly from the asynchronousThread thread. - * - * @param msg - * @throws IOException - */ - public void sendMessageImmediate(byte[] msg) throws IOException - { - if (Thread.currentThread() == receiveThread) - { - throw new IOException("Assertion error: sendMessage may never be invoked by the receiver thread!"); - } - - boolean wasInterrupted = false; - - try - { - synchronized (connectionSemaphore) - { - while (true) - { - if (connectionClosed) - { - throw (IOException) new IOException("Sorry, this connection is closed.") - .initCause(reasonClosedCause); - } - - if (flagKexOngoing == false) - { - break; - } - - try - { - connectionSemaphore.wait(); - } - catch (InterruptedException e) - { - wasInterrupted = true; - } - } - - try - { - tc.sendMessage(msg); - idle = false; - } - catch (IOException e) - { - close(e, false); - throw e; - } - } - } - finally - { - if (wasInterrupted) - Thread.currentThread().interrupt(); - } - } - - public void receiveLoop() throws IOException - { - byte[] msg = new byte[35000]; - - while (true) - { - int msglen; - try - { - msglen = tc.receiveMessage(msg, 0, msg.length); - } - catch (SocketTimeoutException e) - { - // Timeout in read - if (idle) - { - log.debug("Ignoring socket timeout"); - continue; - } - throw e; - } - idle = true; - - int type = msg[0] & 0xff; - - if (type == Packets.SSH_MSG_IGNORE) - { - continue; - } - - if (type == Packets.SSH_MSG_DEBUG) - { - if (log.isDebugEnabled()) - { - TypesReader tr = new TypesReader(msg, 0, msglen); - tr.readByte(); - tr.readBoolean(); - StringBuilder debugMessageBuffer = new StringBuilder(); - debugMessageBuffer.append(tr.readString("UTF-8")); - - for (int i = 0; i < debugMessageBuffer.length(); i++) - { - char c = debugMessageBuffer.charAt(i); - - if ((c >= 32) && (c <= 126)) - { - continue; - } - debugMessageBuffer.setCharAt(i, '\uFFFD'); - } - - log.debug("DEBUG Message from remote: '" + debugMessageBuffer.toString() + "'"); - } - continue; - } - - if (type == Packets.SSH_MSG_UNIMPLEMENTED) - { - throw new IOException("Peer sent UNIMPLEMENTED message, that should not happen."); - } - - if (type == Packets.SSH_MSG_DISCONNECT) - { - TypesReader tr = new TypesReader(msg, 0, msglen); - tr.readByte(); - int reason_code = tr.readUINT32(); - StringBuilder reasonBuffer = new StringBuilder(); - reasonBuffer.append(tr.readString("UTF-8")); - - /* - * Do not get fooled by servers that send abnormal long error - * messages - */ - - if (reasonBuffer.length() > 255) - { - reasonBuffer.setLength(255); - reasonBuffer.setCharAt(254, '.'); - reasonBuffer.setCharAt(253, '.'); - reasonBuffer.setCharAt(252, '.'); - } - - /* - * Also, check that the server did not send characters that may - * screw up the receiver -> restrict to reasonable US-ASCII - * subset -> "printable characters" (ASCII 32 - 126). Replace - * all others with 0xFFFD (UNICODE replacement character). - */ - - for (int i = 0; i < reasonBuffer.length(); i++) - { - char c = reasonBuffer.charAt(i); - - if ((c >= 32) && (c <= 126)) - { - continue; - } - reasonBuffer.setCharAt(i, '\uFFFD'); - } - - throw new IOException("Peer sent DISCONNECT message (reason code " + reason_code + "): " - + reasonBuffer.toString()); - } - - /* - * Is it a KEX Packet? - */ - - if ((type == Packets.SSH_MSG_KEXINIT) || (type == Packets.SSH_MSG_NEWKEYS) - || ((type >= 30) && (type <= 49))) - { - km.handleMessage(msg, msglen); - continue; - } - - MessageHandler mh = null; - - for (int i = 0; i < messageHandlers.size(); i++) - { - HandlerEntry he = messageHandlers.get(i); - if ((he.low <= type) && (type <= he.high)) - { - mh = he.mh; - break; - } - } - - if (mh == null) - { - throw new IOException("Unexpected SSH message (type " + type + ")"); - } - - mh.handleMessage(msg, msglen); - } - } -} diff --git a/third-party/jersey-servlet/pom.xml b/third-party/jersey-servlet/pom.xml deleted file mode 100644 index 27d503e898..0000000000 --- a/third-party/jersey-servlet/pom.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - - - org.opendaylight.controller - commons.thirdparty - 1.2.0-SNAPSHOT - ../commons/thirdparty - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - HEAD - - - 4.0.0 - org.opendaylight.controller.thirdparty - com.sun.jersey.jersey-servlet - 1.19.0-SNAPSHOT - bundle - - - - org.apache.felix - maven-bundle-plugin - 2.3.6 - true - - - *;scope=!provided;type=!pom;inline=false - false - - com.sun.jersey.api.core.servlet, - com.sun.jersey.spi.container.servlet, - com.sun.jersey.spi.scanning.servlet, - com.sun.jersey.server.impl.container.servlet - - - com.sun.jersey.api.container, - com.sun.jersey.api.core, - com.sun.jersey.api.model, - com.sun.jersey.api.representation, - com.sun.jersey.api.uri, - com.sun.jersey.api.view, - com.sun.jersey.core.header, - com.sun.jersey.core.reflection, - com.sun.jersey.core.spi.component, - com.sun.jersey.core.spi.component.ioc, - com.sun.jersey.core.spi.scanning, - com.sun.jersey.core.util, - com.sun.jersey.server.impl, - com.sun.jersey.server.impl.application, - com.sun.jersey.server.impl.inject, - com.sun.jersey.server.impl.monitoring, - com.sun.jersey.server.probes, - com.sun.jersey.server.spi.component, - com.sun.jersey.spi, - com.sun.jersey.spi.container, - com.sun.jersey.spi.dispatch, - com.sun.jersey.spi.inject, - com.sun.jersey.spi.service, - com.sun.jersey.spi.template, - javax.naming, - javax.ws.rs, - javax.ws.rs.core, - javax.ws.rs.ext, - *;resolution:=optional - - - ${project.basedir}/META-INF - - - - - - - - com.sun.jersey - jersey-servlet - 1.17 - - - equinoxSDK381 - javax.servlet - 3.0.0.v201112011016 - provided - - - diff --git a/third-party/net.sf.jung2/pom.xml b/third-party/net.sf.jung2/pom.xml deleted file mode 100644 index 63455dc8be..0000000000 --- a/third-party/net.sf.jung2/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - org.opendaylight.controller - commons.thirdparty - 1.2.0-SNAPSHOT - ../commons/thirdparty - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - HEAD - - - 4.0.0 - org.opendaylight.controller.thirdparty - net.sf.jung2 - 2.1.0-SNAPSHOT - bundle - - - - org.apache.felix - maven-bundle-plugin - 2.3.6 - true - - - *;scope=compile|runtime;type=!pom;inline=false - false - - org.apache.commons*, - edu.uci.ics.jung.algorithms.blockmodel, - edu.uci.ics.jung.algorithms.cluster, - edu.uci.ics.jung.algorithms.filters, - edu.uci.ics.jung.algorithms.flows, - edu.uci.ics.jung.algorithms.generators, - edu.uci.ics.jung.algorithms.generators.random, - edu.uci.ics.jung.algorithms.layout, - edu.uci.ics.jung.algorithms.layout.util, - edu.uci.ics.jung.algorithms.metrics, - edu.uci.ics.jung.algorithms.scoring, - edu.uci.ics.jung.algorithms.scoring.util, - edu.uci.ics.jung.algorithms.shortestpath, - edu.uci.ics.jung.algorithms.transformation, - edu.uci.ics.jung.algorithms.util, - edu.uci.ics.jung.graph;-split-package:=merge-first, - edu.uci.ics.jung.graph.event, - edu.uci.ics.jung.graph.util;-split-package:=merge-first - - - !* - - - ${project.basedir}/META-INF - - - - - - - - net.sf.jung - jung-api - 2.0.1 - - - net.sf.jung - jung-graph-impl - 2.0.1 - - - net.sourceforge.collections - collections-generic - 4.01 - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/StructurallyEquivalent.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/StructurallyEquivalent.java deleted file mode 100644 index a9d457345e..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/StructurallyEquivalent.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2004, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * Created on Jan 28, 2004 - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.blockmodel; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.CollectionUtils; -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - -/** - * Identifies sets of structurally equivalent vertices in a graph. Vertices - * i and j are structurally equivalent iff the set of i's - * neighbors is identical to the set of j's neighbors, with the - * exception of i and j themselves. This algorithm finds all - * sets of equivalent vertices in O(V^2) time. - * - *

      You can extend this class to have a different definition of equivalence (by - * overriding isStructurallyEquivalent), and may give it hints for - * accelerating the process by overriding canPossiblyCompare. - * (For example, in a bipartite graph, canPossiblyCompare may - * return false for vertices in - * different partitions. This function should be fast.) - * - * @author Danyel Fisher - */ -public class StructurallyEquivalent implements Transformer, VertexPartition> -{ - public VertexPartition transform(Graph g) - { - Set> vertex_pairs = getEquivalentPairs(g); - - Set> rv = new HashSet>(); - Map> intermediate = new HashMap>(); - for (Pair p : vertex_pairs) - { - Set res = intermediate.get(p.getFirst()); - if (res == null) - res = intermediate.get(p.getSecond()); - if (res == null) // we haven't seen this one before - res = new HashSet(); - res.add(p.getFirst()); - res.add(p.getSecond()); - intermediate.put(p.getFirst(), res); - intermediate.put(p.getSecond(), res); - } - rv.addAll(intermediate.values()); - - // pick up the vertices which don't appear in intermediate; they are - // singletons (equivalence classes of size 1) - Collection singletons = CollectionUtils.subtract(g.getVertices(), - intermediate.keySet()); - for (V v : singletons) - { - Set v_set = Collections.singleton(v); - intermediate.put(v, v_set); - rv.add(v_set); - } - - return new VertexPartition(g, intermediate, rv); - } - - /** - * For each vertex pair v, v1 in G, checks whether v and v1 are fully - * equivalent: meaning that they connect to the exact same vertices. (Is - * this regular equivalence, or whathaveyou?) - * - * Returns a Set of Pairs of vertices, where all the vertices in the inner - * Pairs are equivalent. - * - * @param g - */ - protected Set> getEquivalentPairs(Graph g) { - - Set> rv = new HashSet>(); - Set alreadyEquivalent = new HashSet(); - - List l = new ArrayList(g.getVertices()); - - for (V v1 : l) - { - if (alreadyEquivalent.contains(v1)) - continue; - - for (Iterator iterator = l.listIterator(l.indexOf(v1) + 1); iterator.hasNext();) { - V v2 = iterator.next(); - - if (alreadyEquivalent.contains(v2)) - continue; - - if (!canPossiblyCompare(v1, v2)) - continue; - - if (isStructurallyEquivalent(g, v1, v2)) { - Pair p = new Pair(v1, v2); - alreadyEquivalent.add(v2); - rv.add(p); - } - } - } - - return rv; - } - - /** - * Checks whether a pair of vertices are structurally equivalent. - * Specifically, whether v1's predecessors are equal to v2's predecessors, - * and same for successors. - * - * @param g the graph in which the structural equivalence comparison is to take place - * @param v1 the vertex to check for structural equivalence to v2 - * @param v2 the vertex to check for structural equivalence to v1 - */ - protected boolean isStructurallyEquivalent(Graph g, V v1, V v2) { - - if( g.degree(v1) != g.degree(v2)) { - return false; - } - - Set n1 = new HashSet(g.getPredecessors(v1)); - n1.remove(v2); - n1.remove(v1); - Set n2 = new HashSet(g.getPredecessors(v2)); - n2.remove(v1); - n2.remove(v2); - - Set o1 = new HashSet(g.getSuccessors(v1)); - Set o2 = new HashSet(g.getSuccessors(v2)); - o1.remove(v1); - o1.remove(v2); - o2.remove(v1); - o2.remove(v2); - - // this neglects self-loops and directed edges from 1 to other - boolean b = (n1.equals(n2) && o1.equals(o2)); - if (!b) - return b; - - // if there's a directed edge v1->v2 then there's a directed edge v2->v1 - b &= ( g.isSuccessor(v1, v2) == g.isSuccessor(v2, v1)); - - // self-loop check - b &= ( g.isSuccessor(v1, v1) == g.isSuccessor(v2, v2)); - - return b; - - } - - /** - * This is a space for optimizations. For example, for a bipartite graph, - * vertices from different partitions cannot possibly be compared. - * - * @param v1 - * @param v2 - */ - protected boolean canPossiblyCompare(V v1, V v2) { - return true; - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/VertexPartition.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/VertexPartition.java deleted file mode 100644 index b5ec5831ba..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/VertexPartition.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -/* - * Created on Feb 3, 2004 - */ -package edu.uci.ics.jung.algorithms.blockmodel; - -import java.util.*; - -import edu.uci.ics.jung.graph.Graph; - - -/** - * Maintains information about a vertex partition of a graph. - * This can be built from a map from vertices to vertex sets - * or from a collection of (disjoint) vertex sets, - * such as those created by various clustering methods. - */ -public class VertexPartition -{ - private Map> vertex_partition_map; - private Collection> vertex_sets; - private Graph graph; - - /** - * Creates an instance based on the specified graph and mapping from vertices - * to vertex sets, and generates a set of partitions based on this mapping. - * @param g the graph over which the vertex partition is defined - * @param partition_map the mapping from vertices to vertex sets (partitions) - */ - public VertexPartition(Graph g, Map> partition_map) - { - this.vertex_partition_map = Collections.unmodifiableMap(partition_map); - this.graph = g; - } - - /** - * Creates an instance based on the specified graph, vertex-set mapping, - * and set of disjoint vertex sets. The vertex-set mapping and vertex - * partitions must be consistent; that is, the mapping must reflect the - * division of vertices into partitions, and each vertex must appear in - * exactly one partition. - * @param g the graph over which the vertex partition is defined - * @param partition_map the mapping from vertices to vertex sets (partitions) - * @param vertex_sets the set of disjoint vertex sets - */ - public VertexPartition(Graph g, Map> partition_map, - Collection> vertex_sets) - { - this.vertex_partition_map = Collections.unmodifiableMap(partition_map); - this.vertex_sets = vertex_sets; - this.graph = g; - } - - /** - * Creates an instance based on the specified graph and set of disjoint vertex sets, - * and generates a vertex-to-partition map based on these sets. - * @param g the graph over which the vertex partition is defined - * @param vertex_sets the set of disjoint vertex sets - */ - public VertexPartition(Graph g, Collection> vertex_sets) - { - this.vertex_sets = vertex_sets; - this.graph = g; - } - - /** - * Returns the graph on which the partition is defined. - * @return the graph on which the partition is defined - */ - public Graph getGraph() - { - return graph; - } - - /** - * Returns a map from each vertex in the input graph to its partition. - * This map is generated if it does not already exist. - * @return a map from each vertex in the input graph to a vertex set - */ - public Map> getVertexToPartitionMap() - { - if (vertex_partition_map == null) - { - this.vertex_partition_map = new HashMap>(); - for (Set set : this.vertex_sets) - for (V v : set) - this.vertex_partition_map.put(v, set); - } - return vertex_partition_map; - } - - /** - * Returns a collection of vertex sets, where each vertex in the - * input graph is in exactly one set. - * This collection is generated based on the vertex-to-partition map - * if it does not already exist. - * @return a collection of vertex sets such that each vertex in the - * instance's graph is in exactly one set - */ - public Collection> getVertexPartitions() - { - if (vertex_sets == null) - { - this.vertex_sets = new HashSet>(); - this.vertex_sets.addAll(vertex_partition_map.values()); - } - return vertex_sets; - } - - /** - * Returns the number of partitions. - */ - public int numPartitions() - { - return vertex_sets.size(); - } - - @Override - public String toString() - { - return "Partitions: " + vertex_partition_map; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/package.html deleted file mode 100644 index d1cb06acae..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/blockmodel/package.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - -Support for establishing and maintaining graph element equivalence (such as in blockmodeling). -

      -In blockmodeling, groups of vertices are clustered together by similarity -(as if members of a "block" appearing on the diagonal of the graph's adjacency -matrix). -

      -This support currently includes: -

        -
      • VertexPartition: A class that maintains information on a -division of the vertices of a graph into disjoint sets. -
      • StructurallyEquivalent: An algorithm that finds sets of vertices that are -structurally equivalent. -
      - -

      - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/BicomponentClusterer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/BicomponentClusterer.java deleted file mode 100644 index aa697c7dbb..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/BicomponentClusterer.java +++ /dev/null @@ -1,162 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.cluster; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.UndirectedGraph; - -/** - * Finds all biconnected components (bicomponents) of an undirected graph. - * A graph is a biconnected component if - * at least 2 vertices must be removed in order to disconnect the graph. (Graphs - * consisting of one vertex, or of two connected vertices, are also biconnected.) Biconnected - * components of three or more vertices have the property that every pair of vertices in the component - * are connected by two or more vertex-disjoint paths. - *

      - * Running time: O(|V| + |E|) where |V| is the number of vertices and |E| is the number of edges - * @see "Depth first search and linear graph algorithms by R. E. Tarjan (1972), SIAM J. Comp." - * - * @author Joshua O'Madadhain - */ -public class BicomponentClusterer implements Transformer, Set>> -{ - protected Map dfs_num; - protected Map high; - protected Map parents; - protected Stack stack; - protected int converse_depth; - - /** - * Constructs a new bicomponent finder - */ - public BicomponentClusterer() { - } - - /** - * Extracts the bicomponents from the graph. - * @param theGraph the graph whose bicomponents are to be extracted - * @return the ClusterSet of bicomponents - */ - public Set> transform(UndirectedGraph theGraph) - { - Set> bicomponents = new LinkedHashSet>(); - - if (theGraph.getVertices().isEmpty()) - return bicomponents; - - // initialize DFS number for each vertex to 0 - dfs_num = new HashMap(); - for (V v : theGraph.getVertices()) - { - dfs_num.put(v, 0); - } - - for (V v : theGraph.getVertices()) - { - if (dfs_num.get(v).intValue() == 0) // if we haven't hit this vertex yet... - { - high = new HashMap(); - stack = new Stack(); - parents = new HashMap(); - converse_depth = theGraph.getVertexCount(); - // find the biconnected components for this subgraph, starting from v - findBiconnectedComponents(theGraph, v, bicomponents); - - // if we only visited one vertex, this method won't have - // ID'd it as a biconnected component, so mark it as one - if (theGraph.getVertexCount() - converse_depth == 1) - { - Set s = new HashSet(); - s.add(v); - bicomponents.add(s); - } - } - } - - return bicomponents; - } - - /** - *

      Stores, in bicomponents, all the biconnected - * components that are reachable from v.

      - * - *

      The algorithm basically proceeds as follows: do a depth-first - * traversal starting from v, marking each vertex with - * a value that indicates the order in which it was encountered (dfs_num), - * and with - * a value that indicates the highest point in the DFS tree that is known - * to be reachable from this vertex using non-DFS edges (high). (Since it - * is measured on non-DFS edges, "high" tells you how far back in the DFS - * tree you can reach by two distinct paths, hence biconnectivity.) - * Each time a new vertex w is encountered, push the edge just traversed - * on a stack, and call this method recursively. If w.high is no greater than - * v.dfs_num, then the contents of the stack down to (v,w) is a - * biconnected component (and v is an articulation point, that is, a - * component boundary). In either case, set v.high to max(v.high, w.high), - * and continue. If w has already been encountered but is - * not v's parent, set v.high max(v.high, w.dfs_num) and continue. - * - *

      (In case anyone cares, the version of this algorithm on p. 224 of - * Udi Manber's "Introduction to Algorithms: A Creative Approach" seems to be - * wrong: the stack should be initialized outside this method, - * (v,w) should only be put on the stack if w hasn't been seen already, - * and there's no real benefit to putting v on the stack separately: just - * check for (v,w) on the stack rather than v. Had I known this, I could - * have saved myself a few days. JRTOM)

      - * - */ - protected void findBiconnectedComponents(UndirectedGraph g, V v, Set> bicomponents) - { - int v_dfs_num = converse_depth; - dfs_num.put(v, v_dfs_num); - converse_depth--; - high.put(v, v_dfs_num); - - for (V w : g.getNeighbors(v)) - { - int w_dfs_num = dfs_num.get(w).intValue();//get(w, dfs_num); - E vw = g.findEdge(v,w); - if (w_dfs_num == 0) // w hasn't yet been visited - { - parents.put(w, v); // v is w's parent in the DFS tree - stack.push(vw); - findBiconnectedComponents(g, w, bicomponents); - int w_high = high.get(w).intValue();//get(w, high); - if (w_high <= v_dfs_num) - { - // v disconnects w from the rest of the graph, - // i.e., v is an articulation point - // thus, everything between the top of the stack and - // v is part of a single biconnected component - Set bicomponent = new HashSet(); - E e; - do - { - e = stack.pop(); - bicomponent.addAll(g.getIncidentVertices(e)); - } - while (e != vw); - bicomponents.add(bicomponent); - } - high.put(v, Math.max(w_high, high.get(v).intValue())); - } - else if (w != parents.get(v)) // (v,w) is a back or a forward edge - high.put(v, Math.max(w_dfs_num, high.get(v).intValue())); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/EdgeBetweennessClusterer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/EdgeBetweennessClusterer.java deleted file mode 100644 index 59e4605e35..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/EdgeBetweennessClusterer.java +++ /dev/null @@ -1,109 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.cluster; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - - -/** - * An algorithm for computing clusters (community structure) in graphs based on edge betweenness. - * The betweenness of an edge is defined as the extent to which that edge lies along - * shortest paths between all pairs of nodes. - * - * This algorithm works by iteratively following the 2 step process: - *
        - *
      • Compute edge betweenness for all edges in current graph - *
      • Remove edge with highest betweenness - *
      - *

      - * Running time is: O(kmn) where k is the number of edges to remove, m is the total number of edges, and - * n is the total number of vertices. For very sparse graphs the running time is closer to O(kn^2) and for - * graphs with strong community structure, the complexity is even lower. - *

      - * This algorithm is a slight modification of the algorithm discussed below in that the number of edges - * to be removed is parameterized. - * @author Scott White - * @author Tom Nelson (converted to jung2) - * @see "Community structure in social and biological networks by Michelle Girvan and Mark Newman" - */ -public class EdgeBetweennessClusterer implements Transformer,Set>> { - private int mNumEdgesToRemove; - private Map> edges_removed; - - /** - * Constructs a new clusterer for the specified graph. - * @param numEdgesToRemove the number of edges to be progressively removed from the graph - */ - public EdgeBetweennessClusterer(int numEdgesToRemove) { - mNumEdgesToRemove = numEdgesToRemove; - edges_removed = new LinkedHashMap>(); - } - - /** - * Finds the set of clusters which have the strongest "community structure". - * The more edges removed the smaller and more cohesive the clusters. - * @param graph the graph - */ - public Set> transform(Graph graph) { - - if (mNumEdgesToRemove < 0 || mNumEdgesToRemove > graph.getEdgeCount()) { - throw new IllegalArgumentException("Invalid number of edges passed in."); - } - - edges_removed.clear(); - - for (int k=0;k bc = new BetweennessCentrality(graph); - E to_remove = null; - double score = 0; - for (E e : graph.getEdges()) - if (bc.getEdgeScore(e) > score) - { - to_remove = e; - score = bc.getEdgeScore(e); - } - edges_removed.put(to_remove, graph.getEndpoints(to_remove)); - graph.removeEdge(to_remove); - } - - WeakComponentClusterer wcSearch = new WeakComponentClusterer(); - Set> clusterSet = wcSearch.transform(graph); - - for (Map.Entry> entry : edges_removed.entrySet()) - { - Pair endpoints = entry.getValue(); - graph.addEdge(entry.getKey(), endpoints.getFirst(), endpoints.getSecond()); - } - return clusterSet; - } - - /** - * Retrieves the list of all edges that were removed - * (assuming extract(...) was previously called). - * The edges returned - * are stored in order in which they were removed. - * - * @return the edges in the original graph - */ - public List getEdgesRemoved() - { - return new ArrayList(edges_removed.keySet()); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/VoltageClusterer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/VoltageClusterer.java deleted file mode 100644 index 859c06307c..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/VoltageClusterer.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright (c) 2004, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * - * Created on Aug 12, 2004 - */ -package edu.uci.ics.jung.algorithms.cluster; - -import edu.uci.ics.jung.algorithms.scoring.VoltageScorer; -import edu.uci.ics.jung.algorithms.util.DiscreteDistribution; -import edu.uci.ics.jung.algorithms.util.KMeansClusterer; -import edu.uci.ics.jung.algorithms.util.KMeansClusterer.NotEnoughClustersException; -import edu.uci.ics.jung.graph.Graph; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -/** - *

      Clusters vertices of a Graph based on their ranks as - * calculated by VoltageScorer. This algorithm is based on, - * but not identical with, the method described in the paper below. - * The primary difference is that Wu and Huberman assume a priori that the clusters - * are of approximately the same size, and therefore use a more complex - * method than k-means (which is used here) for determining cluster - * membership based on co-occurrence data.

      - * - *

      The algorithm proceeds as follows: - *

        - *
      • first, generate a set of candidate clusters as follows: - *
          - *
        • pick (widely separated) vertex pair, run VoltageScorer - *
        • group the vertices in two clusters according to their voltages - *
        • store resulting candidate clusters - *
        - *
      • second, generate k-1 clusters as follows: - *
          - *
        • pick a vertex v as a cluster 'seed' - *
          (Wu/Huberman: most frequent vertex in candidate clusters) - *
        • calculate co-occurrence over all candidate clusters of v with each other - * vertex - *
        • separate co-occurrence counts into high/low; - * high vertices constitute a cluster - *
        • remove v's vertices from candidate clusters; continue - *
        - *
      • finally, remaining unassigned vertices are assigned to the kth ("garbage") - * cluster. - *

      - * - *

      NOTE: Depending on how the co-occurrence data splits the data into - * clusters, the number of clusters returned by this algorithm may be less than the - * number of clusters requested. The number of clusters will never be more than - * the number requested, however.

      - * - * @author Joshua O'Madadhain - * @see "'Finding communities in linear time: a physics approach', Fang Wu and Bernardo Huberman, http://www.hpl.hp.com/research/idl/papers/linear/" - * @see VoltageScorer - * @see KMeansClusterer - */ -public class VoltageClusterer -{ - protected int num_candidates; - protected KMeansClusterer kmc; - protected Random rand; - protected Graph g; - - /** - * Creates an instance of a VoltageCluster with the specified parameters. - * These are mostly parameters that are passed directly to VoltageScorer - * and KMeansClusterer. - * - * @param num_candidates the number of candidate clusters to create - */ - public VoltageClusterer(Graph g, int num_candidates) - { - if (num_candidates < 1) - throw new IllegalArgumentException("must generate >=1 candidates"); - - this.num_candidates = num_candidates; - this.kmc = new KMeansClusterer(); - rand = new Random(); - this.g = g; - } - - protected void setRandomSeed(int random_seed) - { - rand = new Random(random_seed); - } - - /** - * Returns a community (cluster) centered around v. - * @param v the vertex whose community we wish to discover - */ - public Collection> getCommunity(V v) - { - return cluster_internal(v, 2); - } - - /** - * Clusters the vertices of g into - * num_clusters clusters, based on their connectivity. - * @param num_clusters the number of clusters to identify - */ - public Collection> cluster(int num_clusters) - { - return cluster_internal(null, num_clusters); - } - - /** - * Does the work of getCommunity and cluster. - * @param origin the vertex around which clustering is to be done - * @param num_clusters the (maximum) number of clusters to find - */ - protected Collection> cluster_internal(V origin, int num_clusters) - { - // generate candidate clusters - // repeat the following 'samples' times: - // * pick (widely separated) vertex pair, run VoltageScorer - // * use k-means to identify 2 communities in ranked graph - // * store resulting candidate communities - ArrayList v_array = new ArrayList(g.getVertices()); - - LinkedList> candidates = new LinkedList>(); - - for (int j = 0; j < num_candidates; j++) - { - V source; - if (origin == null) - source = v_array.get((int)(rand.nextDouble() * v_array.size())); - else - source = origin; - V target = null; - do - { - target = v_array.get((int)(rand.nextDouble() * v_array.size())); - } - while (source == target); - VoltageScorer vs = new VoltageScorer(g, source, target); - vs.evaluate(); - - Map voltage_ranks = new HashMap(); - for (V v : g.getVertices()) - voltage_ranks.put(v, new double[] {vs.getVertexScore(v)}); - -// addOneCandidateCluster(candidates, voltage_ranks); - addTwoCandidateClusters(candidates, voltage_ranks); - } - - // repeat the following k-1 times: - // * pick a vertex v as a cluster seed - // (Wu/Huberman: most frequent vertex in candidates) - // * calculate co-occurrence (in candidate clusters) - // of this vertex with all others - // * use k-means to separate co-occurrence counts into high/low; - // high vertices are a cluster - // * remove v's vertices from candidate clusters - - Collection> clusters = new LinkedList>(); - Set remaining = new HashSet(g.getVertices()); - - List seed_candidates = getSeedCandidates(candidates); - int seed_index = 0; - - for (int j = 0; j < (num_clusters - 1); j++) - { - if (remaining.isEmpty()) - break; - - V seed; - if (seed_index == 0 && origin != null) - seed = origin; - else - { - do { seed = seed_candidates.get(seed_index++); } - while (!remaining.contains(seed)); - } - - Map occur_counts = getObjectCounts(candidates, seed); - if (occur_counts.size() < 2) - break; - - // now that we have the counts, cluster them... - try - { - Collection> high_low = kmc.cluster(occur_counts, 2); - // ...get the cluster with the highest-valued centroid... - Iterator> h_iter = high_low.iterator(); - Map cluster1 = h_iter.next(); - Map cluster2 = h_iter.next(); - double[] centroid1 = DiscreteDistribution.mean(cluster1.values()); - double[] centroid2 = DiscreteDistribution.mean(cluster2.values()); - Set new_cluster; - if (centroid1[0] >= centroid2[0]) - new_cluster = cluster1.keySet(); - else - new_cluster = cluster2.keySet(); - - // ...remove the elements of new_cluster from each candidate... - for (Set cluster : candidates) - cluster.removeAll(new_cluster); - clusters.add(new_cluster); - remaining.removeAll(new_cluster); - } - catch (NotEnoughClustersException nece) - { - // all remaining vertices are in the same cluster - break; - } - } - - // identify remaining vertices (if any) as a 'garbage' cluster - if (!remaining.isEmpty()) - clusters.add(remaining); - - return clusters; - } - - /** - * Do k-means with three intervals and pick the - * smaller two clusters (presumed to be on the ends); this is closer to the Wu-Huberman method. - * @param candidates - * @param voltage_ranks - */ - protected void addTwoCandidateClusters(LinkedList> candidates, - Map voltage_ranks) - { - try - { - List> clusters = new ArrayList>(kmc.cluster(voltage_ranks, 3)); - boolean b01 = clusters.get(0).size() > clusters.get(1).size(); - boolean b02 = clusters.get(0).size() > clusters.get(2).size(); - boolean b12 = clusters.get(1).size() > clusters.get(2).size(); - if (b01 && b02) - { - candidates.add(clusters.get(1).keySet()); - candidates.add(clusters.get(2).keySet()); - } - else if (!b01 && b12) - { - candidates.add(clusters.get(0).keySet()); - candidates.add(clusters.get(2).keySet()); - } - else if (!b02 && !b12) - { - candidates.add(clusters.get(0).keySet()); - candidates.add(clusters.get(1).keySet()); - } - } - catch (NotEnoughClustersException e) - { - // no valid candidates, continue - } - } - - /** - * alternative to addTwoCandidateClusters(): cluster vertices by voltages into 2 clusters. - * We only consider the smaller of the two clusters returned - * by k-means to be a 'true' cluster candidate; the other is a garbage cluster. - * @param candidates - * @param voltage_ranks - */ - protected void addOneCandidateCluster(LinkedList> candidates, - Map voltage_ranks) - { - try - { - List> clusters; - clusters = new ArrayList>(kmc.cluster(voltage_ranks, 2)); - if (clusters.get(0).size() < clusters.get(1).size()) - candidates.add(clusters.get(0).keySet()); - else - candidates.add(clusters.get(1).keySet()); - } - catch (NotEnoughClustersException e) - { - // no valid candidates, continue - } - } - - /** - * Returns an array of cluster seeds, ranked in decreasing order - * of number of appearances in the specified collection of candidate - * clusters. - * @param candidates - */ - protected List getSeedCandidates(Collection> candidates) - { - final Map occur_counts = getObjectCounts(candidates, null); - - ArrayList occurrences = new ArrayList(occur_counts.keySet()); - Collections.sort(occurrences, new MapValueArrayComparator(occur_counts)); - - System.out.println("occurrences: "); - for (int i = 0; i < occurrences.size(); i++) - System.out.println(occur_counts.get(occurrences.get(i))[0]); - - return occurrences; - } - - protected Map getObjectCounts(Collection> candidates, V seed) - { - Map occur_counts = new HashMap(); - for (V v : g.getVertices()) - occur_counts.put(v, new double[]{0}); - - for (Set candidate : candidates) - { - if (seed == null) - System.out.println(candidate.size()); - if (seed == null || candidate.contains(seed)) - { - for (V element : candidate) - { - double[] count = occur_counts.get(element); - count[0]++; - } - } - } - - if (seed == null) - { - System.out.println("occur_counts size: " + occur_counts.size()); - for (V v : occur_counts.keySet()) - System.out.println(occur_counts.get(v)[0]); - } - - return occur_counts; - } - - protected class MapValueArrayComparator implements Comparator - { - private Map map; - - protected MapValueArrayComparator(Map map) - { - this.map = map; - } - - public int compare(V o1, V o2) - { - double[] count0 = map.get(o1); - double[] count1 = map.get(o2); - if (count0[0] < count1[0]) - return 1; - else if (count0[0] > count1[0]) - return -1; - return 0; - } - - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/WeakComponentClusterer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/WeakComponentClusterer.java deleted file mode 100644 index cb79a78448..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/WeakComponentClusterer.java +++ /dev/null @@ -1,73 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.cluster; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.collections15.Buffer; -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.buffer.UnboundedFifoBuffer; - -import edu.uci.ics.jung.graph.Graph; - - - -/** - * Finds all weak components in a graph as sets of vertex sets. A weak component is defined as - * a maximal subgraph in which all pairs of vertices in the subgraph are reachable from one - * another in the underlying undirected subgraph. - *

      This implementation identifies components as sets of vertex sets. - * To create the induced graphs from any or all of these vertex sets, - * see algorithms.filters.FilterUtils. - *

      - * Running time: O(|V| + |E|) where |V| is the number of vertices and |E| is the number of edges. - * @author Scott White - */ -public class WeakComponentClusterer implements Transformer, Set>> -{ - /** - * Extracts the weak components from a graph. - * @param graph the graph whose weak components are to be extracted - * @return the list of weak components - */ - public Set> transform(Graph graph) { - - Set> clusterSet = new HashSet>(); - - HashSet unvisitedVertices = new HashSet(graph.getVertices()); - - while (!unvisitedVertices.isEmpty()) { - Set cluster = new HashSet(); - V root = unvisitedVertices.iterator().next(); - unvisitedVertices.remove(root); - cluster.add(root); - - Buffer queue = new UnboundedFifoBuffer(); - queue.add(root); - - while (!queue.isEmpty()) { - V currentVertex = queue.remove(); - Collection neighbors = graph.getNeighbors(currentVertex); - - for(V neighbor : neighbors) { - if (unvisitedVertices.contains(neighbor)) { - queue.add(neighbor); - unvisitedVertices.remove(neighbor); - cluster.add(neighbor); - } - } - } - clusterSet.add(cluster); - } - return clusterSet; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/package.html deleted file mode 100644 index f8bdb2279a..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/cluster/package.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - -Mechanisms for identifying clusters in graphs. Where these clusters define disjoint sets of vertices, -they may be used to define a VertexPartition for more convenient manipulation of the vertex/set -relationships. - -Current clustering algorithms include: -

        -
      • BicomponentClusterer: finds all subsets of vertices for which at least -2 vertices must be removed in order to disconnect the induced subgraphs. -
      • EdgeBetweennessClusterer: identifies vertex clusters by removing the edges of the highest -'betweenness' scores (see the importance/scoring package). -
      • VoltageClusterer: Clusters vertices based on their ranks as -calculated by VoltageRanker. -
      • WeakComponentVertexClusterer: Clusters vertices based on their membership in weakly -connected components of a graph. -
      - - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/EdgePredicateFilter.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/EdgePredicateFilter.java deleted file mode 100644 index 5e3be06d18..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/EdgePredicateFilter.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Created on May 19, 2008 - * - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.filters; - -import org.apache.commons.collections15.Predicate; - -import edu.uci.ics.jung.graph.Graph; - -/** - * Transforms the input graph into one which contains only those edges - * that pass the specified Predicate. The filtered graph - * is a copy of the original graph (same type, uses the same vertex and - * edge objects). All vertices from the original graph - * are copied into the new graph (even if they are not incident to any - * edges in the new graph). - * - * @author Joshua O'Madadhain - */ -public class EdgePredicateFilter implements Filter -{ - protected Predicate edge_pred; - - /** - * Creates an instance based on the specified edge Predicate. - * @param edge_pred the predicate that specifies which edges to add to the filtered graph - */ - public EdgePredicateFilter(Predicate edge_pred) - { - this.edge_pred = edge_pred; - } - - @SuppressWarnings("unchecked") - public Graph transform(Graph g) - { - Graph filtered; - try - { - filtered = g.getClass().newInstance(); - } - catch (InstantiationException e) - { - throw new RuntimeException("Unable to create copy of existing graph: ", e); - } - catch (IllegalAccessException e) - { - throw new RuntimeException("Unable to create copy of existing graph: ", e); - } - - for (V v : g.getVertices()) - filtered.addVertex(v); - - for (E e : g.getEdges()) - { - if (edge_pred.evaluate(e)) - filtered.addEdge(e, g.getIncidentVertices(e)); - } - - return filtered; - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/Filter.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/Filter.java deleted file mode 100644 index a62895cc43..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/Filter.java +++ /dev/null @@ -1,26 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.filters; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Graph; - - - -/** - * An interface for classes that return a subset of the input Graph - * as a Graph. The Graph returned may be either a - * new graph or a view into an existing graph; the documentation for the filter - * must specify which. - * - * @author danyelf - */ -public interface Filter extends Transformer, Graph>{ } diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/FilterUtils.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/FilterUtils.java deleted file mode 100644 index 4845c0f37b..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/FilterUtils.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * Created on Jun 7, 2008 - * - */ -package edu.uci.ics.jung.algorithms.filters; - -import java.util.ArrayList; -import java.util.Collection; - -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Utility methods relating to filtering. - */ -public class FilterUtils -{ - /** - * Creates the induced subgraph from graph whose vertex set - * is equal to vertices. The graph returned has - * vertices as its vertex set, and includes all edges from - * graph which are incident only to elements of - * vertices. - * - * @param the vertex type - * @param the edge type - * @param vertices the subset of graph's vertices around - * which the subgraph is to be constructed - * @param graph the graph whose subgraph is to be constructed - * @return the subgraph induced by vertices - * @throws IllegalArgumentException if any vertex in - * vertices is not in graph - */ - @SuppressWarnings("unchecked") - public static > G createInducedSubgraph(Collection - vertices, G graph) - { - G subgraph = null; - try - { - subgraph = (G)graph.getClass().newInstance(); - - for (V v : vertices) - { - if (!graph.containsVertex(v)) - throw new IllegalArgumentException("Vertex " + v + - " is not an element of " + graph); - subgraph.addVertex(v); - } - - for (E e : graph.getEdges()) - { - Collection incident = graph.getIncidentVertices(e); - if (vertices.containsAll(incident)) - subgraph.addEdge(e, incident, graph.getEdgeType(e)); - } - } - catch (InstantiationException e) - { - throw new RuntimeException("Unable to create copy of existing graph: ", e); - } - catch (IllegalAccessException e) - { - throw new RuntimeException("Unable to create copy of existing graph: ", e); - } - return subgraph; - } - - /** - * Creates the induced subgraphs of graph associated with each - * element of vertex_collections. - * Note that these vertex collections need not be disjoint. - * @param the vertex type - * @param the edge type - * @param vertex_collections the collections of vertex collections to be - * used to induce the subgraphs - * @param graph the graph whose subgraphs are to be created - * @return the induced subgraphs of graph associated with each - * element of vertex_collections - */ - public static > Collection - createAllInducedSubgraphs(Collection> - vertex_collections, G graph) - { - Collection subgraphs = new ArrayList(); - - for (Collection vertex_set : vertex_collections) - subgraphs.add(createInducedSubgraph(vertex_set, graph)); - - return subgraphs; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/KNeighborhoodFilter.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/KNeighborhoodFilter.java deleted file mode 100644 index 62bcfc29b5..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/KNeighborhoodFilter.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -/* - * Created on Dec 26, 2001 - * - */ -package edu.uci.ics.jung.algorithms.filters; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import edu.uci.ics.jung.algorithms.filters.Filter; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - -/** - * A filter used to extract the k-neighborhood around one or more root node(s). - * The k-neighborhood is defined as the subgraph induced by the set of - * vertices that are k or fewer hops (unweighted shortest-path distance) - * away from the root node. - * - * @author Danyel Fisher - */ -public class KNeighborhoodFilter implements Filter { - - /** - * The type of edge to follow for defining the neighborhood. - */ - public static enum EdgeType { IN_OUT, IN, OUT } - private Set rootNodes; - private int radiusK; - private EdgeType edgeType; - - /** - * Constructs a new instance of the filter. - * @param rootNodes the set of root nodes - * @param radiusK the neighborhood radius around the root set - * @param edgeType 0 for in/out edges, 1 for in-edges, 2 for out-edges - */ - public KNeighborhoodFilter(Set rootNodes, int radiusK, EdgeType edgeType) { - this.rootNodes = rootNodes; - this.radiusK = radiusK; - this.edgeType = edgeType; - } - - /** - * Constructs a new instance of the filter. - * @param rootNode the root node - * @param radiusK the neighborhood radius around the root set - * @param edgeType 0 for in/out edges, 1 for in-edges, 2 for out-edges - */ - public KNeighborhoodFilter(V rootNode, int radiusK, EdgeType edgeType) { - this.rootNodes = new HashSet(); - this.rootNodes.add(rootNode); - this.radiusK = radiusK; - this.edgeType = edgeType; - } - - /** - * Constructs an unassembled graph containing the k-neighborhood around the root node(s). - */ - @SuppressWarnings("unchecked") - public Graph transform(Graph graph) { - // generate a Set of Vertices we want - // add all to the UG - int currentDepth = 0; - List currentVertices = new ArrayList(); - Set visitedVertices = new HashSet(); - Set visitedEdges = new HashSet(); - Set acceptedVertices = new HashSet(); - //Copy, mark, and add all the root nodes to the new subgraph - for (V currentRoot : rootNodes) { - - visitedVertices.add(currentRoot); - acceptedVertices.add(currentRoot); - currentVertices.add(currentRoot); - } - ArrayList newVertices = null; - //Use BFS to locate the neighborhood around the root nodes within distance k - while (currentDepth < radiusK) { - newVertices = new ArrayList(); - for (V currentVertex : currentVertices) { - - Collection edges = null; - switch (edgeType) { - case IN_OUT : - edges = graph.getIncidentEdges(currentVertex); - break; - case IN : - edges = graph.getInEdges(currentVertex); - break; - case OUT : - edges = graph.getOutEdges(currentVertex); - break; - } - for (E currentEdge : edges) { - - V currentNeighbor = - graph.getOpposite(currentVertex, currentEdge); - if (!visitedEdges.contains(currentEdge)) { - visitedEdges.add(currentEdge); - if (!visitedVertices.contains(currentNeighbor)) { - visitedVertices.add(currentNeighbor); - acceptedVertices.add(currentNeighbor); - newVertices.add(currentNeighbor); - } - } - } - } - currentVertices = newVertices; - currentDepth++; - } - Graph ug = null; - try { - ug = graph.getClass().newInstance(); - for(E edge : graph.getEdges()) { - Pair endpoints = graph.getEndpoints(edge); - if(acceptedVertices.containsAll(endpoints)) { - ug.addEdge(edge, endpoints.getFirst(), endpoints.getSecond()); - } - } - } - catch (InstantiationException e) - { - throw new RuntimeException("Unable to create copy of existing graph: ", e); - } - catch (IllegalAccessException e) - { - throw new RuntimeException("Unable to create copy of existing graph: ", e); - } - return ug; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/VertexPredicateFilter.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/VertexPredicateFilter.java deleted file mode 100644 index 4543b424dc..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/VertexPredicateFilter.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Created on May 19, 2008 - * - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.filters; - -import java.util.Collection; - -import org.apache.commons.collections15.Predicate; - -import edu.uci.ics.jung.graph.Graph; - -/** - * Transforms the input graph into one which contains only those vertices - * that pass the specified Predicate. The filtered graph - * is a copy of the original graph (same type, uses the same vertex and - * edge objects). Only those edges whose entire incident vertex collection - * passes the predicate are copied into the new graph. - * - * @author Joshua O'Madadhain - */ -public class VertexPredicateFilter implements Filter -{ - protected Predicate vertex_pred; - - /** - * Creates an instance based on the specified vertex Predicate. - * @param vertex_pred the predicate that specifies which vertices to add to the filtered graph - */ - public VertexPredicateFilter(Predicate vertex_pred) - { - this.vertex_pred = vertex_pred; - } - - @SuppressWarnings("unchecked") - public Graph transform(Graph g) - { - Graph filtered; - try - { - filtered = g.getClass().newInstance(); - } - catch (InstantiationException e) - { - throw new RuntimeException("Unable to create copy of existing graph: ", e); - } - catch (IllegalAccessException e) - { - throw new RuntimeException("Unable to create copy of existing graph: ", e); - } - - for (V v : g.getVertices()) - if (vertex_pred.evaluate(v)) - filtered.addVertex(v); - - Collection filtered_vertices = filtered.getVertices(); - - for (E e : g.getEdges()) - { - Collection incident = g.getIncidentVertices(e); - if (filtered_vertices.containsAll(incident)) - filtered.addEdge(e, incident); - } - - return filtered; - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/package.html deleted file mode 100644 index 0f9a018f88..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/filters/package.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - -Filtering mechanisms that produce subgraphs of an original graph. -Currently includes: -
        -
      • Filter: an interface for graph filters -
      • {Edge,Vertex}PredicateFilter: graph filters that return the -induced subgraph according to the -specified edge or vertex Predicate, respectively. -
      • KNeighborhoodFilter: a filter that returns the subgraph -induced by vertices within (unweighted) distance k of a specified vertex. -
      - - - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/flows/EdmondsKarpMaxFlow.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/flows/EdmondsKarpMaxFlow.java deleted file mode 100644 index af9ee34c4c..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/flows/EdmondsKarpMaxFlow.java +++ /dev/null @@ -1,314 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.flows; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Buffer; -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.buffer.UnboundedFifoBuffer; - -import edu.uci.ics.jung.algorithms.util.IterativeProcess; -import edu.uci.ics.jung.graph.DirectedGraph; -import edu.uci.ics.jung.graph.util.EdgeType; - - -/** - * Implements the Edmonds-Karp maximum flow algorithm for solving the maximum flow problem. - * After the algorithm is executed, - * the input {@code Map} is populated with a {@code Number} for each edge that indicates - * the flow along that edge. - *

      - * An example of using this algorithm is as follows: - *

      - * EdmondsKarpMaxFlow ek = new EdmondsKarpMaxFlow(graph, source, sink, edge_capacities, edge_flows, 
      - * edge_factory);
      - * ek.evaluate(); // This instructs the class to compute the max flow
      - * 
      - * - * @see "Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein." - * @see "Network Flows by Ahuja, Magnanti, and Orlin." - * @see "Theoretical improvements in algorithmic efficiency for network flow problems by Edmonds and Karp, 1972." - * @author Scott White, adapted to jung2 by Tom Nelson - */ -public class EdmondsKarpMaxFlow extends IterativeProcess { - - private DirectedGraph mFlowGraph; - private DirectedGraph mOriginalGraph; - private V source; - private V target; - private int mMaxFlow; - private Set mSourcePartitionNodes; - private Set mSinkPartitionNodes; - private Set mMinCutEdges; - - private Map residualCapacityMap = new HashMap(); - private Map parentMap = new HashMap(); - private Map parentCapacityMap = new HashMap(); - private Transformer edgeCapacityTransformer; - private Map edgeFlowMap; - private Factory edgeFactory; - - /** - * Constructs a new instance of the algorithm solver for a given graph, source, and sink. - * Source and sink vertices must be elements of the specified graph, and must be - * distinct. - * @param directedGraph the flow graph - * @param source the source vertex - * @param sink the sink vertex - * @param edgeCapacityTransformer the transformer that gets the capacity for each edge. - * @param edgeFlowMap the map where the solver will place the value of the flow for each edge - * @param edgeFactory used to create new edge instances for backEdges - */ - @SuppressWarnings("unchecked") - public EdmondsKarpMaxFlow(DirectedGraph directedGraph, V source, V sink, - Transformer edgeCapacityTransformer, Map edgeFlowMap, - Factory edgeFactory) { - - if(directedGraph.getVertices().contains(source) == false || - directedGraph.getVertices().contains(sink) == false) { - throw new IllegalArgumentException("source and sink vertices must be elements of the specified graph"); - } - if (source.equals(sink)) { - throw new IllegalArgumentException("source and sink vertices must be distinct"); - } - mOriginalGraph = directedGraph; - - this.source = source; - this.target = sink; - this.edgeFlowMap = edgeFlowMap; - this.edgeCapacityTransformer = edgeCapacityTransformer; - this.edgeFactory = edgeFactory; - try { - mFlowGraph = directedGraph.getClass().newInstance(); - for(E e : mOriginalGraph.getEdges()) { - mFlowGraph.addEdge(e, mOriginalGraph.getSource(e), - mOriginalGraph.getDest(e), EdgeType.DIRECTED); - } - for(V v : mOriginalGraph.getVertices()) { - mFlowGraph.addVertex(v); - } - - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - mMaxFlow = 0; - mSinkPartitionNodes = new HashSet(); - mSourcePartitionNodes = new HashSet(); - mMinCutEdges = new HashSet(); - } - - private void clearParentValues() { - parentMap.clear(); - parentCapacityMap.clear(); - parentCapacityMap.put(source, Integer.MAX_VALUE); - parentMap.put(source, source); - } - - protected boolean hasAugmentingPath() { - - mSinkPartitionNodes.clear(); - mSourcePartitionNodes.clear(); - mSinkPartitionNodes.addAll(mFlowGraph.getVertices()); - - Set visitedEdgesMap = new HashSet(); - Buffer queue = new UnboundedFifoBuffer(); - queue.add(source); - - while (!queue.isEmpty()) { - V currentVertex = queue.remove(); - mSinkPartitionNodes.remove(currentVertex); - mSourcePartitionNodes.add(currentVertex); - Number currentCapacity = parentCapacityMap.get(currentVertex); - - Collection neighboringEdges = mFlowGraph.getOutEdges(currentVertex); - - for (E neighboringEdge : neighboringEdges) { - - V neighboringVertex = mFlowGraph.getDest(neighboringEdge); - - Number residualCapacity = residualCapacityMap.get(neighboringEdge); - if (residualCapacity.intValue() <= 0 || visitedEdgesMap.contains(neighboringEdge)) - continue; - - V neighborsParent = parentMap.get(neighboringVertex); - Number neighborCapacity = parentCapacityMap.get(neighboringVertex); - int newCapacity = Math.min(residualCapacity.intValue(),currentCapacity.intValue()); - - if ((neighborsParent == null) || newCapacity > neighborCapacity.intValue()) { - parentMap.put(neighboringVertex, currentVertex); - parentCapacityMap.put(neighboringVertex, new Integer(newCapacity)); - visitedEdgesMap.add(neighboringEdge); - if (neighboringVertex != target) { - queue.add(neighboringVertex); - } - } - } - } - - boolean hasAugmentingPath = false; - Number targetsParentCapacity = parentCapacityMap.get(target); - if (targetsParentCapacity != null && targetsParentCapacity.intValue() > 0) { - updateResidualCapacities(); - hasAugmentingPath = true; - } - clearParentValues(); - return hasAugmentingPath; - } - - @Override - public void step() { - while (hasAugmentingPath()) { - } - computeMinCut(); -// return 0; - } - - private void computeMinCut() { - - for (E e : mOriginalGraph.getEdges()) { - - V source = mOriginalGraph.getSource(e); - V destination = mOriginalGraph.getDest(e); - if (mSinkPartitionNodes.contains(source) && mSinkPartitionNodes.contains(destination)) { - continue; - } - if (mSourcePartitionNodes.contains(source) && mSourcePartitionNodes.contains(destination)) { - continue; - } - if (mSinkPartitionNodes.contains(source) && mSourcePartitionNodes.contains(destination)) { - continue; - } - mMinCutEdges.add(e); - } - } - - /** - * Returns the value of the maximum flow from the source to the sink. - */ - public int getMaxFlow() { - return mMaxFlow; - } - - /** - * Returns the nodes which share the same partition (as defined by the min-cut edges) - * as the sink node. - */ - public Set getNodesInSinkPartition() { - return mSinkPartitionNodes; - } - - /** - * Returns the nodes which share the same partition (as defined by the min-cut edges) - * as the source node. - */ - public Set getNodesInSourcePartition() { - return mSourcePartitionNodes; - } - - /** - * Returns the edges in the minimum cut. - */ - public Set getMinCutEdges() { - return mMinCutEdges; - } - - /** - * Returns the graph for which the maximum flow is calculated. - */ - public DirectedGraph getFlowGraph() { - return mFlowGraph; - } - - @Override - protected void initializeIterations() { - parentCapacityMap.put(source, Integer.MAX_VALUE); - parentMap.put(source, source); - - List edgeList = new ArrayList(mFlowGraph.getEdges()); - - for (int eIdx=0;eIdx< edgeList.size();eIdx++) { - E edge = edgeList.get(eIdx); - Number capacity = edgeCapacityTransformer.transform(edge); - - if (capacity == null) { - throw new IllegalArgumentException("Edge capacities must be provided in Transformer passed to constructor"); - } - residualCapacityMap.put(edge, capacity); - - V source = mFlowGraph.getSource(edge); - V destination = mFlowGraph.getDest(edge); - - if(mFlowGraph.isPredecessor(source, destination) == false) { - E backEdge = edgeFactory.create(); - mFlowGraph.addEdge(backEdge, destination, source, EdgeType.DIRECTED); - residualCapacityMap.put(backEdge, 0); - } - } - } - - @Override - protected void finalizeIterations() { - - for (E currentEdge : mFlowGraph.getEdges()) { - Number capacity = edgeCapacityTransformer.transform(currentEdge); - - Number residualCapacity = residualCapacityMap.get(currentEdge); - if (capacity != null) { - Integer flowValue = new Integer(capacity.intValue()-residualCapacity.intValue()); - this.edgeFlowMap.put(currentEdge, flowValue); - } - } - - Set backEdges = new HashSet(); - for (E currentEdge: mFlowGraph.getEdges()) { - - if (edgeCapacityTransformer.transform(currentEdge) == null) { - backEdges.add(currentEdge); - } else { - residualCapacityMap.remove(currentEdge); - } - } - for(E e : backEdges) { - mFlowGraph.removeEdge(e); - } - } - - private void updateResidualCapacities() { - - Number augmentingPathCapacity = parentCapacityMap.get(target); - mMaxFlow += augmentingPathCapacity.intValue(); - V currentVertex = target; - V parentVertex = null; - while ((parentVertex = parentMap.get(currentVertex)) != currentVertex) { - E currentEdge = mFlowGraph.findEdge(parentVertex, currentVertex); - - Number residualCapacity = residualCapacityMap.get(currentEdge); - - residualCapacity = residualCapacity.intValue() - augmentingPathCapacity.intValue(); - residualCapacityMap.put(currentEdge, residualCapacity); - - E backEdge = mFlowGraph.findEdge(currentVertex, parentVertex); - residualCapacity = residualCapacityMap.get(backEdge); - residualCapacity = residualCapacity.intValue() + augmentingPathCapacity.intValue(); - residualCapacityMap.put(backEdge, residualCapacity); - currentVertex = parentVertex; - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/flows/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/flows/package.html deleted file mode 100644 index 1ec243d845..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/flows/package.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - -Methods for calculating properties relating to network flows (such as max flow/min cut). - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/EvolvingGraphGenerator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/EvolvingGraphGenerator.java deleted file mode 100644 index d351f9b1ca..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/EvolvingGraphGenerator.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.generators; - - - -/** - * An interface for algorithms that generate graphs that evolve iteratively. - * @author Scott White - */ -public interface EvolvingGraphGenerator extends GraphGenerator { - - /** - * Instructs the algorithm to evolve the graph N steps. - * @param numSteps number of steps to iterate from the current state - */ - void evolveGraph(int numSteps); - - /** - * Retrieves the total number of steps elapsed. - * @return number of elapsed steps - */ - int numIterations(); -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/GraphGenerator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/GraphGenerator.java deleted file mode 100644 index a32906095f..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/GraphGenerator.java +++ /dev/null @@ -1,20 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.generators; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.graph.Graph; - -/** - * An interface for algorithms that generate graphs. - * @author Scott White - */ -public interface GraphGenerator extends Factory>{ } diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/Lattice2DGenerator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/Lattice2DGenerator.java deleted file mode 100644 index e84425cebb..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/Lattice2DGenerator.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2009, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ - -package edu.uci.ics.jung.algorithms.generators; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.EdgeType; - -/** - * Simple generator of an m x n lattice where each vertex - * is incident with each of its neighbors (to the left, right, up, and down). - * May be toroidal, in which case the vertices on the edges are connected to - * their counterparts on the opposite edges as well. - * - *

      If the graph factory supplied has a default edge type of {@code EdgeType.DIRECTED}, - * then edges will be created in both directions between adjacent vertices. - * - * @author Joshua O'Madadhain - */ -public class Lattice2DGenerator implements GraphGenerator -{ - protected int row_count; - protected int col_count; - protected boolean is_toroidal; - protected boolean is_directed; - protected Factory> graph_factory; - protected Factory vertex_factory; - protected Factory edge_factory; - private List v_array; - - /** - * Constructs a generator of square lattices of size {@code latticeSize} - * with the specified parameters. - * - * @param graph_factory used to create the {@code Graph} for the lattice - * @param vertex_factory used to create the lattice vertices - * @param edge_factory used to create the lattice edges - * @param latticeSize the number of rows and columns of the lattice - * @param isToroidal if true, the created lattice wraps from top to bottom and left to right - */ - public Lattice2DGenerator(Factory> graph_factory, Factory vertex_factory, - Factory edge_factory, int latticeSize, boolean isToroidal) - { - this(graph_factory, vertex_factory, edge_factory, latticeSize, latticeSize, isToroidal); - } - - /** - * Creates a generator of {@code row_count} x {@code col_count} lattices - * with the specified parameters. - * - * @param graph_factory used to create the {@code Graph} for the lattice - * @param vertex_factory used to create the lattice vertices - * @param edge_factory used to create the lattice edges - * @param row_count the number of rows in the lattice - * @param col_count the number of columns in the lattice - * @param isToroidal if true, the created lattice wraps from top to bottom and left to right - */ - public Lattice2DGenerator(Factory> graph_factory, Factory vertex_factory, - Factory edge_factory, int row_count, int col_count, boolean isToroidal) - { - if (row_count < 2 || col_count < 2) - { - throw new IllegalArgumentException("Row and column counts must each be at least 2."); - } - - this.row_count = row_count; - this.col_count = col_count; - this.is_toroidal = isToroidal; - this.graph_factory = graph_factory; - this.vertex_factory = vertex_factory; - this.edge_factory = edge_factory; - this.is_directed = (graph_factory.create().getDefaultEdgeType() == EdgeType.DIRECTED); - } - - /** - * @see edu.uci.ics.jung.algorithms.generators.GraphGenerator#create() - */ - @SuppressWarnings("unchecked") - public Graph create() - { - int vertex_count = row_count * col_count; - Graph graph = graph_factory.create(); - v_array = new ArrayList(vertex_count); - for (int i = 0; i < vertex_count; i++) - { - V v = vertex_factory.create(); - graph.addVertex(v); - v_array.add(i, v); - } - - int start = is_toroidal ? 0 : 1; - int end_row = is_toroidal ? row_count : row_count - 1; - int end_col = is_toroidal ? col_count : col_count - 1; - - // fill in edges - // down - for (int i = 0; i < end_row; i++) - for (int j = 0; j < col_count; j++) - graph.addEdge(edge_factory.create(), getVertex(i,j), getVertex(i+1, j)); - // right - for (int i = 0; i < row_count; i++) - for (int j = 0; j < end_col; j++) - graph.addEdge(edge_factory.create(), getVertex(i,j), getVertex(i, j+1)); - - // if the graph is directed, fill in the edges going the other direction... - if (graph.getDefaultEdgeType() == EdgeType.DIRECTED) - { - // up - for (int i = start; i < row_count; i++) - for (int j = 0; j < col_count; j++) - graph.addEdge(edge_factory.create(), getVertex(i,j), getVertex(i-1, j)); - // left - for (int i = 0; i < row_count; i++) - for (int j = start; j < col_count; j++) - graph.addEdge(edge_factory.create(), getVertex(i,j), getVertex(i, j-1)); - } - - return graph; - } - - /** - * Returns the number of edges found in a lattice of this generator's specifications. - * (This is useful for subclasses that may modify the generated graphs to add more edges.) - */ - public int getGridEdgeCount() - { - int boundary_adjustment = (is_toroidal ? 0 : 1); - int vertical_edge_count = col_count * (row_count - boundary_adjustment); - int horizontal_edge_count = row_count * (col_count - boundary_adjustment); - - return (vertical_edge_count + horizontal_edge_count) * (is_directed ? 2 : 1); - } - - protected int getIndex(int i, int j) - { - return ((mod(i, row_count)) * col_count) + (mod(j, col_count)); - } - - protected int mod(int i, int modulus) - { - int i_mod = i % modulus; - return i_mod >= 0 ? i_mod : i_mod + modulus; - } - - /** - * Returns the vertex at position ({@code i mod row_count, j mod col_count}). - */ - protected V getVertex(int i, int j) - { - return v_array.get(getIndex(i, j)); - } - - /** - * Returns the {@code i}th vertex (counting row-wise). - */ - protected V getVertex(int i) - { - return v_array.get(i); - } - - /** - * Returns the row in which vertex {@code i} is found. - */ - protected int getRow(int i) - { - return i / row_count; - } - - /** - * Returns the column in which vertex {@code i} is found. - */ - protected int getCol(int i) - { - return i % col_count; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/package.html deleted file mode 100644 index 441922dca5..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/package.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - -Methods for generating new (often random) graphs with various properties. - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/BarabasiAlbertGenerator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/BarabasiAlbertGenerator.java deleted file mode 100644 index 77b419b4a4..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/BarabasiAlbertGenerator.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.generators.random; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.algorithms.generators.EvolvingGraphGenerator; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.MultiGraph; -import edu.uci.ics.jung.graph.util.EdgeType; -import edu.uci.ics.jung.graph.util.Pair; - - -/** - *

      Simple evolving scale-free random graph generator. At each time - * step, a new vertex is created and is connected to existing vertices - * according to the principle of "preferential attachment", whereby - * vertices with higher degree have a higher probability of being - * selected for attachment.

      - * - *

      At a given timestep, the probability p of creating an edge - * between an existing vertex v and the newly added vertex is - *

      - * p = (degree(v) + 1) / (|E| + |V|);
      - * 
      - * - *

      where |E| and |V| are, respectively, the number - * of edges and vertices currently in the network (counting neither the new - * vertex nor the other edges that are being attached to it).

      - * - *

      Note that the formula specified in the original paper - * (cited below) was - *

      - * p = degree(v) / |E|
      - * 
      - *

      - * - *

      However, this would have meant that the probability of attachment for any existing - * isolated vertex would be 0. This version uses Lagrangian smoothing to give - * each existing vertex a positive attachment probability.

      - * - *

      The graph created may be either directed or undirected (controlled by a constructor - * parameter); the default is undirected. - * If the graph is specified to be directed, then the edges added will be directed - * from the newly added vertex u to the existing vertex v, with probability proportional to the - * indegree of v (number of edges directed towards v). If the graph is specified to be undirected, - * then the (undirected) edges added will connect u to v, with probability proportional to the - * degree of v.

      - * - *

      The parallel constructor parameter specifies whether parallel edges - * may be created.

      - * - * @see "A.-L. Barabasi and R. Albert, Emergence of scaling in random networks, Science 286, 1999." - * @author Scott White - * @author Joshua O'Madadhain - * @author Tom Nelson - adapted to jung2 - */ -public class BarabasiAlbertGenerator implements EvolvingGraphGenerator { - private Graph mGraph = null; - private int mNumEdgesToAttachPerStep; - private int mElapsedTimeSteps; - private Random mRandom; - protected List vertex_index; - protected int init_vertices; - protected Map index_vertex; - protected Factory> graphFactory; - protected Factory vertexFactory; - protected Factory edgeFactory; - - /** - * Constructs a new instance of the generator. - * @param init_vertices number of unconnected 'seed' vertices that the graph should start with - * @param numEdgesToAttach the number of edges that should be attached from the - * new vertex to pre-existing vertices at each time step - * @param directed specifies whether the graph and edges to be created should be directed or not - * @param parallel specifies whether the algorithm permits parallel edges - * @param seed random number seed - */ - public BarabasiAlbertGenerator(Factory> graphFactory, - Factory vertexFactory, Factory edgeFactory, - int init_vertices, int numEdgesToAttach, - int seed, Set seedVertices) - { - assert init_vertices > 0 : "Number of initial unconnected 'seed' vertices " + - "must be positive"; - assert numEdgesToAttach > 0 : "Number of edges to attach " + - "at each time step must be positive"; - - mNumEdgesToAttachPerStep = numEdgesToAttach; - mRandom = new Random(seed); - this.graphFactory = graphFactory; - this.vertexFactory = vertexFactory; - this.edgeFactory = edgeFactory; - this.init_vertices = init_vertices; - initialize(seedVertices); - } - - - /** - * Constructs a new instance of the generator, whose output will be an undirected graph, - * and which will use the current time as a seed for the random number generation. - * @param init_vertices number of vertices that the graph should start with - * @param numEdgesToAttach the number of edges that should be attached from the - * new vertex to pre-existing vertices at each time step - */ - public BarabasiAlbertGenerator(Factory> graphFactory, - Factory vertexFactory, Factory edgeFactory, - int init_vertices, int numEdgesToAttach, Set seedVertices) { - this(graphFactory, vertexFactory, edgeFactory, init_vertices, numEdgesToAttach, (int) System.currentTimeMillis(), seedVertices); - } - - private void initialize(Set seedVertices) { - - mGraph = graphFactory.create(); - - vertex_index = new ArrayList(2*init_vertices); - index_vertex = new HashMap(2*init_vertices); - for (int i = 0; i < init_vertices; i++) { - V v = vertexFactory.create(); - mGraph.addVertex(v); - vertex_index.add(v); - index_vertex.put(v, i); - seedVertices.add(v); - } - - mElapsedTimeSteps = 0; - } - - private void createRandomEdge(Collection preexistingNodes, - V newVertex, Set> added_pairs) { - V attach_point; - boolean created_edge = false; - Pair endpoints; - do { - attach_point = vertex_index.get(mRandom.nextInt(vertex_index.size())); - - endpoints = new Pair(newVertex, attach_point); - - // if parallel edges are not allowed, skip attach_point if - // already exists; note that because of the way edges are added, we only need to check - // the list of candidate edges for duplicates. - if (!(mGraph instanceof MultiGraph)) - { - if (added_pairs.contains(endpoints)) - continue; - if (mGraph.getDefaultEdgeType() == EdgeType.UNDIRECTED && - added_pairs.contains(new Pair(attach_point, newVertex))) - continue; - } - - double degree = mGraph.inDegree(attach_point); - - // subtract 1 from numVertices because we don't want to count newVertex - // (which has already been added to the graph, but not to vertex_index) - double attach_prob = (degree + 1) / (mGraph.getEdgeCount() + mGraph.getVertexCount() - 1); - if (attach_prob >= mRandom.nextDouble()) - created_edge = true; - } - while (!created_edge); - - added_pairs.add(endpoints); - - if (mGraph.getDefaultEdgeType() == EdgeType.UNDIRECTED) { - added_pairs.add(new Pair(attach_point, newVertex)); - } - } - - public void evolveGraph(int numTimeSteps) { - - for (int i = 0; i < numTimeSteps; i++) { - evolveGraph(); - mElapsedTimeSteps++; - } - } - - private void evolveGraph() { - Collection preexistingNodes = mGraph.getVertices(); - V newVertex = vertexFactory.create(); - - mGraph.addVertex(newVertex); - - // generate and store the new edges; don't add them to the graph - // yet because we don't want to bias the degree calculations - // (all new edges in a timestep should be added in parallel) - Set> added_pairs = new HashSet>(mNumEdgesToAttachPerStep*3); - - for (int i = 0; i < mNumEdgesToAttachPerStep; i++) - createRandomEdge(preexistingNodes, newVertex, added_pairs); - - for (Pair pair : added_pairs) - { - V v1 = pair.getFirst(); - V v2 = pair.getSecond(); - if (mGraph.getDefaultEdgeType() != EdgeType.UNDIRECTED || - !mGraph.isNeighbor(v1, v2)) - mGraph.addEdge(edgeFactory.create(), pair); - } - // now that we're done attaching edges to this new vertex, - // add it to the index - vertex_index.add(newVertex); - index_vertex.put(newVertex, new Integer(vertex_index.size() - 1)); - } - - public int numIterations() { - return mElapsedTimeSteps; - } - - public Graph create() { - return mGraph; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/EppsteinPowerLawGenerator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/EppsteinPowerLawGenerator.java deleted file mode 100644 index e3bf04b68d..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/EppsteinPowerLawGenerator.java +++ /dev/null @@ -1,128 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.generators.random; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.algorithms.generators.GraphGenerator; -import edu.uci.ics.jung.graph.Graph; - -/** - * Graph generator that generates undirected graphs with power-law degree distributions. - * @author Scott White - * @see "A Steady State Model for Graph Power Law by David Eppstein and Joseph Wang" - */ -public class EppsteinPowerLawGenerator implements GraphGenerator { - private int mNumVertices; - private int mNumEdges; - private int mNumIterations; - private double mMaxDegree; - private Random mRandom; - private Factory> graphFactory; - private Factory vertexFactory; - private Factory edgeFactory; - - /** - * Creates an instance with the specified factories and specifications. - * @param graphFactory the factory to use to generate the graph - * @param vertexFactory the factory to use to create vertices - * @param edgeFactory the factory to use to create edges - * @param numVertices the number of vertices for the generated graph - * @param numEdges the number of edges the generated graph will have, should be Theta(numVertices) - * @param r the number of iterations to use; the larger the value the better the graph's degree - * distribution will approximate a power-law - */ - public EppsteinPowerLawGenerator(Factory> graphFactory, - Factory vertexFactory, Factory edgeFactory, - int numVertices, int numEdges, int r) { - this.graphFactory = graphFactory; - this.vertexFactory = vertexFactory; - this.edgeFactory = edgeFactory; - mNumVertices = numVertices; - mNumEdges = numEdges; - mNumIterations = r; - mRandom = new Random(); - } - - protected Graph initializeGraph() { - Graph graph = null; - graph = graphFactory.create(); - for(int i=0; i vertices = new ArrayList(graph.getVertices()); - while (graph.getEdgeCount() < mNumEdges) { - V u = vertices.get((int) (mRandom.nextDouble() * mNumVertices)); - V v = vertices.get((int) (mRandom.nextDouble() * mNumVertices)); - if (!graph.isSuccessor(v,u)) { - graph.addEdge(edgeFactory.create(), u, v); - } - } - - double maxDegree = 0; - for (V v : graph.getVertices()) { - maxDegree = Math.max(graph.degree(v),maxDegree); - } - mMaxDegree = maxDegree; //(maxDegree+1)*(maxDegree)/2; - - return graph; - } - - /** - * Generates a graph whose degree distribution approximates a power-law. - * @return the generated graph - */ - public Graph create() { - Graph graph = initializeGraph(); - - List vertices = new ArrayList(graph.getVertices()); - for (int rIdx = 0; rIdx < mNumIterations; rIdx++) { - - V v = null; - int degree = 0; - do { - v = vertices.get((int) (mRandom.nextDouble() * mNumVertices)); - degree = graph.degree(v); - - } while (degree == 0); - - List edges = new ArrayList(graph.getIncidentEdges(v)); - E randomExistingEdge = edges.get((int) (mRandom.nextDouble()*degree)); - - // FIXME: look at email thread on a more efficient RNG for arbitrary distributions - - V x = vertices.get((int) (mRandom.nextDouble() * mNumVertices)); - V y = null; - do { - y = vertices.get((int) (mRandom.nextDouble() * mNumVertices)); - - } while (mRandom.nextDouble() > ((graph.degree(y)+1)/mMaxDegree)); - - if (!graph.isSuccessor(y,x) && x != y) { - graph.removeEdge(randomExistingEdge); - graph.addEdge(edgeFactory.create(), x, y); - } - } - - return graph; - } - - /** - * Sets the seed for the random number generator. - * @param seed input to the random number generator. - */ - public void setSeed(long seed) { - mRandom.setSeed(seed); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/ErdosRenyiGenerator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/ErdosRenyiGenerator.java deleted file mode 100644 index 3a33730802..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/ErdosRenyiGenerator.java +++ /dev/null @@ -1,100 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.generators.random; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.algorithms.generators.GraphGenerator; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.UndirectedGraph; - -/** - * Generates a random graph using the Erdos-Renyi binomial model - * (each pair of vertices is connected with probability p). - * - * @author William Giordano, Scott White, Joshua O'Madadhain - */ -public class ErdosRenyiGenerator implements GraphGenerator { - private int mNumVertices; - private double mEdgeConnectionProbability; - private Random mRandom; - Factory> graphFactory; - Factory vertexFactory; - Factory edgeFactory; - - /** - * - * @param numVertices number of vertices graph should have - * @param p Connection's probability between 2 vertices - */ - public ErdosRenyiGenerator(Factory> graphFactory, - Factory vertexFactory, Factory edgeFactory, - int numVertices,double p) - { - if (numVertices <= 0) { - throw new IllegalArgumentException("A positive # of vertices must be specified."); - } - mNumVertices = numVertices; - if (p < 0 || p > 1) { - throw new IllegalArgumentException("p must be between 0 and 1."); - } - this.graphFactory = graphFactory; - this.vertexFactory = vertexFactory; - this.edgeFactory = edgeFactory; - mEdgeConnectionProbability = p; - mRandom = new Random(); - } - - /** - * Returns a graph in which each pair of vertices is connected by - * an undirected edge with the probability specified by the constructor. - */ - public Graph create() { - UndirectedGraph g = graphFactory.create(); - for(int i=0; i list = new ArrayList(g.getVertices()); - - for (int i = 0; i < mNumVertices-1; i++) { - V v_i = list.get(i); - for (int j = i+1; j < mNumVertices; j++) { - V v_j = list.get(j); - if (mRandom.nextDouble() < mEdgeConnectionProbability) { - g.addEdge(edgeFactory.create(), v_i, v_j); - } - } - } - return g; - } - - /** - * Sets the seed of the internal random number generator to {@code seed}. - * Enables consistent behavior. - */ - public void setSeed(long seed) { - mRandom.setSeed(seed); - } -} - - - - - - - - - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/KleinbergSmallWorldGenerator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/KleinbergSmallWorldGenerator.java deleted file mode 100644 index de01b69b5a..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/KleinbergSmallWorldGenerator.java +++ /dev/null @@ -1,184 +0,0 @@ - -package edu.uci.ics.jung.algorithms.generators.random; - -/* -* Copyright (c) 2009, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ - -import java.util.HashMap; -import java.util.Map; -import java.util.Random; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.algorithms.generators.Lattice2DGenerator; -import edu.uci.ics.jung.algorithms.util.WeightedChoice; -import edu.uci.ics.jung.graph.Graph; - -/** - * Graph generator that produces a random graph with small world properties. - * The underlying model is an mxn (optionally toroidal) lattice. Each node u - * has four local connections, one to each of its neighbors, and - * in addition 1+ long range connections to some node v where v is chosen randomly according to - * probability proportional to d^-alpha where d is the lattice distance between u and v and alpha - * is the clustering exponent. - * - * @see "Navigation in a small world J. Kleinberg, Nature 406(2000), 845." - * @author Joshua O'Madadhain - */ -public class KleinbergSmallWorldGenerator extends Lattice2DGenerator { - private double clustering_exponent; - private Random random; - private int num_connections = 1; - - /** - * Creates - * @param graph_factory - * @param vertex_factory - * @param edge_factory - * @param latticeSize - * @param clusteringExponent - */ - public KleinbergSmallWorldGenerator(Factory> graph_factory, Factory vertex_factory, - Factory edge_factory, int latticeSize, double clusteringExponent) - { - this(graph_factory, vertex_factory, edge_factory, latticeSize, latticeSize, clusteringExponent); - } - - /** - * @param graph_factory - * @param vertex_factory - * @param edge_factory - * @param row_count - * @param col_count - * @param clusteringExponent - */ - public KleinbergSmallWorldGenerator(Factory> graph_factory, Factory vertex_factory, - Factory edge_factory, int row_count, int col_count, double clusteringExponent) - { - super(graph_factory, vertex_factory, edge_factory, row_count, col_count, true); - clustering_exponent = clusteringExponent; - initialize(); - } - - /** - * @param graph_factory - * @param vertex_factory - * @param edge_factory - * @param row_count - * @param col_count - * @param clusteringExponent - * @param isToroidal - */ - public KleinbergSmallWorldGenerator(Factory> graph_factory, Factory vertex_factory, - Factory edge_factory, int row_count, int col_count, double clusteringExponent, - boolean isToroidal) - { - super(graph_factory, vertex_factory, edge_factory, row_count, col_count, isToroidal); - clustering_exponent = clusteringExponent; - initialize(); - } - - private void initialize() - { - this.random = new Random(); - } - - /** - * Sets the {@code Random} instance used by this instance. Useful for - * unit testing. - */ - public void setRandom(Random random) - { - this.random = random; - } - - /** - * Sets the seed of the internal random number generator. May be used to provide repeatable - * experiments. - */ - public void setRandomSeed(long seed) - { - random.setSeed(seed); - } - - /** - * Sets the number of new 'small-world' connections (outgoing edges) to be added to each vertex. - */ - public void setConnectionCount(int num_connections) - { - if (num_connections <= 0) - { - throw new IllegalArgumentException("Number of new connections per vertex must be >= 1"); - } - this.num_connections = num_connections; - } - - /** - * Returns the number of new 'small-world' connections to be made to each vertex. - */ - public int getConnectionCount() - { - return this.num_connections; - } - - /** - * Generates a random small world network according to the parameters given - * @return a random small world graph - */ - @Override - public Graph create() - { - Graph graph = super.create(); - - // TODO: For toroidal graphs, we can make this more clever by pre-creating the WeightedChoice object - // and using the output as an offset to the current vertex location. - WeightedChoice weighted_choice; - - // Add long range connections - for (int i = 0; i < graph.getVertexCount(); i++) - { - V source = getVertex(i); - int row = getRow(i); - int col = getCol(i); - int row_offset = row < row_count/2 ? -row_count : row_count; - int col_offset = col < col_count/2 ? -col_count : col_count; - - Map vertex_weights = new HashMap(); - for (int j = 0; j < row_count; j++) - { - for (int k = 0; k < col_count; k++) - { - if (j == row && k == col) - continue; - int v_dist = Math.abs(j - row); - int h_dist = Math.abs(k - col); - if (is_toroidal) - { - v_dist = Math.min(v_dist, Math.abs(j - row+row_offset)); - h_dist = Math.min(h_dist, Math.abs(k - col+col_offset)); - } - int distance = v_dist + h_dist; - if (distance < 2) - continue; - else - vertex_weights.put(getVertex(j,k), (float)Math.pow(distance, -clustering_exponent)); - } - } - - for (int j = 0; j < this.num_connections; j++) { - weighted_choice = new WeightedChoice(vertex_weights, random); - V target = weighted_choice.nextItem(); - graph.addEdge(edge_factory.create(), source, target); - } - } - - return graph; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/MixedRandomGraphGenerator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/MixedRandomGraphGenerator.java deleted file mode 100644 index a39a6404bd..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/MixedRandomGraphGenerator.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - */ -/* - * Created on Jul 2, 2003 - * - */ -package edu.uci.ics.jung.algorithms.generators.random; - -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.EdgeType; - -/** - * - * Generates a mixed-mode random graph based on the output of BarabasiAlbertGenerator. - * Primarily intended for providing a heterogeneous sample graph for visualization testing, etc. - * - */ -public class MixedRandomGraphGenerator { - - /** - * Equivalent to generateMixedRandomGraph(edge_weight, num_vertices, true). - */ - public static Graph generateMixedRandomGraph( - Factory> graphFactory, - Factory vertexFactory, - Factory edgeFactory, - Map edge_weight, - int num_vertices, Set seedVertices) - { - return generateMixedRandomGraph(graphFactory, vertexFactory, edgeFactory, - edge_weight, num_vertices, true, seedVertices); - } - - /** - * Returns a random mixed-mode graph. Starts with a randomly generated - * Barabasi-Albert (preferential attachment) generator - * (4 initial vertices, 3 edges added at each step, and num_vertices - 4 evolution steps). - * Then takes the resultant graph, replaces random undirected edges with directed - * edges, and assigns random weights to each edge. - */ - public static Graph generateMixedRandomGraph( - Factory> graphFactory, - Factory vertexFactory, - Factory edgeFactory, - Map edge_weights, - int num_vertices, boolean parallel, Set seedVertices) - { - int seed = (int)(Math.random() * 10000); - BarabasiAlbertGenerator bag = - new BarabasiAlbertGenerator(graphFactory, vertexFactory, edgeFactory, - 4, 3, //false, parallel, - seed, seedVertices); - bag.evolveGraph(num_vertices - 4); - Graph ug = bag.create(); - - // create a SparseMultigraph version of g - Graph g = graphFactory.create(); - //new SparseMultigraph(); - for(V v : ug.getVertices()) { - g.addVertex(v); - } - - // randomly replace some of the edges by directed edges to - // get a mixed-mode graph, add random weights - - for(E e : ug.getEdges()) { - V v1 = ug.getEndpoints(e).getFirst(); - V v2 = ug.getEndpoints(e).getSecond(); - - E me = edgeFactory.create(); - g.addEdge(me, v1, v2, Math.random() < .5 ? EdgeType.DIRECTED : EdgeType.UNDIRECTED); - edge_weights.put(me, Math.random()); - } - - return g; - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/package.html deleted file mode 100644 index 9f85614a82..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/generators/random/package.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - -Methods for generating random graphs with various properties. These include: -
        -
      • BarabasiAlbertGenerator: scale-free graphs using the preferential attachment heuristic. -
      • EppsteinPowerLawGenerator: graphs whose degree distribution approximates a power law -
      • ErdosRenyiGenerator: graphs for which edges are created with a specified probability -
      • MixedRandomGraphGenerator: takes the output of BarabasiAlbertGenerator and -perturbs it to generate a mixed-mode analog with both directed and undirected edges. -
      • - - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/AbstractRanker.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/AbstractRanker.java deleted file mode 100644 index 6ea8bc84a7..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/AbstractRanker.java +++ /dev/null @@ -1,388 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.importance; - -import java.text.DecimalFormat; -import java.text.Format; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.map.LazyMap; - -import edu.uci.ics.jung.algorithms.util.IterativeProcess; -import edu.uci.ics.jung.graph.Graph; - -/** - * Abstract class for algorithms that rank nodes or edges by some "importance" metric. Provides a common set of - * services such as: - *
          - *
        • storing rank scores
        • - *
        • getters and setters for rank scores
        • - *
        • computing default edge weights
        • - *
        • normalizing default or user-provided edge transition weights
        • - *
        • normalizing rank scores
        • - *
        • automatic cleanup of decorations
        • - *
        • creation of Ranking list
        • - *
        • print rankings in sorted order by rank
        • - *
        - *

        - * By default, all rank scores are removed from the vertices (or edges) being ranked. - * @author Scott White - */ -public abstract class AbstractRanker extends IterativeProcess { - private Graph mGraph; - private List> mRankings; - private boolean mRemoveRankScoresOnFinalize; - private boolean mRankNodes; - private boolean mRankEdges; - private boolean mNormalizeRankings; - protected Map> vertexRankScores = - LazyMap.decorate( - new HashMap>(), - new Factory>() { - public Map create() { - return new HashMap(); - }}); - protected Map> edgeRankScores = - LazyMap.decorate( - new HashMap>(), - new Factory>() { - public Map create() { - return new HashMap(); - }}); - private Map edgeWeights = new HashMap(); - - protected void initialize(Graph graph, boolean isNodeRanker, - boolean isEdgeRanker) { - if (!isNodeRanker && !isEdgeRanker) - throw new IllegalArgumentException("Must rank edges, vertices, or both"); - mGraph = graph; - mRemoveRankScoresOnFinalize = true; - mNormalizeRankings = true; - mRankNodes = isNodeRanker; - mRankEdges = isEdgeRanker; - } - - /** - * @return all rankScores - */ - public Map> getVertexRankScores() { - return vertexRankScores; - } - - public Map> getEdgeRankScores() { - return edgeRankScores; - } - - /** - * @return the rankScores - */ - public Map getVertexRankScores(Object key) { - return vertexRankScores.get(key); - } - - public Map getEdgeRankScores(Object key) { - return edgeRankScores.get(key); - } - - protected Collection getVertices() { - return mGraph.getVertices(); - } - - protected int getVertexCount() { - return mGraph.getVertexCount(); - } - - protected Graph getGraph() { - return mGraph; - } - - @Override - public void reset() { - } - - /** - * Returns true if this ranker ranks nodes, and - * false otherwise. - */ - public boolean isRankingNodes() { - return mRankNodes; - } - - /** - * Returns true if this ranker ranks edges, and - * false otherwise. - */ - public boolean isRankingEdges() { - return mRankEdges; - } - - /** - * Instructs the ranker whether or not it should remove the rank scores from the nodes (or edges) once the ranks - * have been computed. - * @param removeRankScoresOnFinalize true if the rank scores are to be removed, false otherwise - */ - public void setRemoveRankScoresOnFinalize(boolean removeRankScoresOnFinalize) { - this.mRemoveRankScoresOnFinalize = removeRankScoresOnFinalize; - } - - protected void onFinalize(Object e) {} - - /** - * The user datum key used to store the rank score. - * @return the key - */ - abstract public Object getRankScoreKey(); - - - @Override - protected void finalizeIterations() { - List> sortedRankings = new ArrayList>(); - - int id = 1; - if (mRankNodes) { - for (V currentVertex : getVertices()) { - Ranking ranking = new Ranking(id,getVertexRankScore(currentVertex),currentVertex); - sortedRankings.add(ranking); - if (mRemoveRankScoresOnFinalize) { - this.vertexRankScores.get(getRankScoreKey()).remove(currentVertex); - } - id++; - onFinalize(currentVertex); - } - } - if (mRankEdges) { - for (E currentEdge : mGraph.getEdges()) { - - Ranking ranking = new Ranking(id,getEdgeRankScore(currentEdge),currentEdge); - sortedRankings.add(ranking); - if (mRemoveRankScoresOnFinalize) { - this.edgeRankScores.get(getRankScoreKey()).remove(currentEdge); - } - id++; - onFinalize(currentEdge); - } - } - - mRankings = sortedRankings; - Collections.sort(mRankings); - } - - /** - * Retrieves the list of ranking instances in descending sorted order by rank score - * If the algorithm is ranking edges, the instances will be of type EdgeRanking, otherwise - * if the algorithm is ranking nodes the instances will be of type NodeRanking - * @return the list of rankings - */ - public List> getRankings() { - return mRankings; - } - - /** - * Return a list of the top k rank scores. - * @param topKRankings the value of k to use - * @return list of rank scores - */ - public List getRankScores(int topKRankings) { - List scores = new ArrayList(); - int count=1; - for (Ranking currentRanking : getRankings()) { - if (count > topKRankings) { - return scores; - } - scores.add(currentRanking.rankScore); - count++; - } - - return scores; - } - - /** - * Given an edge or node, returns the corresponding rank score. This is a default - * implementation of getRankScore which assumes the decorations are of type MutableDouble. - * This method only returns legal values if setRemoveRankScoresOnFinalize(false) was called - * prior to evaluate(). - * @return the rank score value - */ - public double getVertexRankScore(V v) { - Number rankScore = vertexRankScores.get(getRankScoreKey()).get(v); - if (rankScore != null) { - return rankScore.doubleValue(); - } else { - throw new RuntimeException("setRemoveRankScoresOnFinalize(false) must be called before evaluate()."); - } - } - - public double getVertexRankScore(V v, Object key) { - return vertexRankScores.get(key).get(v).doubleValue(); - } - - public double getEdgeRankScore(E e) { - Number rankScore = edgeRankScores.get(getRankScoreKey()).get(e); - if (rankScore != null) { - return rankScore.doubleValue(); - } else { - throw new RuntimeException("setRemoveRankScoresOnFinalize(false) must be called before evaluate()."); - } - } - - public double getEdgeRankScore(E e, Object key) { - return edgeRankScores.get(key).get(e).doubleValue(); - } - - protected void setVertexRankScore(V v, double rankValue, Object key) { - vertexRankScores.get(key).put(v, rankValue); - } - - protected void setEdgeRankScore(E e, double rankValue, Object key) { - edgeRankScores.get(key).put(e, rankValue); - } - - protected void setVertexRankScore(V v, double rankValue) { - setVertexRankScore(v,rankValue, getRankScoreKey()); - } - - protected void setEdgeRankScore(E e, double rankValue) { - setEdgeRankScore(e, rankValue, getRankScoreKey()); - } - - protected void removeVertexRankScore(V v, Object key) { - vertexRankScores.get(key).remove(v); - } - - protected void removeEdgeRankScore(E e, Object key) { - edgeRankScores.get(key).remove(e); - } - - protected void removeVertexRankScore(V v) { - vertexRankScores.get(getRankScoreKey()).remove(v); - } - - protected void removeEdgeRankScore(E e) { - edgeRankScores.get(getRankScoreKey()).remove(e); - } - - protected double getEdgeWeight(E e) { - return edgeWeights.get(e).doubleValue(); - } - - protected void setEdgeWeight(E e, double weight) { - edgeWeights.put(e, weight); - } - - public void setEdgeWeights(Map edgeWeights) { - this.edgeWeights = edgeWeights; - } - - /** - * @return the edgeWeights - */ - public Map getEdgeWeights() { - return edgeWeights; - } - - protected void assignDefaultEdgeTransitionWeights() { - - for (V currentVertex : getVertices()) { - - Collection outgoingEdges = mGraph.getOutEdges(currentVertex); - - double numOutEdges = outgoingEdges.size(); - for (E currentEdge : outgoingEdges) { - setEdgeWeight(currentEdge,1.0/numOutEdges); - } - } - } - - protected void normalizeEdgeTransitionWeights() { - - for (V currentVertex : getVertices()) { - - Collection outgoingEdges = mGraph.getOutEdges(currentVertex); - - double totalEdgeWeight = 0; - for (E currentEdge : outgoingEdges) { - totalEdgeWeight += getEdgeWeight(currentEdge); - } - - for (E currentEdge : outgoingEdges) { - setEdgeWeight(currentEdge,getEdgeWeight(currentEdge)/totalEdgeWeight); - } - } - } - - protected void normalizeRankings() { - if (!mNormalizeRankings) { - return; - } - double totalWeight = 0; - - for (V currentVertex : getVertices()) { - totalWeight += getVertexRankScore(currentVertex); - } - - for (V currentVertex : getVertices()) { - setVertexRankScore(currentVertex,getVertexRankScore(currentVertex)/totalWeight); - } - } - - /** - * Print the rankings to standard out in descending order of rank score - * @param verbose if true, include information about the actual rank order as well as - * the original position of the vertex before it was ranked - * @param printScore if true, include the actual value of the rank score - */ - public void printRankings(boolean verbose,boolean printScore) { - double total = 0; - Format formatter = new DecimalFormat("#0.#######"); - int rank = 1; - - for (Ranking currentRanking : getRankings()) { - double rankScore = currentRanking.rankScore; - if (verbose) { - System.out.print("Rank " + rank + ": "); - if (printScore) { - System.out.print(formatter.format(rankScore)); - } - System.out.print("\tVertex Id: " + currentRanking.originalPos); - System.out.print(" (" + currentRanking.getRanked() + ")"); - System.out.println(); - } else { - System.out.print(rank + "\t"); - if (printScore) { - System.out.print(formatter.format(rankScore)); - } - System.out.println("\t" + currentRanking.originalPos); - - } - total += rankScore; - rank++; - } - - if (verbose) { - System.out.println("Total: " + formatter.format(total)); - } - } - - /** - * Allows the user to specify whether or not s/he wants the rankings to be normalized. - * In some cases, this will have no effect since the algorithm doesn't allow normalization - * as an option - * @param normalizeRankings - */ - public void setNormalizeRankings(boolean normalizeRankings) { - mNormalizeRankings = normalizeRankings; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/BetweennessCentrality.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/BetweennessCentrality.java deleted file mode 100644 index 25906f206a..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/BetweennessCentrality.java +++ /dev/null @@ -1,190 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.importance; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import org.apache.commons.collections15.Buffer; -import org.apache.commons.collections15.buffer.UnboundedFifoBuffer; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.UndirectedGraph; - -/** - * Computes betweenness centrality for each vertex and edge in the graph. The result is that each vertex - * and edge has a UserData element of type MutableDouble whose key is 'centrality.BetweennessCentrality'. - * Note: Many social network researchers like to normalize the betweenness values by dividing the values by - * (n-1)(n-2)/2. The values given here are unnormalized.

        - * - * A simple example of usage is: - *

        - * BetweennessCentrality ranker = new BetweennessCentrality(someGraph);
        - * ranker.evaluate();
        - * ranker.printRankings();
        - * 
        - * - * Running time is: O(n^2 + nm). - * @see "Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001." - * @author Scott White - * @author Tom Nelson converted to jung2 - */ - -public class BetweennessCentrality extends AbstractRanker { - - public static final String CENTRALITY = "centrality.BetweennessCentrality"; - - /** - * Constructor which initializes the algorithm - * @param g the graph whose nodes are to be analyzed - */ - public BetweennessCentrality(Graph g) { - initialize(g, true, true); - } - - public BetweennessCentrality(Graph g, boolean rankNodes) { - initialize(g, rankNodes, true); - } - - public BetweennessCentrality(Graph g, boolean rankNodes, boolean rankEdges) - { - initialize(g, rankNodes, rankEdges); - } - - protected void computeBetweenness(Graph graph) { - - Map decorator = new HashMap(); - Map bcVertexDecorator = - vertexRankScores.get(getRankScoreKey()); - bcVertexDecorator.clear(); - Map bcEdgeDecorator = - edgeRankScores.get(getRankScoreKey()); - bcEdgeDecorator.clear(); - - Collection vertices = graph.getVertices(); - - for (V s : vertices) { - - initializeData(graph,decorator); - - decorator.get(s).numSPs = 1; - decorator.get(s).distance = 0; - - Stack stack = new Stack(); - Buffer queue = new UnboundedFifoBuffer(); - queue.add(s); - - while (!queue.isEmpty()) { - V v = queue.remove(); - stack.push(v); - - for(V w : getGraph().getSuccessors(v)) { - - if (decorator.get(w).distance < 0) { - queue.add(w); - decorator.get(w).distance = decorator.get(v).distance + 1; - } - - if (decorator.get(w).distance == decorator.get(v).distance + 1) { - decorator.get(w).numSPs += decorator.get(v).numSPs; - decorator.get(w).predecessors.add(v); - } - } - } - - while (!stack.isEmpty()) { - V w = stack.pop(); - - for (V v : decorator.get(w).predecessors) { - - double partialDependency = (decorator.get(v).numSPs / decorator.get(w).numSPs); - partialDependency *= (1.0 + decorator.get(w).dependency); - decorator.get(v).dependency += partialDependency; - E currentEdge = getGraph().findEdge(v, w); - double edgeValue = bcEdgeDecorator.get(currentEdge).doubleValue(); - edgeValue += partialDependency; - bcEdgeDecorator.put(currentEdge, edgeValue); - } - if (w != s) { - double bcValue = bcVertexDecorator.get(w).doubleValue(); - bcValue += decorator.get(w).dependency; - bcVertexDecorator.put(w, bcValue); - } - } - } - - if(graph instanceof UndirectedGraph) { - for (V v : vertices) { - double bcValue = bcVertexDecorator.get(v).doubleValue(); - bcValue /= 2.0; - bcVertexDecorator.put(v, bcValue); - } - for (E e : graph.getEdges()) { - double bcValue = bcEdgeDecorator.get(e).doubleValue(); - bcValue /= 2.0; - bcEdgeDecorator.put(e, bcValue); - } - } - - for (V vertex : vertices) { - decorator.remove(vertex); - } - } - - private void initializeData(Graph g, Map decorator) { - for (V vertex : g.getVertices()) { - - Map bcVertexDecorator = vertexRankScores.get(getRankScoreKey()); - if(bcVertexDecorator.containsKey(vertex) == false) { - bcVertexDecorator.put(vertex, 0.0); - } - decorator.put(vertex, new BetweennessData()); - } - for (E e : g.getEdges()) { - - Map bcEdgeDecorator = edgeRankScores.get(getRankScoreKey()); - if(bcEdgeDecorator.containsKey(e) == false) { - bcEdgeDecorator.put(e, 0.0); - } - } - } - - /** - * the user datum key used to store the rank scores - * @return the key - */ - @Override - public String getRankScoreKey() { - return CENTRALITY; - } - - @Override - public void step() { - computeBetweenness(getGraph()); - } - - class BetweennessData { - double distance; - double numSPs; - List predecessors; - double dependency; - - BetweennessData() { - distance = -1; - numSPs = 0; - predecessors = new ArrayList(); - dependency = 0; - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/KStepMarkov.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/KStepMarkov.java deleted file mode 100644 index 9ee4030ce3..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/KStepMarkov.java +++ /dev/null @@ -1,135 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.importance; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import edu.uci.ics.jung.graph.DirectedGraph; - - -/** - * Algorithm variant of PageRankWithPriors that computes the importance of a node based upon taking fixed-length random - * walks out from the root set and then computing the stationary probability of being at each node. Specifically, it computes - * the relative probability that the markov chain will spend at any particular node, given that it start in the root - * set and ends after k steps. - *

        - * A simple example of usage is: - *

        - * KStepMarkov ranker = new KStepMarkov(someGraph,rootSet,6,null);
        - * ranker.evaluate();
        - * ranker.printRankings();
        - * 
        - *

        - * - * @author Scott White - * @author Tom Nelson - adapter to jung2 - * @see "Algorithms for Estimating Relative Importance in Graphs by Scott White and Padhraic Smyth, 2003" - */ -public class KStepMarkov extends RelativeAuthorityRanker { - public final static String RANK_SCORE = "jung.algorithms.importance.KStepMarkovExperimental.RankScore"; - private final static String CURRENT_RANK = "jung.algorithms.importance.KStepMarkovExperimental.CurrentRank"; - private int mNumSteps; - HashMap mPreviousRankingsMap; - - /** - * Construct the algorihm instance and initializes the algorithm. - * @param graph the graph to be analyzed - * @param priors the set of root nodes - * @param k positive integer parameter which controls the relative tradeoff between a distribution "biased" towards - * R and the steady-state distribution which is independent of where the Markov-process started. Generally values - * between 4-8 are reasonable - * @param edgeWeights the weight for each edge - */ - public KStepMarkov(DirectedGraph graph, Set priors, int k, Map edgeWeights) { - super.initialize(graph,true,false); - mNumSteps = k; - setPriors(priors); - initializeRankings(); - if (edgeWeights == null) { - assignDefaultEdgeTransitionWeights(); - } else { - setEdgeWeights(edgeWeights); - } - normalizeEdgeTransitionWeights(); - } - - /** - * The user datum key used to store the rank scores. - * @return the key - */ - @Override - public String getRankScoreKey() { - return RANK_SCORE; - } - - protected void incrementRankScore(V v, double rankValue) { - double value = getVertexRankScore(v, RANK_SCORE); - value += rankValue; - setVertexRankScore(v, value, RANK_SCORE); - } - - protected double getCurrentRankScore(V v) { - return getVertexRankScore(v, CURRENT_RANK); - } - - protected void setCurrentRankScore(V v, double rankValue) { - setVertexRankScore(v, rankValue, CURRENT_RANK); - } - - protected void initializeRankings() { - mPreviousRankingsMap = new HashMap(); - for (V v : getVertices()) { - Set priors = getPriors(); - double numPriors = priors.size(); - - if (getPriors().contains(v)) { - setVertexRankScore(v, 1.0/ numPriors); - setCurrentRankScore(v, 1.0/ numPriors); - mPreviousRankingsMap.put(v,1.0/numPriors); - } else { - setVertexRankScore(v, 0); - setCurrentRankScore(v, 0); - mPreviousRankingsMap.put(v, 0); - } - } - } - @Override - public void step() { - - for (int i=0;i incomingEdges = getGraph().getInEdges(v); - - double currentPageRankSum = 0; - for (E e : incomingEdges) { - double currentWeight = getEdgeWeight(e); - currentPageRankSum += - mPreviousRankingsMap.get(getGraph().getOpposite(v,e)).doubleValue()*currentWeight; - } - setCurrentRankScore(v,currentPageRankSum); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/Ranking.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/Ranking.java deleted file mode 100644 index b96e559341..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/Ranking.java +++ /dev/null @@ -1,77 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.importance; - - -/** - * Abstract data container for ranking objects. Stores common data relevant to both node and edge rankings, namely, - * the original position of the instance in the list and the actual ranking score. - * @author Scott White - */ -public class Ranking implements Comparable { - /** - * The original (0-indexed) position of the instance being ranked - */ - public int originalPos; - /** - * The actual rank score (normally between 0 and 1) - */ - public double rankScore; - - /** - * what is being ranked - */ - private V ranked; - - /** - * Constructor which allows values to be set on construction - * @param originalPos The original (0-indexed) position of the instance being ranked - * @param rankScore The actual rank score (normally between 0 and 1) - */ - public Ranking(int originalPos, double rankScore, V ranked) { - this.originalPos = originalPos; - this.rankScore = rankScore; - this.ranked = ranked; - } - - /** - * Compares two ranking based on the rank score. - * @param o The other ranking - * @return -1 if the other ranking is higher, 0 if they are equal, and 1 if this ranking is higher - */ - public int compareTo(Object o) { - - Ranking otherRanking = (Ranking) o; - return Double.compare(otherRanking.rankScore,rankScore); - } - - /** - * Returns the rank score as a string. - * @return the stringified rank score - */ - @Override - public String toString() { - return String.valueOf(rankScore); - } - - /** - * @return the ranked - */ - public V getRanked() { - return ranked; - } - - /** - * @param ranked the ranked to set - */ - public void setRanked(V ranked) { - this.ranked = ranked; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/RelativeAuthorityRanker.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/RelativeAuthorityRanker.java deleted file mode 100644 index b40ba8d4a6..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/RelativeAuthorityRanker.java +++ /dev/null @@ -1,73 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.importance; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - - -/** - * This class provides basic infrastructure for relative authority algorithms that compute the importance of nodes - * relative to one or more root nodes. The services provided are: - *

          - *
        • The set of root nodes (priors) is stored and maintained
        • - *
        • Getters and setters for the prior rank score are provided
        • - *
        - * - * @author Scott White - */ -public abstract class RelativeAuthorityRanker extends AbstractRanker { - private Set mPriors; - /** - * The default key used for the user datum key corresponding to prior rank scores. - */ - - protected Map priorRankScoreMap = new HashMap(); - /** - * Cleans up all of the prior rank scores on finalize. - */ - @Override - protected void finalizeIterations() { - super.finalizeIterations(); - priorRankScoreMap.clear(); - } - - /** - * Retrieves the value of the prior rank score. - * @param v the root node (prior) - * @return the prior rank score - */ - protected double getPriorRankScore(V v) { - return priorRankScoreMap.get(v).doubleValue(); - - } - - /** - * Allows the user to specify a value to set for the prior rank score - * @param v the root node (prior) - * @param value the score to set to - */ - public void setPriorRankScore(V v, double value) { - this.priorRankScoreMap.put(v, value); - } - - /** - * Retrieves the set of priors. - * @return the set of root nodes (priors) - */ - protected Set getPriors() { return mPriors; } - - /** - * Specifies which vertices are root nodes (priors). - * @param priors the root nodes - */ - protected void setPriors(Set priors) { mPriors = priors; } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/WeightedNIPaths.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/WeightedNIPaths.java deleted file mode 100644 index bd715ce7ed..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/importance/WeightedNIPaths.java +++ /dev/null @@ -1,194 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.importance; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.graph.DirectedGraph; - - - -/** - * This algorithm measures the importance of nodes based upon both the number and length of disjoint paths that lead - * to a given node from each of the nodes in the root set. Specifically the formula for measuring the importance of a - * node is given by: I(t|R) = sum_i=1_|P(r,t)|_{alpha^|p_i|} where alpha is the path decay coefficient, p_i is path i - * and P(r,t) is a set of maximum-sized node-disjoint paths from r to t. - *

        - * This algorithm uses heuristic breadth-first search to try and find the maximum-sized set of node-disjoint paths - * between two nodes. As such, it is not guaranteed to give exact answers. - *

        - * A simple example of usage is: - *

        - * WeightedNIPaths ranker = new WeightedNIPaths(someGraph,2.0,6,rootSet);
        - * ranker.evaluate();
        - * ranker.printRankings();
        - * 
        - * - * @author Scott White - * @see "Algorithms for Estimating Relative Importance in Graphs by Scott White and Padhraic Smyth, 2003" - */ -public class WeightedNIPaths extends AbstractRanker { - public final static String WEIGHTED_NIPATHS_KEY = "jung.algorithms.importance.WEIGHTED_NIPATHS_KEY"; - private double mAlpha; - private int mMaxDepth; - private Set mPriors; - private Map pathIndices = new HashMap(); - private Map roots = new HashMap(); - private Map> pathsSeenMap = new HashMap>(); - private Factory vertexFactory; - private Factory edgeFactory; - - /** - * Constructs and initializes the algorithm. - * @param graph the graph whose nodes are being measured for their importance - * @param alpha the path decay coefficient (>= 1); 2 is recommended - * @param maxDepth the maximal depth to search out from the root set - * @param priors the root set (starting vertices) - */ - public WeightedNIPaths(DirectedGraph graph, Factory vertexFactory, - Factory edgeFactory, double alpha, int maxDepth, Set priors) { - super.initialize(graph, true,false); - this.vertexFactory = vertexFactory; - this.edgeFactory = edgeFactory; - mAlpha = alpha; - mMaxDepth = maxDepth; - mPriors = priors; - for (V v : graph.getVertices()) { - super.setVertexRankScore(v, 0.0); - } - } - - protected void incrementRankScore(V v, double rankValue) { - setVertexRankScore(v, getVertexRankScore(v) + rankValue); - } - - protected void computeWeightedPathsFromSource(V root, int depth) { - - int pathIdx = 1; - - for (E e : getGraph().getOutEdges(root)) { - this.pathIndices.put(e, pathIdx); - this.roots.put(e, root); - newVertexEncountered(pathIdx, getGraph().getEndpoints(e).getSecond(), root); - pathIdx++; - } - - List edges = new ArrayList(); - - V virtualNode = vertexFactory.create(); - getGraph().addVertex(virtualNode); - E virtualSinkEdge = edgeFactory.create(); - - getGraph().addEdge(virtualSinkEdge, virtualNode, root); - edges.add(virtualSinkEdge); - - int currentDepth = 0; - while (currentDepth <= depth) { - - double currentWeight = Math.pow(mAlpha, -1.0 * currentDepth); - for (E currentEdge : edges) { - incrementRankScore(getGraph().getEndpoints(currentEdge).getSecond(),// - currentWeight); - } - - if ((currentDepth == depth) || (edges.size() == 0)) break; - - List newEdges = new ArrayList(); - - for (E currentSourceEdge : edges) { //Iterator sourceEdgeIt = edges.iterator(); sourceEdgeIt.hasNext();) { - Number sourcePathIndex = this.pathIndices.get(currentSourceEdge); - - // from the currentSourceEdge, get its opposite end - // then iterate over the out edges of that opposite end - V newDestVertex = getGraph().getEndpoints(currentSourceEdge).getSecond(); - Collection outs = getGraph().getOutEdges(newDestVertex); - for (E currentDestEdge : outs) { - V destEdgeRoot = this.roots.get(currentDestEdge); - V destEdgeDest = getGraph().getEndpoints(currentDestEdge).getSecond(); - - if (currentSourceEdge == virtualSinkEdge) { - newEdges.add(currentDestEdge); - continue; - } - if (destEdgeRoot == root) { - continue; - } - if (destEdgeDest == getGraph().getEndpoints(currentSourceEdge).getFirst()) {//currentSourceEdge.getSource()) { - continue; - } - Set pathsSeen = this.pathsSeenMap.get(destEdgeDest); - - if (pathsSeen == null) { - newVertexEncountered(sourcePathIndex.intValue(), destEdgeDest, root); - } else if (roots.get(destEdgeDest) != root) { - roots.put(destEdgeDest,root); - pathsSeen.clear(); - pathsSeen.add(sourcePathIndex); - } else if (!pathsSeen.contains(sourcePathIndex)) { - pathsSeen.add(sourcePathIndex); - } else { - continue; - } - - this.pathIndices.put(currentDestEdge, sourcePathIndex); - this.roots.put(currentDestEdge, root); - newEdges.add(currentDestEdge); - } - } - - edges = newEdges; - currentDepth++; - } - - getGraph().removeVertex(virtualNode); - } - - private void newVertexEncountered(int sourcePathIndex, V dest, V root) { - Set pathsSeen = new HashSet(); - pathsSeen.add(sourcePathIndex); - this.pathsSeenMap.put(dest, pathsSeen); - roots.put(dest, root); - } - - @Override - public void step() { - for (V v : mPriors) { - computeWeightedPathsFromSource(v, mMaxDepth); - } - - normalizeRankings(); -// return 0; - } - - /** - * Given a node, returns the corresponding rank score. This implementation of getRankScore assumes - * the decoration representing the rank score is of type MutableDouble. - * @return the rank score for this node - */ - @Override - public String getRankScoreKey() { - return WEIGHTED_NIPATHS_KEY; - } - - @Override - protected void onFinalize(Object udc) { - pathIndices.remove(udc); - roots.remove(udc); - pathsSeenMap.remove(udc); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/AbstractLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/AbstractLayout.java deleted file mode 100644 index b59dcfaa4c..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/AbstractLayout.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * Created on Jul 7, 2003 - * - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.functors.ChainedTransformer; -import org.apache.commons.collections15.functors.CloneTransformer; -import org.apache.commons.collections15.map.LazyMap; - -import edu.uci.ics.jung.graph.Graph; - -/** - * Abstract class for implementations of {@code Layout}. It handles some of the - * basic functions: storing coordinates, maintaining the dimensions, initializing - * the locations, maintaining locked vertices. - * - * @author Danyel Fisher, Scott White - * @author Tom Nelson - converted to jung2 - * @param the vertex type - * @param the edge type - */ -abstract public class AbstractLayout implements Layout { - - /** - * a set of vertices that should not move in relation to the - * other vertices - */ - private Set dontmove = new HashSet(); - - protected Dimension size; - protected Graph graph; - protected boolean initialized; - - protected Map locations = - LazyMap.decorate(new HashMap(), - new Transformer() { - public Point2D transform(V arg0) { - return new Point2D.Double(); - }}); - - - /** - * Creates an instance which does not initialize the vertex locations. - * - * @param graph the graph for which the layout algorithm is to be created. - */ - protected AbstractLayout(Graph graph) { - if (graph == null) - { - throw new IllegalArgumentException("Graph must be non-null"); - } - this.graph = graph; - } - - @SuppressWarnings("unchecked") - protected AbstractLayout(Graph graph, Transformer initializer) { - this.graph = graph; - Transformer chain = - ChainedTransformer.getInstance(initializer, CloneTransformer.getInstance()); - this.locations = LazyMap.decorate(new HashMap(), (Transformer)chain); - initialized = true; - } - - protected AbstractLayout(Graph graph, Dimension size) { - this.graph = graph; - this.size = size; - } - - @SuppressWarnings("unchecked") - protected AbstractLayout(Graph graph, Transformer initializer, Dimension size) { - this.graph = graph; - Transformer chain = - ChainedTransformer.getInstance(initializer, CloneTransformer.getInstance()); - this.locations = LazyMap.decorate(new HashMap(), (Transformer)chain); - this.size = size; - } - - public void setGraph(Graph graph) { - this.graph = graph; - if(size != null && graph != null) { - initialize(); - } - } - - /** - * When a visualization is resized, it presumably wants to fix the - * locations of the vertices and possibly to reinitialize its data. The - * current method calls initializeLocations followed by initialize_local. - */ - public void setSize(Dimension size) { - - if(size != null && graph != null) { - - Dimension oldSize = this.size; - this.size = size; - initialize(); - - if(oldSize != null) { - adjustLocations(oldSize, size); - } - } - } - - private void adjustLocations(Dimension oldSize, Dimension size) { - - int xOffset = (size.width - oldSize.width) / 2; - int yOffset = (size.height - oldSize.height) / 2; - - // now, move each vertex to be at the new screen center - while(true) { - try { - for(V v : getGraph().getVertices()) { - offsetVertex(v, xOffset, yOffset); - } - break; - } catch(ConcurrentModificationException cme) { - } - } - } - - public boolean isLocked(V v) { - return dontmove.contains(v); - } - - @SuppressWarnings("unchecked") - public void setInitializer(Transformer initializer) { - if(this.equals(initializer)) { - throw new IllegalArgumentException("Layout cannot be initialized with itself"); - } - Transformer chain = - ChainedTransformer.getInstance(initializer, CloneTransformer.getInstance()); - this.locations = LazyMap.decorate(new HashMap(), (Transformer)chain); - initialized = true; - } - - /** - * Returns the current size of the visualization space, accoring to the - * last call to resize(). - * - * @return the current size of the screen - */ - public Dimension getSize() { - return size; - } - - /** - * Returns the Coordinates object that stores the vertex' x and y location. - * - * @param v - * A Vertex that is a part of the Graph being visualized. - * @return A Coordinates object with x and y locations. - */ - private Point2D getCoordinates(V v) { - return locations.get(v); - } - - public Point2D transform(V v) { - return getCoordinates(v); - } - - /** - * Returns the x coordinate of the vertex from the Coordinates object. - * in most cases you will be better off calling transform(v). - */ - public double getX(V v) { - assert getCoordinates(v) != null : "Cannot getX for an unmapped vertex "+v; - return getCoordinates(v).getX(); - } - - /** - * Returns the y coordinate of the vertex from the Coordinates object. - * In most cases you will be better off calling transform(v). - */ - public double getY(V v) { - assert getCoordinates(v) != null : "Cannot getY for an unmapped vertex "+v; - return getCoordinates(v).getY(); - } - - /** - * @param v - * @param xOffset - * @param yOffset - */ - protected void offsetVertex(V v, double xOffset, double yOffset) { - Point2D c = getCoordinates(v); - c.setLocation(c.getX()+xOffset, c.getY()+yOffset); - setLocation(v, c); - } - - /** - * Accessor for the graph that represets all vertices. - * - * @return the graph that contains all vertices. - */ - public Graph getGraph() { - return graph; - } - - /** - * Forcibly moves a vertex to the (x,y) location by setting its x and y - * locations to the inputted location. Does not add the vertex to the - * "dontmove" list, and (in the default implementation) does not make any - * adjustments to the rest of the graph. - */ - public void setLocation(V picked, double x, double y) { - Point2D coord = getCoordinates(picked); - coord.setLocation(x, y); - } - - public void setLocation(V picked, Point2D p) { - Point2D coord = getCoordinates(picked); - coord.setLocation(p); - } - - /** - * Locks {@code v} in place if {@code state} is {@code true}, otherwise unlocks it. - */ - public void lock(V v, boolean state) { - if(state == true) - dontmove.add(v); - else - dontmove.remove(v); - } - - /** - * Locks all vertices in place if {@code lock} is {@code true}, otherwise unlocks all vertices. - */ - public void lock(boolean lock) { - for(V v : graph.getVertices()) { - lock(v, lock); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/AggregateLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/AggregateLayout.java deleted file mode 100644 index 38058377a1..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/AggregateLayout.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * - * - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.util.IterativeContext; -import edu.uci.ics.jung.graph.Graph; - -/** - * A {@code Layout} implementation that combines - * multiple other layouts so that they may be manipulated - * as one layout. The relaxer thread will step each layout - * in sequence. - * - * @author Tom Nelson - tomnelson@dev.java.net - * - * @param the vertex type - * @param the edge type - */ -public class AggregateLayout implements Layout, IterativeContext { - - protected Layout delegate; - protected Map,Point2D> layouts = new HashMap,Point2D>(); - - /** - * Creates an instance backed by the specified {@code delegate}. - * @param delegate - */ - public AggregateLayout(Layout delegate) { - this.delegate = delegate; - } - - /** - * @return the delegate - */ - public Layout getDelegate() { - return delegate; - } - - /** - * @param delegate the delegate to set - */ - public void setDelegate(Layout delegate) { - this.delegate = delegate; - } - - /** - * adds the passed layout as a sublayout, also specifying - * the center of where this sublayout should appear - * @param layout - * @param center - */ - public void put(Layout layout, Point2D center) { - layouts.put(layout,center); - } - - /** - * Returns the center of the passed layout. - * @param layout - * @return the center of the passed layout - */ - public Point2D get(Layout layout) { - return layouts.get(layout); - } - - /** - * Removes {@code layout} from this instance. - */ - public void remove(Layout layout) { - layouts.remove(layout); - } - - /** - * Removes all layouts from this instance. - */ - public void removeAll() { - layouts.clear(); - } - - /** - * Returns the graph for which this layout is defined. - * @return the graph for which this layout is defined - * @see edu.uci.ics.jung.algorithms.layout.Layout#getGraph() - */ - public Graph getGraph() { - return delegate.getGraph(); - } - - /** - * Returns the size of the underlying layout. - * @return the size of the underlying layout - * @see edu.uci.ics.jung.algorithms.layout.Layout#getSize() - */ - public Dimension getSize() { - return delegate.getSize(); - } - - /** - * - * @see edu.uci.ics.jung.algorithms.layout.Layout#initialize() - */ - public void initialize() { - delegate.initialize(); - for(Layout layout : layouts.keySet()) { - layout.initialize(); - } - } - - /** - * Override to test if the passed vertex is locked in - * any of the layouts. - * @param v - * @return true if v is locked in any of the layouts, and false otherwise - * @see edu.uci.ics.jung.algorithms.layout.Layout#isLocked(java.lang.Object) - */ - public boolean isLocked(V v) { - boolean locked = false; - for(Layout layout : layouts.keySet()) { - locked |= layout.isLocked(v); - } - locked |= delegate.isLocked(v); - return locked; - } - - /** - * override to lock or unlock this vertex in any layout with - * a subgraph containing it - * @param v - * @param state - * @see edu.uci.ics.jung.algorithms.layout.Layout#lock(java.lang.Object, boolean) - */ - public void lock(V v, boolean state) { - for(Layout layout : layouts.keySet()) { - if(layout.getGraph().getVertices().contains(v)) { - layout.lock(v, state); - } - } - delegate.lock(v, state); - } - - /** - * - * @see edu.uci.ics.jung.algorithms.layout.Layout#reset() - */ - public void reset() { - for(Layout layout : layouts.keySet()) { - layout.reset(); - } - delegate.reset(); - } - - /** - * @param graph - * @see edu.uci.ics.jung.algorithms.layout.Layout#setGraph(edu.uci.ics.jung.graph.Graph) - */ - public void setGraph(Graph graph) { - delegate.setGraph(graph); - } - - /** - * @param initializer - * @see edu.uci.ics.jung.algorithms.layout.Layout#setInitializer(org.apache.commons.collections15.Transformer) - */ - public void setInitializer(Transformer initializer) { - delegate.setInitializer(initializer); - } - - /** - * @param v - * @param location - * @see edu.uci.ics.jung.algorithms.layout.Layout#setLocation(java.lang.Object, java.awt.geom.Point2D) - */ - public void setLocation(V v, Point2D location) { - boolean wasInSublayout = false; - for(Layout layout : layouts.keySet()) { - if(layout.getGraph().getVertices().contains(v)) { - Point2D center = layouts.get(layout); - // transform by the layout itself, but offset to the - // center of the sublayout - Dimension d = layout.getSize(); - - AffineTransform at = - AffineTransform.getTranslateInstance(-center.getX()+d.width/2,-center.getY()+d.height/2); - Point2D localLocation = at.transform(location, null); - layout.setLocation(v, localLocation); - wasInSublayout = true; - } - } - if(wasInSublayout == false && getGraph().getVertices().contains(v)) { - delegate.setLocation(v, location); - } - } - - /** - * @param d - * @see edu.uci.ics.jung.algorithms.layout.Layout#setSize(java.awt.Dimension) - */ - public void setSize(Dimension d) { - delegate.setSize(d); - } - - /** - * Returns a map from each {@code Layout} instance to its center point. - */ - public Map,Point2D> getLayouts() { - return layouts; - } - - /** - * Returns the location of the vertex. The location is specified first - * by the sublayouts, and then by the base layout if no sublayouts operate - * on this vertex. - * @return the location of the vertex - * @see org.apache.commons.collections15.Transformer#transform(java.lang.Object) - */ - public Point2D transform(V v) { - boolean wasInSublayout = false; - for(Layout layout : layouts.keySet()) { - if(layout.getGraph().getVertices().contains(v)) { - wasInSublayout = true; - Point2D center = layouts.get(layout); - // transform by the layout itself, but offset to the - // center of the sublayout - Dimension d = layout.getSize(); - AffineTransform at = - AffineTransform.getTranslateInstance(center.getX()-d.width/2, - center.getY()-d.height/2); - return at.transform(layout.transform(v),null); - } - } - if(wasInSublayout == false) { - return delegate.transform(v); - } - return null; - - } - - /** - * Check all sublayouts.keySet() and the delegate layout, returning - * done == true iff all are done. - */ - public boolean done() { - boolean done = true; - for(Layout layout : layouts.keySet()) { - if(layout instanceof IterativeContext) { - done &= ((IterativeContext)layout).done(); - } - } - if(delegate instanceof IterativeContext) { - done &= ((IterativeContext)delegate).done(); - } - return done; - } - - /** - * call step on any sublayout that is also an IterativeContext - * and is not done - */ - public void step() { - for(Layout layout : layouts.keySet()) { - if(layout instanceof IterativeContext) { - IterativeContext context = (IterativeContext)layout; - if(context.done() == false) { - context.step(); - } - } - } - if(delegate instanceof IterativeContext) { - IterativeContext context = (IterativeContext)delegate; - if(context.done() == false) { - context.step(); - } - } - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/BalloonLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/BalloonLayout.java deleted file mode 100644 index 1d9f384ae7..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/BalloonLayout.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2005, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * Created on Jul 9, 2005 - */ - -package edu.uci.ics.jung.algorithms.layout; -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.map.LazyMap; - -import edu.uci.ics.jung.graph.Forest; -import edu.uci.ics.jung.graph.util.TreeUtils; - -/** - * A {@code Layout} implementation that assigns positions to {@code Tree} or - * {@code Forest} vertices using associations with nested circles ("balloons"). - * A balloon is nested inside another balloon if the first balloon's subtree - * is a subtree of the second balloon's subtree. - * - * @author Tom Nelson - * - */ -public class BalloonLayout extends TreeLayout { - - protected Map polarLocations = - LazyMap.decorate(new HashMap(), - new Transformer() { - public PolarPoint transform(V arg0) { - return new PolarPoint(); - }}); - - protected Map radii = new HashMap(); - - /** - * Creates an instance based on the input forest. - */ - public BalloonLayout(Forest g) - { - super(g); - } - - protected void setRootPolars() - { - List roots = TreeUtils.getRoots(graph); - if(roots.size() == 1) { - // its a Tree - V root = roots.get(0); - setRootPolar(root); - setPolars(new ArrayList(graph.getChildren(root)), - getCenter(), getSize().width/2); - } else if (roots.size() > 1) { - // its a Forest - setPolars(roots, getCenter(), getSize().width/2); - } - } - - protected void setRootPolar(V root) { - PolarPoint pp = new PolarPoint(0,0); - Point2D p = getCenter(); - polarLocations.put(root, pp); - locations.put(root, p); - } - - - protected void setPolars(List kids, Point2D parentLocation, double parentRadius) { - - int childCount = kids.size(); - if(childCount == 0) return; - // handle the 1-child case with 0 limit on angle. - double angle = Math.max(0, Math.PI / 2 * (1 - 2.0/childCount)); - double childRadius = parentRadius*Math.cos(angle) / (1 + Math.cos(angle)); - double radius = parentRadius - childRadius; - - double rand = Math.random(); - - for(int i=0; i< childCount; i++) { - V child = kids.get(i); - double theta = i* 2*Math.PI/childCount + rand; - radii.put(child, childRadius); - - PolarPoint pp = new PolarPoint(theta, radius); - polarLocations.put(child, pp); - - Point2D p = PolarPoint.polarToCartesian(pp); - p.setLocation(p.getX()+parentLocation.getX(), p.getY()+parentLocation.getY()); - locations.put(child, p); - setPolars(new ArrayList(graph.getChildren(child)), p, childRadius); - } - } - - @Override - public void setSize(Dimension size) { - this.size = size; - setRootPolars(); - } - - /** - * Returns the coordinates of {@code v}'s parent, or the - * center of this layout's area if it's a root. - */ - public Point2D getCenter(V v) { - V parent = graph.getParent(v); - if(parent == null) { - return getCenter(); - } - return locations.get(parent); - } - - @Override - public void setLocation(V v, Point2D location) { - Point2D c = getCenter(v); - Point2D pv = new Point2D.Double(location.getX()-c.getX(),location.getY()-c.getY()); - PolarPoint newLocation = PolarPoint.cartesianToPolar(pv); - polarLocations.get(v).setLocation(newLocation); - - Point2D center = getCenter(v); - pv.setLocation(pv.getX()+center.getX(), pv.getY()+center.getY()); - locations.put(v, pv); - } - - @Override - public Point2D transform(V v) { - return locations.get(v); - } - - /** - * @return the radii - */ - public Map getRadii() { - return radii; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/CircleLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/CircleLayout.java deleted file mode 100644 index 8cafb77827..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/CircleLayout.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -/* - * Created on Dec 4, 2003 - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.map.LazyMap; - -import edu.uci.ics.jung.graph.Graph; - - - -/** - * A {@code Layout} implementation that positions vertices equally spaced on a regular circle. - * - * @author Masanori Harada - */ -public class CircleLayout extends AbstractLayout { - - private double radius; - private List vertex_ordered_list; - - Map circleVertexDataMap = - LazyMap.decorate(new HashMap(), - new Factory() { - public CircleVertexData create() { - return new CircleVertexData(); - }}); - - /** - * Creates an instance for the specified graph. - */ - public CircleLayout(Graph g) { - super(g); - } - - /** - * Returns the radius of the circle. - */ - public double getRadius() { - return radius; - } - - /** - * Sets the radius of the circle. Must be called before - * {@code initialize()} is called. - */ - public void setRadius(double radius) { - this.radius = radius; - } - - /** - * Sets the order of the vertices in the layout according to the ordering - * specified by {@code comparator}. - */ - public void setVertexOrder(Comparator comparator) - { - if (vertex_ordered_list == null) - vertex_ordered_list = new ArrayList(getGraph().getVertices()); - Collections.sort(vertex_ordered_list, comparator); - } - - /** - * Sets the order of the vertices in the layout according to the ordering - * of {@code vertex_list}. - */ - public void setVertexOrder(List vertex_list) - { - if (!vertex_list.containsAll(getGraph().getVertices())) - throw new IllegalArgumentException("Supplied list must include " + - "all vertices of the graph"); - this.vertex_ordered_list = vertex_list; - } - - public void reset() { - initialize(); - } - - public void initialize() - { - Dimension d = getSize(); - - if (d != null) - { - if (vertex_ordered_list == null) - setVertexOrder(new ArrayList(getGraph().getVertices())); - - double height = d.getHeight(); - double width = d.getWidth(); - - if (radius <= 0) { - radius = 0.45 * (height < width ? height : width); - } - - int i = 0; - for (V v : vertex_ordered_list) - { - Point2D coord = transform(v); - - double angle = (2 * Math.PI * i) / vertex_ordered_list.size(); - - coord.setLocation(Math.cos(angle) * radius + width / 2, - Math.sin(angle) * radius + height / 2); - - CircleVertexData data = getCircleData(v); - data.setAngle(angle); - i++; - } - } - } - - protected CircleVertexData getCircleData(V v) { - return circleVertexDataMap.get(v); - } - - protected static class CircleVertexData { - private double angle; - - protected double getAngle() { - return angle; - } - - protected void setAngle(double angle) { - this.angle = angle; - } - - @Override - public String toString() { - return "CircleVertexData: angle=" + angle; - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/DAGLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/DAGLayout.java deleted file mode 100644 index 97d3ee6b55..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/DAGLayout.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * - * Created on Dec 4, 2003 - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - -/** - * An implementation of {@code Layout} suitable for tree-like directed - * acyclic graphs. Parts of it will probably not terminate if the graph is - * cyclic! The layout will result in directed edges pointing generally upwards. - * Any vertices with no successors are considered to be level 0, and tend - * towards the top of the layout. Any vertex has a level one greater than the - * maximum level of all its successors. - * - * - * @author John Yesberg - */ -public class DAGLayout extends SpringLayout { - - /** - * Each vertex has a minimumLevel. Any vertex with no successors has - * minimumLevel of zero. The minimumLevel of any vertex must be strictly - * greater than the minimumLevel of its parents. (Vertex A is a parent of - * Vertex B iff there is an edge from B to A.) Typically, a vertex will - * have a minimumLevel which is one greater than the minimumLevel of its - * parent's. However, if the vertex has two parents, its minimumLevel will - * be one greater than the maximum of the parents'. We need to calculate - * the minimumLevel for each vertex. When we layout the graph, vertices - * cannot be drawn any higher than the minimumLevel. The graphHeight of a - * graph is the greatest minimumLevel that is used. We will modify the - * SpringLayout calculations so that nodes cannot move above their assigned - * minimumLevel. - */ - private Map minLevels = new HashMap(); - // Simpler than the "pair" technique. - static int graphHeight; - static int numRoots; - final double SPACEFACTOR = 1.3; - // How much space do we allow for additional floating at the bottom. - final double LEVELATTRACTIONRATE = 0.8; - - /** - * A bunch of parameters to help work out when to stop quivering. - * - * If the MeanSquareVel(ocity) ever gets below the MSV_THRESHOLD, then we - * will start a final cool-down phase of COOL_DOWN_INCREMENT increments. If - * the MeanSquareVel ever exceeds the threshold, we will exit the cool down - * phase, and continue looking for another opportunity. - */ - final double MSV_THRESHOLD = 10.0; - double meanSquareVel; - boolean stoppingIncrements = false; - int incrementsLeft; - final int COOL_DOWN_INCREMENTS = 200; - - /** - * Creates an instance for the specified graph. - */ - public DAGLayout(Graph g) { - super(g); - } - - /** - * setRoot calculates the level of each vertex in the graph. Level 0 is - * allocated to any vertex with no successors. Level n+1 is allocated to - * any vertex whose successors' maximum level is n. - */ - public void setRoot(Graph g) { - numRoots = 0; - for(V v : g.getVertices()) { - Collection successors = getGraph().getSuccessors(v); - if (successors.size() == 0) { - setRoot(v); - numRoots++; - } - } - } - - /** - * Set vertex v to be level 0. - */ - public void setRoot(V v) { - minLevels.put(v, new Integer(0)); - // set all the levels. - propagateMinimumLevel(v); - } - - /** - * A recursive method for allocating the level for each vertex. Ensures - * that all predecessors of v have a level which is at least one greater - * than the level of v. - * - * @param v - */ - public void propagateMinimumLevel(V v) { - int level = minLevels.get(v).intValue(); - for(V child : getGraph().getPredecessors(v)) { - int oldLevel, newLevel; - Number o = minLevels.get(child); - if (o != null) - oldLevel = o.intValue(); - else - oldLevel = 0; - newLevel = Math.max(oldLevel, level + 1); - minLevels.put(child, new Integer(newLevel)); - - if (newLevel > graphHeight) - graphHeight = newLevel; - propagateMinimumLevel(child); - } - } - - /** - * Sets random locations for a vertex within the dimensions of the space. - * This overrides the method in AbstractLayout - * - * @param coord - * @param d - */ - private void initializeLocation( - V v, - Point2D coord, - Dimension d) { - - int level = minLevels.get(v).intValue(); - int minY = (int) (level * d.getHeight() / (graphHeight * SPACEFACTOR)); - double x = Math.random() * d.getWidth(); - double y = Math.random() * (d.getHeight() - minY) + minY; - coord.setLocation(x,y); - } - - @Override - public void setSize(Dimension size) { - super.setSize(size); - for(V v : getGraph().getVertices()) { - initializeLocation(v,transform(v),getSize()); - } - } - - /** - * Had to override this one as well, to ensure that setRoot() is called. - */ - @Override - public void initialize() { - super.initialize(); - setRoot(getGraph()); - } - - /** - * Override the moveNodes() method from SpringLayout. The only change we - * need to make is to make sure that nodes don't float higher than the minY - * coordinate, as calculated by their minimumLevel. - */ - @Override - protected void moveNodes() { - // Dimension d = currentSize; - double oldMSV = meanSquareVel; - meanSquareVel = 0; - - synchronized (getSize()) { - - for(V v : getGraph().getVertices()) { - if (isLocked(v)) - continue; - SpringLayout.SpringVertexData vd = springVertexData.get(v); - Point2D xyd = transform(v); - - int width = getSize().width; - int height = getSize().height; - - // (JY addition: three lines are new) - int level = - minLevels.get(v).intValue(); - int minY = (int) (level * height / (graphHeight * SPACEFACTOR)); - int maxY = - level == 0 - ? (int) (height / (graphHeight * SPACEFACTOR * 2)) - : height; - - // JY added 2* - double the sideways repulsion. - vd.dx += 2 * vd.repulsiondx + vd.edgedx; - vd.dy += vd.repulsiondy + vd.edgedy; - - // JY Addition: Attract the vertex towards it's minimumLevel - // height. - double delta = xyd.getY() - minY; - vd.dy -= delta * LEVELATTRACTIONRATE; - if (level == 0) - vd.dy -= delta * LEVELATTRACTIONRATE; - // twice as much at the top. - - // JY addition: - meanSquareVel += (vd.dx * vd.dx + vd.dy * vd.dy); - - // keeps nodes from moving any faster than 5 per time unit - xyd.setLocation(xyd.getX()+Math.max(-5, Math.min(5, vd.dx)) , xyd.getY()+Math.max(-5, Math.min(5, vd.dy)) ); - - if (xyd.getX() < 0) { - xyd.setLocation(0, xyd.getY()); - } else if (xyd.getX() > width) { - xyd.setLocation(width, xyd.getY()); - } - - // (JY addition: These two lines replaced 0 with minY) - if (xyd.getY() < minY) { - xyd.setLocation(xyd.getX(), minY); - // (JY addition: replace height with maxY) - } else if (xyd.getY() > maxY) { - xyd.setLocation(xyd.getX(), maxY); - } - - // (JY addition: if there's only one root, anchor it in the - // middle-top of the screen) - if (numRoots == 1 && level == 0) { - xyd.setLocation(width/2, xyd.getY()); - } - } - } - //System.out.println("MeanSquareAccel="+meanSquareVel); - if (!stoppingIncrements - && Math.abs(meanSquareVel - oldMSV) < MSV_THRESHOLD) { - stoppingIncrements = true; - incrementsLeft = COOL_DOWN_INCREMENTS; - } else if ( - stoppingIncrements - && Math.abs(meanSquareVel - oldMSV) <= MSV_THRESHOLD) { - incrementsLeft--; - if (incrementsLeft <= 0) - incrementsLeft = 0; - } - } - - /** - * Override incrementsAreDone so that we can eventually stop. - */ - @Override - public boolean done() { - if (stoppingIncrements && incrementsLeft == 0) - return true; - else - return false; - } - - /** - * Override forceMove so that if someone moves a node, we can re-layout - * everything. - */ - @Override - public void setLocation(V picked, double x, double y) { - Point2D coord = transform(picked); - coord.setLocation(x,y); - stoppingIncrements = false; - } - - /** - * Override forceMove so that if someone moves a node, we can re-layout - * everything. - */ - @Override - public void setLocation(V picked, Point2D p) { - Point2D coord = transform(picked); - coord.setLocation(p); - stoppingIncrements = false; - } - - /** - * Overridden relaxEdges. This one reduces the effect of edges between - * greatly different levels. - * - */ - @Override - protected void relaxEdges() { - for(E e : getGraph().getEdges()) { - Pair endpoints = getGraph().getEndpoints(e); - V v1 = endpoints.getFirst(); - V v2 = endpoints.getSecond(); - - Point2D p1 = transform(v1); - Point2D p2 = transform(v2); - double vx = p1.getX() - p2.getX(); - double vy = p1.getY() - p2.getY(); - double len = Math.sqrt(vx * vx + vy * vy); - - // JY addition. - int level1 = - minLevels.get(v1).intValue(); - int level2 = - minLevels.get(v2).intValue(); - - // desiredLen *= Math.pow( 1.1, (v1.degree() + v2.degree()) ); -// double desiredLen = getLength(e); - double desiredLen = lengthFunction.transform(e); - - // round from zero, if needed [zero would be Bad.]. - len = (len == 0) ? .0001 : len; - - // force factor: optimal length minus actual length, - // is made smaller as the current actual length gets larger. - // why? - - // System.out.println("Desired : " + getLength( e )); - double f = force_multiplier * (desiredLen - len) / len; - - f = f * Math.pow(stretch / 100.0, - (getGraph().degree(v1) + getGraph().degree(v2) -2)); - - // JY addition. If this is an edge which stretches a long way, - // don't be so concerned about it. - if (level1 != level2) - f = f / Math.pow(Math.abs(level2 - level1), 1.5); - - // f= Math.min( 0, f ); - - // the actual movement distance 'dx' is the force multiplied by the - // distance to go. - double dx = f * vx; - double dy = f * vy; - SpringVertexData v1D, v2D; - v1D = springVertexData.get(v1); - v2D = springVertexData.get(v2); - -// SpringEdgeData sed = getSpringEdgeData(e); -// sed.f = f; - - v1D.edgedx += dx; - v1D.edgedy += dy; - v2D.edgedx += -dx; - v2D.edgedy += -dy; - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/FRLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/FRLayout.java deleted file mode 100644 index c8a2a24a8a..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/FRLayout.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.layout; - -import edu.uci.ics.jung.algorithms.layout.util.RandomLocationTransformer; -import edu.uci.ics.jung.algorithms.util.IterativeContext; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.map.LazyMap; - -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.Map; - -/** - * Implements the Fruchterman-Reingold force-directed algorithm for node layout. - * - *

        Behavior is determined by the following settable parameters: - *

          - *
        • attraction multiplier: how much edges try to keep their vertices together - *
        • repulsion multiplier: how much vertices try to push each other apart - *
        • maximum iterations: how many iterations this algorithm will use before stopping - *
        - * Each of the first two defaults to 0.75; the maximum number of iterations defaults to 700. - * - * @see "Fruchterman and Reingold, 'Graph Drawing by Force-directed Placement'" - * @see "http://i11www.ilkd.uni-karlsruhe.de/teaching/SS_04/visualisierung/papers/fruchterman91graph.pdf" - * @author Scott White, Yan-Biao Boey, Danyel Fisher - */ -public class FRLayout extends AbstractLayout implements IterativeContext { - - private double forceConstant; - - private double temperature; - - private int currentIteration; - - private int mMaxIterations = 700; - - private Map frVertexData = - LazyMap.decorate(new HashMap(), new Factory() { - public FRVertexData create() { - return new FRVertexData(); - }}); - - private double attraction_multiplier = 0.75; - - private double attraction_constant; - - private double repulsion_multiplier = 0.75; - - private double repulsion_constant; - - private double max_dimension; - - /** - * Creates an instance for the specified graph. - */ - public FRLayout(Graph g) { - super(g); - } - - /** - * Creates an instance of size {@code d} for the specified graph. - */ - public FRLayout(Graph g, Dimension d) { - super(g, new RandomLocationTransformer(d), d); - initialize(); - max_dimension = Math.max(d.height, d.width); - } - - @Override - public void setSize(Dimension size) { - if(initialized == false) { - setInitializer(new RandomLocationTransformer(size)); - } - super.setSize(size); - max_dimension = Math.max(size.height, size.width); - } - - /** - * Sets the attraction multiplier. - */ - public void setAttractionMultiplier(double attraction) { - this.attraction_multiplier = attraction; - } - - /** - * Sets the repulsion multiplier. - */ - public void setRepulsionMultiplier(double repulsion) { - this.repulsion_multiplier = repulsion; - } - - public void reset() { - doInit(); - } - - public void initialize() { - doInit(); - } - - private void doInit() { - Graph graph = getGraph(); - Dimension d = getSize(); - if(graph != null && d != null) { - currentIteration = 0; - temperature = d.getWidth() / 10; - - forceConstant = - Math - .sqrt(d.getHeight() - * d.getWidth() - / graph.getVertexCount()); - - attraction_constant = attraction_multiplier * forceConstant; - repulsion_constant = repulsion_multiplier * forceConstant; - } - } - - private double EPSILON = 0.000001D; - - /** - * Moves the iteration forward one notch, calculation attraction and - * repulsion between vertices and edges and cooling the temperature. - */ - public synchronized void step() { - currentIteration++; - - /** - * Calculate repulsion - */ - while(true) { - - try { - for(V v1 : getGraph().getVertices()) { - calcRepulsion(v1); - } - break; - } catch(ConcurrentModificationException cme) {} - } - - /** - * Calculate attraction - */ - while(true) { - try { - for(E e : getGraph().getEdges()) { - - calcAttraction(e); - } - break; - } catch(ConcurrentModificationException cme) {} - } - - - while(true) { - try { - for(V v : getGraph().getVertices()) { - if (isLocked(v)) continue; - calcPositions(v); - } - break; - } catch(ConcurrentModificationException cme) {} - } - cool(); - } - - protected synchronized void calcPositions(V v) { - FRVertexData fvd = getFRData(v); - if(fvd == null) return; - Point2D xyd = transform(v); - double deltaLength = Math.max(EPSILON, fvd.norm()); - - double newXDisp = fvd.getX() / deltaLength - * Math.min(deltaLength, temperature); - - if (Double.isNaN(newXDisp)) { - throw new IllegalArgumentException( - "Unexpected mathematical result in FRLayout:calcPositions [xdisp]"); } - - double newYDisp = fvd.getY() / deltaLength - * Math.min(deltaLength, temperature); - xyd.setLocation(xyd.getX()+newXDisp, xyd.getY()+newYDisp); - - double borderWidth = getSize().getWidth() / 50.0; - double newXPos = xyd.getX(); - if (newXPos < borderWidth) { - newXPos = borderWidth + Math.random() * borderWidth * 2.0; - } else if (newXPos > (getSize().getWidth() - borderWidth)) { - newXPos = getSize().getWidth() - borderWidth - Math.random() - * borderWidth * 2.0; - } - - double newYPos = xyd.getY(); - if (newYPos < borderWidth) { - newYPos = borderWidth + Math.random() * borderWidth * 2.0; - } else if (newYPos > (getSize().getHeight() - borderWidth)) { - newYPos = getSize().getHeight() - borderWidth - - Math.random() * borderWidth * 2.0; - } - - xyd.setLocation(newXPos, newYPos); - } - - protected void calcAttraction(E e) { - Pair endpoints = getGraph().getEndpoints(e); - V v1 = endpoints.getFirst(); - V v2 = endpoints.getSecond(); - boolean v1_locked = isLocked(v1); - boolean v2_locked = isLocked(v2); - - if(v1_locked && v2_locked) { - // both locked, do nothing - return; - } - Point2D p1 = transform(v1); - Point2D p2 = transform(v2); - if(p1 == null || p2 == null) return; - double xDelta = p1.getX() - p2.getX(); - double yDelta = p1.getY() - p2.getY(); - - double deltaLength = Math.max(EPSILON, Math.sqrt((xDelta * xDelta) - + (yDelta * yDelta))); - - double force = (deltaLength * deltaLength) / attraction_constant; - - if (Double.isNaN(force)) { throw new IllegalArgumentException( - "Unexpected mathematical result in FRLayout:calcPositions [force]"); } - - double dx = (xDelta / deltaLength) * force; - double dy = (yDelta / deltaLength) * force; - if(v1_locked == false) { - FRVertexData fvd1 = getFRData(v1); - fvd1.offset(-dx, -dy); - } - if(v2_locked == false) { - FRVertexData fvd2 = getFRData(v2); - fvd2.offset(dx, dy); - } - } - - protected void calcRepulsion(V v1) { - FRVertexData fvd1 = getFRData(v1); - if(fvd1 == null) - return; - fvd1.setLocation(0, 0); - - try { - for(V v2 : getGraph().getVertices()) { - -// if (isLocked(v2)) continue; - if (v1 != v2) { - Point2D p1 = transform(v1); - Point2D p2 = transform(v2); - if(p1 == null || p2 == null) continue; - double xDelta = p1.getX() - p2.getX(); - double yDelta = p1.getY() - p2.getY(); - - double deltaLength = Math.max(EPSILON, Math - .sqrt((xDelta * xDelta) + (yDelta * yDelta))); - - double force = (repulsion_constant * repulsion_constant) / deltaLength; - - if (Double.isNaN(force)) { throw new RuntimeException( - "Unexpected mathematical result in FRLayout:calcPositions [repulsion]"); } - - fvd1.offset((xDelta / deltaLength) * force, - (yDelta / deltaLength) * force); - } - } - } catch(ConcurrentModificationException cme) { - calcRepulsion(v1); - } - } - - private void cool() { - temperature *= (1.0 - currentIteration / (double) mMaxIterations); - } - - /** - * Sets the maximum number of iterations. - */ - public void setMaxIterations(int maxIterations) { - mMaxIterations = maxIterations; - } - - protected FRVertexData getFRData(V v) { - return frVertexData.get(v); - } - - /** - * This one is an incremental visualization. - */ - public boolean isIncremental() { - return true; - } - - /** - * Returns true once the current iteration has passed the maximum count, - * MAX_ITERATIONS. - */ - public boolean done() { - if (currentIteration > mMaxIterations || temperature < 1.0/max_dimension) - { - return true; - } - return false; - } - - protected static class FRVertexData extends Point2D.Double - { - protected void offset(double x, double y) - { - this.x += x; - this.y += y; - } - - protected double norm() - { - return Math.sqrt(x*x + y*y); - } - } -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/FRLayout2.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/FRLayout2.java deleted file mode 100644 index 0f5b05ea85..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/FRLayout2.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.map.LazyMap; - -import edu.uci.ics.jung.algorithms.layout.util.RandomLocationTransformer; -import edu.uci.ics.jung.algorithms.util.IterativeContext; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - -/** - * Implements the Fruchterman-Reingold force-directed algorithm for node layout. - * This is an experimental attempt at optimizing {@code FRLayout}; if it is successful - * it will be folded back into {@code FRLayout} (and this class will disappear). - * - *

        Behavior is determined by the following settable parameters: - *

          - *
        • attraction multiplier: how much edges try to keep their vertices together - *
        • repulsion multiplier: how much vertices try to push each other apart - *
        • maximum iterations: how many iterations this algorithm will use before stopping - *
        - * Each of the first two defaults to 0.75; the maximum number of iterations defaults to 700. - - * - * @see "Fruchterman and Reingold, 'Graph Drawing by Force-directed Placement'" - * @see http://i11www.ilkd.uni-karlsruhe.de/teaching/SS_04/visualisierung/papers/fruchterman91graph.pdf - * - * @author Tom Nelson - * @author Scott White, Yan-Biao Boey, Danyel Fisher - */ -public class FRLayout2 extends AbstractLayout implements IterativeContext { - - private double forceConstant; - - private double temperature; - - private int currentIteration; - - private int maxIterations = 700; - - private Map frVertexData = - LazyMap.decorate(new HashMap(), new Factory() { - public Point2D create() { - return new Point2D.Double(); - }}); - - private double attraction_multiplier = 0.75; - - private double attraction_constant; - - private double repulsion_multiplier = 0.75; - - private double repulsion_constant; - - private double max_dimension; - - private Rectangle2D innerBounds = new Rectangle2D.Double(); - - private boolean checked = false; - - /** - * Creates an instance for the specified graph. - */ - public FRLayout2(Graph g) { - super(g); - } - - /** - * Creates an instance of size {@code d} for the specified graph. - */ - public FRLayout2(Graph g, Dimension d) { - super(g, new RandomLocationTransformer(d), d); - max_dimension = Math.max(d.height, d.width); - initialize(); - } - - @Override - public void setSize(Dimension size) { - if(initialized == false) - setInitializer(new RandomLocationTransformer(size)); - super.setSize(size); - double t = size.width/50.0; - innerBounds.setFrameFromDiagonal(t,t,size.width-t,size.height-t); - max_dimension = Math.max(size.height, size.width); - } - - /** - * Sets the attraction multiplier. - */ - public void setAttractionMultiplier(double attraction) { - this.attraction_multiplier = attraction; - } - - /** - * Sets the repulsion multiplier. - */ - public void setRepulsionMultiplier(double repulsion) { - this.repulsion_multiplier = repulsion; - } - - public void reset() { - doInit(); - } - - public void initialize() { - doInit(); - } - - private void doInit() { - Graph graph = getGraph(); - Dimension d = getSize(); - if(graph != null && d != null) { - currentIteration = 0; - temperature = d.getWidth() / 10; - - forceConstant = - Math - .sqrt(d.getHeight() - * d.getWidth() - / graph.getVertexCount()); - - attraction_constant = attraction_multiplier * forceConstant; - repulsion_constant = repulsion_multiplier * forceConstant; - } - } - - private double EPSILON = 0.000001D; - - /** - * Moves the iteration forward one notch, calculation attraction and - * repulsion between vertices and edges and cooling the temperature. - */ - public synchronized void step() { - currentIteration++; - - /** - * Calculate repulsion - */ - while(true) { - - try { - for(V v1 : getGraph().getVertices()) { - calcRepulsion(v1); - } - break; - } catch(ConcurrentModificationException cme) {} - } - - /** - * Calculate attraction - */ - while(true) { - try { - for(E e : getGraph().getEdges()) { - calcAttraction(e); - } - break; - } catch(ConcurrentModificationException cme) {} - } - - - while(true) { - try { - for(V v : getGraph().getVertices()) { - if (isLocked(v)) continue; - calcPositions(v); - } - break; - } catch(ConcurrentModificationException cme) {} - } - cool(); - } - - protected synchronized void calcPositions(V v) { - Point2D fvd = this.frVertexData.get(v); - if(fvd == null) return; - Point2D xyd = transform(v); - double deltaLength = Math.max(EPSILON, - Math.sqrt(fvd.getX()*fvd.getX()+fvd.getY()*fvd.getY())); - - double newXDisp = fvd.getX() / deltaLength - * Math.min(deltaLength, temperature); - - assert Double.isNaN(newXDisp) == false : "Unexpected mathematical result in FRLayout:calcPositions [xdisp]"; - - double newYDisp = fvd.getY() / deltaLength - * Math.min(deltaLength, temperature); - double newX = xyd.getX()+Math.max(-5, Math.min(5,newXDisp)); - double newY = xyd.getY()+Math.max(-5, Math.min(5,newYDisp)); - - newX = Math.max(innerBounds.getMinX(), Math.min(newX, innerBounds.getMaxX())); - newY = Math.max(innerBounds.getMinY(), Math.min(newY, innerBounds.getMaxY())); - - xyd.setLocation(newX, newY); - - } - - protected void calcAttraction(E e) { - Pair endpoints = getGraph().getEndpoints(e); - V v1 = endpoints.getFirst(); - V v2 = endpoints.getSecond(); - boolean v1_locked = isLocked(v1); - boolean v2_locked = isLocked(v2); - - if(v1_locked && v2_locked) { - // both locked, do nothing - return; - } - Point2D p1 = transform(v1); - Point2D p2 = transform(v2); - if(p1 == null || p2 == null) return; - double xDelta = p1.getX() - p2.getX(); - double yDelta = p1.getY() - p2.getY(); - - double deltaLength = Math.max(EPSILON, p1.distance(p2)); - - double force = deltaLength / attraction_constant; - - assert Double.isNaN(force) == false : "Unexpected mathematical result in FRLayout:calcPositions [force]"; - - double dx = xDelta * force; - double dy = yDelta * force; - Point2D fvd1 = frVertexData.get(v1); - Point2D fvd2 = frVertexData.get(v2); - if(v2_locked) { - // double the offset for v1, as v2 will not be moving in - // the opposite direction - fvd1.setLocation(fvd1.getX()-2*dx, fvd1.getY()-2*dy); - } else { - fvd1.setLocation(fvd1.getX()-dx, fvd1.getY()-dy); - } - if(v1_locked) { - // double the offset for v2, as v1 will not be moving in - // the opposite direction - fvd2.setLocation(fvd2.getX()+2*dx, fvd2.getY()+2*dy); - } else { - fvd2.setLocation(fvd2.getX()+dx, fvd2.getY()+dy); - } - } - - protected void calcRepulsion(V v1) { - Point2D fvd1 = frVertexData.get(v1); - if(fvd1 == null) return; - fvd1.setLocation(0, 0); - boolean v1_locked = isLocked(v1); - - try { - for(V v2 : getGraph().getVertices()) { - - boolean v2_locked = isLocked(v2); - if (v1_locked && v2_locked) continue; - if (v1 != v2) { - Point2D p1 = transform(v1); - Point2D p2 = transform(v2); - if(p1 == null || p2 == null) continue; - double xDelta = p1.getX() - p2.getX(); - double yDelta = p1.getY() - p2.getY(); - - double deltaLength = Math.max(EPSILON, p1.distanceSq(p2)); - - double force = (repulsion_constant * repulsion_constant);// / deltaLength; - - double forceOverDeltaLength = force / deltaLength; - - assert Double.isNaN(force) == false : "Unexpected mathematical result in FRLayout:calcPositions [repulsion]"; - - if(v2_locked) { - // double the offset for v1, as v2 will not be moving in - // the opposite direction - fvd1.setLocation(fvd1.getX()+2 * xDelta * forceOverDeltaLength, - fvd1.getY()+ 2 * yDelta * forceOverDeltaLength); - } else { - fvd1.setLocation(fvd1.getX()+xDelta * forceOverDeltaLength, - fvd1.getY()+yDelta * forceOverDeltaLength); - } - } - } - } catch(ConcurrentModificationException cme) { - calcRepulsion(v1); - } - } - - private void cool() { - temperature *= (1.0 - currentIteration / (double) maxIterations); - } - - /** - * Sets the maximum number of iterations. - */ - public void setMaxIterations(int maxIterations) { - this.maxIterations = maxIterations; - } - - /** - * This one is an incremental visualization. - */ - public boolean isIncremental() { - return true; - } - - /** - * Returns true once the current iteration has passed the maximum count, - * MAX_ITERATIONS. - */ - public boolean done() { - if (currentIteration > maxIterations || temperature < 1.0/max_dimension) { - if (!checked) - { -// System.out.println("current iteration: " + currentIteration); -// System.out.println("temperature: " + temperature); - checked = true; - } - return true; - } - return false; - } -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/GraphElementAccessor.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/GraphElementAccessor.java deleted file mode 100644 index 4cf1c51c92..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/GraphElementAccessor.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2005, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * - * Created on Apr 12, 2005 - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Shape; -import java.util.Collection; - -/** - * Interface for coordinate-based selection of graph components. - * @author Tom Nelson - * @author Joshua O'Madadhain - */ -public interface GraphElementAccessor -{ - /** - * Returns a vertex which is associated with the - * location (x,y). This is typically determined - * with respect to the vertex's location as specified - * by a Layout. - */ - V getVertex(Layout layout, double x, double y); - - /** - * Returns the vertices contained within {@code rectangle} relative - * to {@code layout}. - */ - Collection getVertices(Layout layout, Shape rectangle); - - /** - * Returns an edge which is associated with the - * location (x,y). This is typically determined - * with respect to the edge's location as specified - * by a {@code Layout}. - */ - E getEdge(Layout layout, double x, double y); - -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/ISOMLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/ISOMLayout.java deleted file mode 100644 index bea8edaa46..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/ISOMLayout.java +++ /dev/null @@ -1,231 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.layout; - -import edu.uci.ics.jung.algorithms.layout.util.RandomLocationTransformer; -import edu.uci.ics.jung.algorithms.util.IterativeContext; -import edu.uci.ics.jung.graph.Graph; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.map.LazyMap; - -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Implements a self-organizing map layout algorithm, based on Meyer's - * self-organizing graph methods. - * - * @author Yan Biao Boey - */ -public class ISOMLayout extends AbstractLayout implements IterativeContext { - - Map isomVertexData = - LazyMap.decorate(new HashMap(), - new Factory() { - public ISOMVertexData create() { - return new ISOMVertexData(); - }}); - - private int maxEpoch; - private int epoch; - - private int radiusConstantTime; - private int radius; - private int minRadius; - - private double adaption; - private double initialAdaption; - private double minAdaption; - - protected GraphElementAccessor elementAccessor = - new RadiusGraphElementAccessor(); - - private double coolingFactor; - - private List queue = new ArrayList(); - private String status = null; - - /** - * Returns the current number of epochs and execution status, as a string. - */ - public String getStatus() { - return status; - } - - /** - * Creates an ISOMLayout instance for the specified graph g. - * @param g - */ - public ISOMLayout(Graph g) { - super(g); - } - - public void initialize() { - - setInitializer(new RandomLocationTransformer(getSize())); - maxEpoch = 2000; - epoch = 1; - - radiusConstantTime = 100; - radius = 5; - minRadius = 1; - - initialAdaption = 90.0D / 100.0D; - adaption = initialAdaption; - minAdaption = 0; - - //factor = 0; //Will be set later on - coolingFactor = 2; - - //temperature = 0.03; - //initialJumpRadius = 100; - //jumpRadius = initialJumpRadius; - - //delay = 100; - } - - - /** - * Advances the current positions of the graph elements. - */ - public void step() { - status = "epoch: " + epoch + "; "; - if (epoch < maxEpoch) { - adjust(); - updateParameters(); - status += " status: running"; - - } else { - status += "adaption: " + adaption + "; "; - status += "status: done"; -// done = true; - } - } - - private synchronized void adjust() { - //Generate random position in graph space - Point2D tempXYD = new Point2D.Double(); - - // creates a new XY data location - tempXYD.setLocation(10 + Math.random() * getSize().getWidth(), - 10 + Math.random() * getSize().getHeight()); - - //Get closest vertex to random position - V winner = elementAccessor.getVertex(this, tempXYD.getX(), tempXYD.getY()); - - while(true) { - try { - for(V v : getGraph().getVertices()) { - ISOMVertexData ivd = getISOMVertexData(v); - ivd.distance = 0; - ivd.visited = false; - } - break; - } catch(ConcurrentModificationException cme) {} - } - adjustVertex(winner, tempXYD); - } - - private synchronized void updateParameters() { - epoch++; - double factor = Math.exp(-1 * coolingFactor * (1.0 * epoch / maxEpoch)); - adaption = Math.max(minAdaption, factor * initialAdaption); - //jumpRadius = (int) factor * jumpRadius; - //temperature = factor * temperature; - if ((radius > minRadius) && (epoch % radiusConstantTime == 0)) { - radius--; - } - } - - private synchronized void adjustVertex(V v, Point2D tempXYD) { - queue.clear(); - ISOMVertexData ivd = getISOMVertexData(v); - ivd.distance = 0; - ivd.visited = true; - queue.add(v); - V current; - - while (!queue.isEmpty()) { - current = queue.remove(0); - ISOMVertexData currData = getISOMVertexData(current); - Point2D currXYData = transform(current); - - double dx = tempXYD.getX() - currXYData.getX(); - double dy = tempXYD.getY() - currXYData.getY(); - double factor = adaption / Math.pow(2, currData.distance); - - currXYData.setLocation(currXYData.getX()+(factor*dx), currXYData.getY()+(factor*dy)); - - if (currData.distance < radius) { - Collection s = getGraph().getNeighbors(current); - while(true) { - try { - for(V child : s) { - ISOMVertexData childData = getISOMVertexData(child); - if (childData != null && !childData.visited) { - childData.visited = true; - childData.distance = currData.distance + 1; - queue.add(child); - } - } - break; - } catch(ConcurrentModificationException cme) {} - } - } - } - } - - protected ISOMVertexData getISOMVertexData(V v) { - return isomVertexData.get(v); - } - - /** - * This one is an incremental visualization. - * @return true is the layout algorithm is incremental, false otherwise - */ - public boolean isIncremental() { - return true; - } - - /** - * Returns true if the vertex positions are no longer being - * updated. Currently ISOMLayout stops updating vertex - * positions after a certain number of iterations have taken place. - * @return true if the vertex position updates have stopped, - * false otherwise - */ - public boolean done() { - return epoch >= maxEpoch; - } - - protected static class ISOMVertexData { - int distance; - boolean visited; - - protected ISOMVertexData() { - distance = 0; - visited = false; - } - } - - /** - * Resets the layout iteration count to 0, which allows the layout algorithm to - * continue updating vertex positions. - */ - public void reset() { - epoch = 0; - } -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/KKLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/KKLayout.java deleted file mode 100644 index a1b9f40293..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/KKLayout.java +++ /dev/null @@ -1,433 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.layout; -/* - * This source is under the same license with JUNG. - * http://jung.sourceforge.net/license.txt for a description. - */ - -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.ConcurrentModificationException; - -import edu.uci.ics.jung.algorithms.layout.util.RandomLocationTransformer; -import edu.uci.ics.jung.algorithms.shortestpath.Distance; -import edu.uci.ics.jung.algorithms.shortestpath.DistanceStatistics; -import edu.uci.ics.jung.algorithms.shortestpath.UnweightedShortestPath; -import edu.uci.ics.jung.algorithms.util.IterativeContext; -import edu.uci.ics.jung.graph.Graph; - -/** - * Implements the Kamada-Kawai algorithm for node layout. - * Does not respect filter calls, and sometimes crashes when the view changes to it. - * - * @see "Tomihisa Kamada and Satoru Kawai: An algorithm for drawing general indirect graphs. Information Processing Letters 31(1):7-15, 1989" - * @see "Tomihisa Kamada: On visualization of abstract objects and relations. Ph.D. dissertation, Dept. of Information Science, Univ. of Tokyo, Dec. 1988." - * - * @author Masanori Harada - */ -public class KKLayout extends AbstractLayout implements IterativeContext { - - private double EPSILON = 0.1d; - - private int currentIteration; - private int maxIterations = 2000; - private String status = "KKLayout"; - - private double L; // the ideal length of an edge - private double K = 1; // arbitrary const number - private double[][] dm; // distance matrix - - private boolean adjustForGravity = true; - private boolean exchangeVertices = true; - - private V[] vertices; - private Point2D[] xydata; - - /** - * Retrieves graph distances between vertices of the visible graph - */ - protected Distance distance; - - /** - * The diameter of the visible graph. In other words, the maximum over all pairs - * of vertices of the length of the shortest path between a and bf the visible graph. - */ - protected double diameter; - - /** - * A multiplicative factor which partly specifies the "preferred" length of an edge (L). - */ - private double length_factor = 0.9; - - /** - * A multiplicative factor which specifies the fraction of the graph's diameter to be - * used as the inter-vertex distance between disconnected vertices. - */ - private double disconnected_multiplier = 0.5; - - /** - * Creates an instance for the specified graph. - */ - public KKLayout(Graph g) - { - this(g, new UnweightedShortestPath(g)); - } - - /** - * Creates an instance for the specified graph and distance metric. - */ - public KKLayout(Graph g, Distance distance){ - super(g); - this.distance = distance; - } - - /** - * Sets a multiplicative factor which - * partly specifies the "preferred" length of an edge (L). - */ - public void setLengthFactor(double length_factor){ - this.length_factor = length_factor; - } - - /** - * Sets a multiplicative factor that specifies the fraction of the graph's diameter to be - * used as the inter-vertex distance between disconnected vertices. - */ - public void setDisconnectedDistanceMultiplier(double disconnected_multiplier){ - this.disconnected_multiplier = disconnected_multiplier; - } - - /** - * Returns a string with information about the current status of the algorithm. - */ - public String getStatus() { - return status + this.getSize(); - } - - /** - * Sets the maximum number of iterations. - */ - public void setMaxIterations(int maxIterations) { - this.maxIterations = maxIterations; - } - - /** - * This one is an incremental visualization. - */ - public boolean isIncremental() { - return true; - } - - /** - * Returns true once the current iteration has passed the maximum count. - */ - public boolean done() { - if (currentIteration > maxIterations) { - return true; - } - return false; - } - - @SuppressWarnings("unchecked") - public void initialize() { - currentIteration = 0; - - if(graph != null && size != null) { - - double height = size.getHeight(); - double width = size.getWidth(); - - int n = graph.getVertexCount(); - dm = new double[n][n]; - vertices = (V[])graph.getVertices().toArray(); - xydata = new Point2D[n]; - - // assign IDs to all visible vertices - while(true) { - try { - int index = 0; - for(V v : graph.getVertices()) { - Point2D xyd = transform(v); - vertices[index] = v; - xydata[index] = xyd; - index++; - } - break; - } catch(ConcurrentModificationException cme) {} - } - - diameter = DistanceStatistics.diameter(graph, distance, true); - - double L0 = Math.min(height, width); - L = (L0 / diameter) * length_factor; // length_factor used to be hardcoded to 0.9 - //L = 0.75 * Math.sqrt(height * width / n); - - for (int i = 0; i < n - 1; i++) { - for (int j = i + 1; j < n; j++) { - Number d_ij = distance.getDistance(vertices[i], vertices[j]); - Number d_ji = distance.getDistance(vertices[j], vertices[i]); - double dist = diameter * disconnected_multiplier; - if (d_ij != null) - dist = Math.min(d_ij.doubleValue(), dist); - if (d_ji != null) - dist = Math.min(d_ji.doubleValue(), dist); - dm[i][j] = dm[j][i] = dist; - } - } - } - } - - public void step() { - try { - currentIteration++; - double energy = calcEnergy(); - status = "Kamada-Kawai V=" + getGraph().getVertexCount() - + "(" + getGraph().getVertexCount() + ")" - + " IT: " + currentIteration - + " E=" + energy - ; - - int n = getGraph().getVertexCount(); - if (n == 0) - return; - - double maxDeltaM = 0; - int pm = -1; // the node having max deltaM - for (int i = 0; i < n; i++) { - if (isLocked(vertices[i])) - continue; - double deltam = calcDeltaM(i); - - if (maxDeltaM < deltam) { - maxDeltaM = deltam; - pm = i; - } - } - if (pm == -1) - return; - - for (int i = 0; i < 100; i++) { - double[] dxy = calcDeltaXY(pm); - xydata[pm].setLocation(xydata[pm].getX()+dxy[0], xydata[pm].getY()+dxy[1]); - - double deltam = calcDeltaM(pm); - if (deltam < EPSILON) - break; - } - - if (adjustForGravity) - adjustForGravity(); - - if (exchangeVertices && maxDeltaM < EPSILON) { - energy = calcEnergy(); - for (int i = 0; i < n - 1; i++) { - if (isLocked(vertices[i])) - continue; - for (int j = i + 1; j < n; j++) { - if (isLocked(vertices[j])) - continue; - double xenergy = calcEnergyIfExchanged(i, j); - if (energy > xenergy) { - double sx = xydata[i].getX(); - double sy = xydata[i].getY(); - xydata[i].setLocation(xydata[j]); - xydata[j].setLocation(sx, sy); - return; - } - } - } - } - } - finally { -// fireStateChanged(); - } - } - - /** - * Shift all vertices so that the center of gravity is located at - * the center of the screen. - */ - public void adjustForGravity() { - Dimension d = getSize(); - double height = d.getHeight(); - double width = d.getWidth(); - double gx = 0; - double gy = 0; - for (int i = 0; i < xydata.length; i++) { - gx += xydata[i].getX(); - gy += xydata[i].getY(); - } - gx /= xydata.length; - gy /= xydata.length; - double diffx = width / 2 - gx; - double diffy = height / 2 - gy; - for (int i = 0; i < xydata.length; i++) { - xydata[i].setLocation(xydata[i].getX()+diffx, xydata[i].getY()+diffy); - } - } - - /* (non-Javadoc) - * @see edu.uci.ics.jung.visualization.layout.AbstractLayout#setSize(java.awt.Dimension) - */ - @Override - public void setSize(Dimension size) { - if(initialized == false) - setInitializer(new RandomLocationTransformer(size)); - super.setSize(size); - } - - /** - * Enable or disable gravity point adjusting. - */ - public void setAdjustForGravity(boolean on) { - adjustForGravity = on; - } - - /** - * Returns true if gravity point adjusting is enabled. - */ - public boolean getAdjustForGravity() { - return adjustForGravity; - } - - /** - * Enable or disable the local minimum escape technique by - * exchanging vertices. - */ - public void setExchangeVertices(boolean on) { - exchangeVertices = on; - } - - /** - * Returns true if the local minimum escape technique by - * exchanging vertices is enabled. - */ - public boolean getExchangeVertices() { - return exchangeVertices; - } - - /** - * Determines a step to new position of the vertex m. - */ - private double[] calcDeltaXY(int m) { - double dE_dxm = 0; - double dE_dym = 0; - double d2E_d2xm = 0; - double d2E_dxmdym = 0; - double d2E_dymdxm = 0; - double d2E_d2ym = 0; - - for (int i = 0; i < vertices.length; i++) { - if (i != m) { - - double dist = dm[m][i]; - double l_mi = L * dist; - double k_mi = K / (dist * dist); - double dx = xydata[m].getX() - xydata[i].getX(); - double dy = xydata[m].getY() - xydata[i].getY(); - double d = Math.sqrt(dx * dx + dy * dy); - double ddd = d * d * d; - - dE_dxm += k_mi * (1 - l_mi / d) * dx; - dE_dym += k_mi * (1 - l_mi / d) * dy; - d2E_d2xm += k_mi * (1 - l_mi * dy * dy / ddd); - d2E_dxmdym += k_mi * l_mi * dx * dy / ddd; - d2E_d2ym += k_mi * (1 - l_mi * dx * dx / ddd); - } - } - // d2E_dymdxm equals to d2E_dxmdym. - d2E_dymdxm = d2E_dxmdym; - - double denomi = d2E_d2xm * d2E_d2ym - d2E_dxmdym * d2E_dymdxm; - double deltaX = (d2E_dxmdym * dE_dym - d2E_d2ym * dE_dxm) / denomi; - double deltaY = (d2E_dymdxm * dE_dxm - d2E_d2xm * dE_dym) / denomi; - return new double[]{deltaX, deltaY}; - } - - /** - * Calculates the gradient of energy function at the vertex m. - */ - private double calcDeltaM(int m) { - double dEdxm = 0; - double dEdym = 0; - for (int i = 0; i < vertices.length; i++) { - if (i != m) { - double dist = dm[m][i]; - double l_mi = L * dist; - double k_mi = K / (dist * dist); - - double dx = xydata[m].getX() - xydata[i].getX(); - double dy = xydata[m].getY() - xydata[i].getY(); - double d = Math.sqrt(dx * dx + dy * dy); - - double common = k_mi * (1 - l_mi / d); - dEdxm += common * dx; - dEdym += common * dy; - } - } - return Math.sqrt(dEdxm * dEdxm + dEdym * dEdym); - } - - /** - * Calculates the energy function E. - */ - private double calcEnergy() { - double energy = 0; - for (int i = 0; i < vertices.length - 1; i++) { - for (int j = i + 1; j < vertices.length; j++) { - double dist = dm[i][j]; - double l_ij = L * dist; - double k_ij = K / (dist * dist); - double dx = xydata[i].getX() - xydata[j].getX(); - double dy = xydata[i].getY() - xydata[j].getY(); - double d = Math.sqrt(dx * dx + dy * dy); - - - energy += k_ij / 2 * (dx * dx + dy * dy + l_ij * l_ij - - 2 * l_ij * d); - } - } - return energy; - } - - /** - * Calculates the energy function E as if positions of the - * specified vertices are exchanged. - */ - private double calcEnergyIfExchanged(int p, int q) { - if (p >= q) - throw new RuntimeException("p should be < q"); - double energy = 0; // < 0 - for (int i = 0; i < vertices.length - 1; i++) { - for (int j = i + 1; j < vertices.length; j++) { - int ii = i; - int jj = j; - if (i == p) ii = q; - if (j == q) jj = p; - - double dist = dm[i][j]; - double l_ij = L * dist; - double k_ij = K / (dist * dist); - double dx = xydata[ii].getX() - xydata[jj].getX(); - double dy = xydata[ii].getY() - xydata[jj].getY(); - double d = Math.sqrt(dx * dx + dy * dy); - - energy += k_ij / 2 * (dx * dx + dy * dy + l_ij * l_ij - - 2 * l_ij * d); - } - } - return energy; - } - - public void reset() { - currentIteration = 0; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/Layout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/Layout.java deleted file mode 100644 index 5162ac5972..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/Layout.java +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.Point2D; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Graph; - -/** - * A generalized interface is a mechanism for returning (x,y) coordinates - * from vertices. In general, most of these methods are used to both control and - * get information from the layout algorithm. - *

        - * @author danyelf - * @author tom nelson - */ -public interface Layout extends Transformer { - - /** - * Initializes fields in the node that may not have - * been set during the constructor. Must be called before - * the iterations begin. - */ - void initialize(); - - /** - * provides initial locations for all vertices. - * @param initializer - */ - void setInitializer(Transformer initializer); - - /** - * setter for graph - * @param graph - */ - void setGraph(Graph graph); - - /** - * Returns the full graph (the one that was passed in at - * construction time) that this Layout refers to. - * - */ - Graph getGraph(); - - /** - * - * - */ - void reset(); - - /** - * @param d - */ - void setSize(Dimension d); - - /** - * Returns the current size of the visualization's space. - */ - Dimension getSize(); - - - /** - * Sets a flag which fixes this vertex in place. - * - * @param v vertex - */ - void lock(V v, boolean state); - - /** - * Returns true if the position of vertex v - * is locked. - */ - boolean isLocked(V v); - - /** - * set the location of a vertex - * @param v - * @param location - */ - void setLocation(V v, Point2D location); - - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/LayoutDecorator.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/LayoutDecorator.java deleted file mode 100644 index b1f25958cb..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/LayoutDecorator.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2005, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * Created on Aug 23, 2005 - */ - -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.Point2D; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.util.IterativeContext; -import edu.uci.ics.jung.graph.Graph; - -/** - * a pure decorator for the Layout interface. Intended to be overridden - * to provide specific behavior decoration - * - * @author Tom Nelson - * - */ -public abstract class LayoutDecorator implements Layout, IterativeContext { - - protected Layout delegate; - - /** - * Creates an instance backed by the specified delegate layout. - */ - public LayoutDecorator(Layout delegate) { - this.delegate = delegate; - } - - /** - * Returns the backing (delegate) layout. - */ - public Layout getDelegate() { - return delegate; - } - - /** - * Sets the backing (delegate) layout. - */ - public void setDelegate(Layout delegate) { - this.delegate = delegate; - } - - /** - * @see edu.uci.ics.jung.algorithms.util.IterativeContext#done() - */ - public void step() { - if(delegate instanceof IterativeContext) { - ((IterativeContext)delegate).step(); - } - } - - /** - * - * @see edu.uci.ics.jung.algorithms.layout.Layout#initialize() - */ - public void initialize() { - delegate.initialize(); - } - - /** - * @param initializer - * @see edu.uci.ics.jung.algorithms.layout.Layout#setInitializer(org.apache.commons.collections15.Transformer) - */ - public void setInitializer(Transformer initializer) { - delegate.setInitializer(initializer); - } - - /** - * @param v - * @param location - * @see edu.uci.ics.jung.algorithms.layout.Layout#setLocation(java.lang.Object, java.awt.geom.Point2D) - */ - public void setLocation(V v, Point2D location) { - delegate.setLocation(v, location); - } - - /** - * @see edu.uci.ics.jung.algorithms.layout.Layout#getSize() - */ - public Dimension getSize() { - return delegate.getSize(); - } - - /** - * @see edu.uci.ics.jung.algorithms.layout.Layout#getGraph() - */ - public Graph getGraph() { - return delegate.getGraph(); - } - - /** - * @see edu.uci.ics.jung.algorithms.layout.Layout#transform(Object) - */ - public Point2D transform(V v) { - return delegate.transform(v); - } - - /** - * @see edu.uci.ics.jung.algorithms.util.IterativeContext#done() - */ - public boolean done() { - if(delegate instanceof IterativeContext) { - return ((IterativeContext)delegate).done(); - } - return true; - } - - /** - * @see edu.uci.ics.jung.algorithms.layout.Layout#lock(Object, boolean) - */ - public void lock(V v, boolean state) { - delegate.lock(v, state); - } - - /** - * @see edu.uci.ics.jung.algorithms.layout.Layout#isLocked(Object) - */ - public boolean isLocked(V v) { - return delegate.isLocked(v); - } - - /** - * @see edu.uci.ics.jung.algorithms.layout.Layout#setSize(Dimension) - */ - public void setSize(Dimension d) { - delegate.setSize(d); - } - - /** - * @see edu.uci.ics.jung.algorithms.layout.Layout#reset() - */ - public void reset() { - delegate.reset(); - } - - public void setGraph(Graph graph) { - delegate.setGraph(graph); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/PolarPoint.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/PolarPoint.java deleted file mode 100644 index aa3dc7b411..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/PolarPoint.java +++ /dev/null @@ -1,103 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.geom.Point2D; - -/** - * Represents a point in polar coordinates: distance and angle from the origin. - * Includes conversions between polar and Cartesian - * coordinates (Point2D). - * - * @author Tom Nelson - tomnelson@dev.java.net - */ -public class PolarPoint -{ - double theta; - double radius; - - /** - * Creates a new instance with radius and angle each 0. - */ - public PolarPoint() { - this(0,0); - } - - /** - * Creates a new instance with radius {@code radius} and angle {@code theta}. - */ - public PolarPoint(double theta, double radius) { - this.theta = theta; - this.radius = radius; - } - - /** - * Returns the angle for this point. - */ - public double getTheta() { return theta; } - - /** - * Returns the radius for this point. - */ - public double getRadius() { return radius; } - - /** - * Sets the angle for this point to {@code theta}. - */ - public void setTheta(double theta) { this.theta = theta; } - - /** - * Sets the radius for this point to {@code theta}. - */ - public void setRadius(double radius) { this.radius = radius; } - - /** - * Returns the result of converting polar to Cartesian coordinates. - */ - public static Point2D polarToCartesian(PolarPoint polar) { - return polarToCartesian(polar.getTheta(), polar.getRadius()); - } - - /** - * Returns the result of converting (theta, radius) to Cartesian coordinates. - */ - public static Point2D polarToCartesian(double theta, double radius) { - return new Point2D.Double(radius*Math.cos(theta), radius*Math.sin(theta)); - } - - /** - * Returns the result of converting point to polar coordinates. - */ - public static PolarPoint cartesianToPolar(Point2D point) { - return cartesianToPolar(point.getX(), point.getY()); - } - - /** - * Returns the result of converting (x, y) to polar coordinates. - */ - public static PolarPoint cartesianToPolar(double x, double y) { - double theta = Math.atan2(y,x); - double radius = Math.sqrt(x*x+y*y); - return new PolarPoint(theta, radius); - } - - @Override - public String toString() { - return "PolarPoint[" + radius + "," + theta +"]"; - } - - /** - * Sets the angle and radius of this point to those of {@code p}. - */ - public void setLocation(PolarPoint p) { - this.theta = p.getTheta(); - this.radius = p.getRadius(); - } -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/RadialTreeLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/RadialTreeLayout.java deleted file mode 100644 index 457bd961f1..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/RadialTreeLayout.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2005, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * Created on Jul 9, 2005 - */ - -package edu.uci.ics.jung.algorithms.layout; -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.HashMap; -import java.util.Map; - -import edu.uci.ics.jung.graph.Forest; - -/** - * A radial layout for Tree or Forest graphs. - * - * @author Tom Nelson - * - */ -public class RadialTreeLayout extends TreeLayout { - - protected Map polarLocations; - - /** - * Creates an instance for the specified graph with default X and Y distances. - */ - public RadialTreeLayout(Forest g) { - this(g, DEFAULT_DISTX, DEFAULT_DISTY); - } - - /** - * Creates an instance for the specified graph and X distance with - * default Y distance. - */ - public RadialTreeLayout(Forest g, int distx) { - this(g, distx, DEFAULT_DISTY); - } - - /** - * Creates an instance for the specified graph, X distance, and Y distance. - */ - public RadialTreeLayout(Forest g, int distx, int disty) { - super(g, distx, disty); - } - - @Override - protected void buildTree() { - super.buildTree(); - this.polarLocations = new HashMap(); - setRadialLocations(); - } - - @Override - public void setSize(Dimension size) { - this.size = size; - buildTree(); - } - - @Override - protected void setCurrentPositionFor(V vertex) { - locations.get(vertex).setLocation(m_currentPoint); - } - - @Override - public void setLocation(V v, Point2D location) - { - Point2D c = getCenter(); - Point2D pv = new Point2D.Double(location.getX() - c.getX(), - location.getY() - c.getY()); - PolarPoint newLocation = PolarPoint.cartesianToPolar(pv); - PolarPoint currentLocation = polarLocations.get(v); - if (currentLocation == null) - polarLocations.put(v, newLocation); - else - currentLocation.setLocation(newLocation); - } - - /** - * Returns the map from vertices to their locations in polar coordinates. - */ - public Map getPolarLocations() { - return polarLocations; - } - - @Override - public Point2D transform(V v) { - PolarPoint pp = polarLocations.get(v); - double centerX = getSize().getWidth()/2; - double centerY = getSize().getHeight()/2; - Point2D cartesian = PolarPoint.polarToCartesian(pp); - cartesian.setLocation(cartesian.getX()+centerX,cartesian.getY()+centerY); - return cartesian; - } - - private Point2D getMaxXY() { - double maxx = 0; - double maxy = 0; - for(Point2D p : locations.values()) { - maxx = Math.max(maxx, p.getX()); - maxy = Math.max(maxy, p.getY()); - } - return new Point2D.Double(maxx,maxy); - } - - private void setRadialLocations() { - Point2D max = getMaxXY(); - double maxx = max.getX(); - double maxy = max.getY(); - maxx = Math.max(maxx, size.width); - double theta = 2*Math.PI/maxx; - - double deltaRadius = size.width/2/maxy; - for(Map.Entry entry : locations.entrySet()) { - V v = entry.getKey(); - Point2D p = entry.getValue(); - PolarPoint polarPoint = new PolarPoint(p.getX()*theta, (p.getY() - this.distY)*deltaRadius); - polarLocations.put(v, polarPoint); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/RadiusGraphElementAccessor.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/RadiusGraphElementAccessor.java deleted file mode 100644 index 5f12c3ca4e..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/RadiusGraphElementAccessor.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2005, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * - * Created on Apr 12, 2005 - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Shape; -import java.awt.geom.Point2D; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import edu.uci.ics.jung.graph.Graph; - - -/** - * Simple implementation of PickSupport that returns the vertex or edge - * that is closest to the specified location. This implementation - * provides the same picking options that were available in - * previous versions of AbstractLayout. - * - *

        No element will be returned that is farther away than the specified - * maximum distance. - * - * @author Tom Nelson - * @author Joshua O'Madadhain - */ -public class RadiusGraphElementAccessor implements GraphElementAccessor { - - protected double maxDistance; - - /** - * Creates an instance with an effectively infinite default maximum distance. - */ - public RadiusGraphElementAccessor() { - this(Math.sqrt(Double.MAX_VALUE - 1000)); - } - - /** - * Creates an instance with the specified default maximum distance. - */ - public RadiusGraphElementAccessor(double maxDistance) { - this.maxDistance = maxDistance; - } - - /** - * Gets the vertex nearest to the location of the (x,y) location selected, - * within a distance of maxDistance. Iterates through all - * visible vertices and checks their distance from the click. Override this - * method to provde a more efficient implementation. - */ - public V getVertex(Layout layout, double x, double y) { - return getVertex(layout, x, y, this.maxDistance); - } - - /** - * Gets the vertex nearest to the location of the (x,y) location selected, - * within a distance of maxDistance. Iterates through all - * visible vertices and checks their distance from the click. Override this - * method to provde a more efficient implementation. - * @param x - * @param y - * @param maxDistance temporarily overrides member maxDistance - */ - public V getVertex(Layout layout, double x, double y, double maxDistance) { - double minDistance = maxDistance * maxDistance; - V closest = null; - while(true) { - try { - for(V v : layout.getGraph().getVertices()) { - - Point2D p = layout.transform(v); - double dx = p.getX() - x; - double dy = p.getY() - y; - double dist = dx * dx + dy * dy; - if (dist < minDistance) { - minDistance = dist; - closest = v; - } - } - break; - } catch(ConcurrentModificationException cme) {} - } - return closest; - } - - public Collection getVertices(Layout layout, Shape rectangle) { - Set pickedVertices = new HashSet(); - while(true) { - try { - for(V v : layout.getGraph().getVertices()) { - - Point2D p = layout.transform(v); - if(rectangle.contains(p)) { - pickedVertices.add(v); - } - } - break; - } catch(ConcurrentModificationException cme) {} - } - return pickedVertices; - } - - /** - * Gets the edge nearest to the location of the (x,y) location selected. - * Calls the longer form of the call. - */ - public E getEdge(Layout layout, double x, double y) { - return getEdge(layout, x, y, this.maxDistance); - } - - /** - * Gets the edge nearest to the location of the (x,y) location selected, - * within a distance of maxDistance, Iterates through all - * visible edges and checks their distance from the click. Override this - * method to provide a more efficient implementation. - * - * @param x - * @param y - * @param maxDistance temporarily overrides member maxDistance - * @return Edge closest to the click. - */ - public E getEdge(Layout layout, double x, double y, double maxDistance) { - double minDistance = maxDistance * maxDistance; - E closest = null; - while(true) { - try { - for(E e : layout.getGraph().getEdges()) { - - // Could replace all this set stuff with getFrom_internal() etc. - Graph graph = layout.getGraph(); - Collection vertices = graph.getIncidentVertices(e); - Iterator vertexIterator = vertices.iterator(); - V v1 = vertexIterator.next(); - V v2 = vertexIterator.next(); - // Get coords - Point2D p1 = layout.transform(v1); - Point2D p2 = layout.transform(v2); - double x1 = p1.getX(); - double y1 = p1.getY(); - double x2 = p2.getX(); - double y2 = p2.getY(); - // Calculate location on line closest to (x,y) - // First, check that v1 and v2 are not coincident. - if (x1 == x2 && y1 == y2) - continue; - double b = - ((y - y1) * (y2 - y1) + (x - x1) * (x2 - x1)) - / ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); - // - double distance2; // square of the distance - if (b <= 0) - distance2 = (x - x1) * (x - x1) + (y - y1) * (y - y1); - else if (b >= 1) - distance2 = (x - x2) * (x - x2) + (y - y2) * (y - y2); - else { - double x3 = x1 + b * (x2 - x1); - double y3 = y1 + b * (y2 - y1); - distance2 = (x - x3) * (x - x3) + (y - y3) * (y - y3); - } - - if (distance2 < minDistance) { - minDistance = distance2; - closest = e; - } - } - break; - } catch(ConcurrentModificationException cme) {} - } - return closest; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/SpringLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/SpringLayout.java deleted file mode 100644 index d21c2a158e..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/SpringLayout.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.layout; - -import edu.uci.ics.jung.algorithms.layout.util.RandomLocationTransformer; -import edu.uci.ics.jung.algorithms.util.IterativeContext; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.functors.ConstantTransformer; -import org.apache.commons.collections15.map.LazyMap; - -import java.awt.Dimension; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.geom.Point2D; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.Map; - -/** - * The SpringLayout package represents a visualization of a set of nodes. The - * SpringLayout, which is initialized with a Graph, assigns X/Y locations to - * each node. When called relax(), the SpringLayout moves the - * visualization forward one step. - * - * @author Danyel Fisher - * @author Joshua O'Madadhain - */ -public class SpringLayout extends AbstractLayout implements IterativeContext { - - protected double stretch = 0.70; - protected Transformer lengthFunction; - protected int repulsion_range_sq = 100 * 100; - protected double force_multiplier = 1.0 / 3.0; - - protected Map springVertexData = - LazyMap.decorate(new HashMap(), - new Factory() { - public SpringVertexData create() { - return new SpringVertexData(); - }}); - - /** - * Constructor for a SpringLayout for a raw graph with associated - * dimension--the input knows how big the graph is. Defaults to the unit - * length function. - */ - @SuppressWarnings("unchecked") - public SpringLayout(Graph g) { - this(g, new ConstantTransformer(30)); - } - - /** - * Constructor for a SpringLayout for a raw graph with associated component. - * - * @param g the {@code Graph} to lay out - * @param length_function provides a length for each edge - */ - public SpringLayout(Graph g, Transformer length_function) - { - super(g); - this.lengthFunction = length_function; - } - - /** - * Returns the current value for the stretch parameter. - * @see #setStretch(double) - */ - public double getStretch() { - return stretch; - } - - /** - * Sets the dimensions of the available space for layout to {@code size}. - */ - @Override - public void setSize(Dimension size) { - if(initialized == false) - setInitializer(new RandomLocationTransformer(size)); - super.setSize(size); - } - - /** - *

        Sets the stretch parameter for this instance. This value - * specifies how much the degrees of an edge's incident vertices - * should influence how easily the endpoints of that edge - * can move (that is, that edge's tendency to change its length).

        - * - *

        The default value is 0.70. Positive values less than 1 cause - * high-degree vertices to move less than low-degree vertices, and - * values > 1 cause high-degree vertices to move more than - * low-degree vertices. Negative values will have unpredictable - * and inconsistent results.

        - * @param stretch - */ - public void setStretch(double stretch) { - this.stretch = stretch; - } - - /** - * Returns the current value for the node repulsion range. - * @see #setRepulsionRange(int) - */ - public int getRepulsionRange() { - return (int)(Math.sqrt(repulsion_range_sq)); - } - - /** - * Sets the node repulsion range (in drawing area units) for this instance. - * Outside this range, nodes do not repel each other. The default value - * is 100. Negative values are treated as their positive equivalents. - * @param range - */ - public void setRepulsionRange(int range) { - this.repulsion_range_sq = range * range; - } - - /** - * Returns the current value for the edge length force multiplier. - * @see #setForceMultiplier(double) - */ - public double getForceMultiplier() { - return force_multiplier; - } - - /** - * Sets the force multiplier for this instance. This value is used to - * specify how strongly an edge "wants" to be its default length - * (higher values indicate a greater attraction for the default length), - * which affects how much its endpoints move at each timestep. - * The default value is 1/3. A value of 0 turns off any attempt by the - * layout to cause edges to conform to the default length. Negative - * values cause long edges to get longer and short edges to get shorter; use - * at your own risk. - */ - public void setForceMultiplier(double force) { - this.force_multiplier = force; - } - - public void initialize() { - } - - /** - * Relaxation step. Moves all nodes a smidge. - */ - public void step() { - try { - for(V v : getGraph().getVertices()) { - SpringVertexData svd = springVertexData.get(v); - if (svd == null) { - continue; - } - svd.dx /= 4; - svd.dy /= 4; - svd.edgedx = svd.edgedy = 0; - svd.repulsiondx = svd.repulsiondy = 0; - } - } catch(ConcurrentModificationException cme) { - step(); - } - - relaxEdges(); - calculateRepulsion(); - moveNodes(); - } - - protected void relaxEdges() { - try { - for(E e : getGraph().getEdges()) { - Pair endpoints = getGraph().getEndpoints(e); - V v1 = endpoints.getFirst(); - V v2 = endpoints.getSecond(); - - Point2D p1 = transform(v1); - Point2D p2 = transform(v2); - if(p1 == null || p2 == null) continue; - double vx = p1.getX() - p2.getX(); - double vy = p1.getY() - p2.getY(); - double len = Math.sqrt(vx * vx + vy * vy); - - double desiredLen = lengthFunction.transform(e); - - // round from zero, if needed [zero would be Bad.]. - len = (len == 0) ? .0001 : len; - - double f = force_multiplier * (desiredLen - len) / len; - - f = f * Math.pow(stretch, (getGraph().degree(v1) + getGraph().degree(v2) - 2)); - - // the actual movement distance 'dx' is the force multiplied by the - // distance to go. - double dx = f * vx; - double dy = f * vy; - SpringVertexData v1D, v2D; - v1D = springVertexData.get(v1); - v2D = springVertexData.get(v2); - - v1D.edgedx += dx; - v1D.edgedy += dy; - v2D.edgedx += -dx; - v2D.edgedy += -dy; - } - } catch(ConcurrentModificationException cme) { - relaxEdges(); - } - } - - protected void calculateRepulsion() { - try { - for (V v : getGraph().getVertices()) { - if (isLocked(v)) continue; - - SpringVertexData svd = springVertexData.get(v); - if(svd == null) continue; - double dx = 0, dy = 0; - - for (V v2 : getGraph().getVertices()) { - if (v == v2) continue; - Point2D p = transform(v); - Point2D p2 = transform(v2); - if(p == null || p2 == null) continue; - double vx = p.getX() - p2.getX(); - double vy = p.getY() - p2.getY(); - double distanceSq = p.distanceSq(p2); - if (distanceSq == 0) { - dx += Math.random(); - dy += Math.random(); - } else if (distanceSq < repulsion_range_sq) { - double factor = 1; - dx += factor * vx / distanceSq; - dy += factor * vy / distanceSq; - } - } - double dlen = dx * dx + dy * dy; - if (dlen > 0) { - dlen = Math.sqrt(dlen) / 2; - svd.repulsiondx += dx / dlen; - svd.repulsiondy += dy / dlen; - } - } - } catch(ConcurrentModificationException cme) { - calculateRepulsion(); - } - } - - protected void moveNodes() - { - synchronized (getSize()) { - try { - for (V v : getGraph().getVertices()) { - if (isLocked(v)) continue; - SpringVertexData vd = springVertexData.get(v); - if(vd == null) continue; - Point2D xyd = transform(v); - - vd.dx += vd.repulsiondx + vd.edgedx; - vd.dy += vd.repulsiondy + vd.edgedy; - - // keeps nodes from moving any faster than 5 per time unit - xyd.setLocation(xyd.getX()+Math.max(-5, Math.min(5, vd.dx)), - xyd.getY()+Math.max(-5, Math.min(5, vd.dy))); - - Dimension d = getSize(); - int width = d.width; - int height = d.height; - - if (xyd.getX() < 0) { - xyd.setLocation(0, xyd.getY()); - } else if (xyd.getX() > width) { - xyd.setLocation(width, xyd.getY()); - } - if (xyd.getY() < 0) { - xyd.setLocation(xyd.getX(), 0); - } else if (xyd.getY() > height) { - xyd.setLocation(xyd.getX(), height); - } - - } - } catch(ConcurrentModificationException cme) { - moveNodes(); - } - } - } - - protected static class SpringVertexData { - protected double edgedx; - protected double edgedy; - protected double repulsiondx; - protected double repulsiondy; - - /** movement speed, x */ - protected double dx; - - /** movement speed, y */ - protected double dy; - } - - - /** - * Used for changing the size of the layout in response to a component's size. - */ - public class SpringDimensionChecker extends ComponentAdapter { - @Override - public void componentResized(ComponentEvent e) { - setSize(e.getComponent().getSize()); - } - } - - /** - * This one is an incremental visualization - */ - public boolean isIncremental() { - return true; - } - - /** - * For now, we pretend it never finishes. - */ - public boolean done() { - return false; - } - - /** - * No effect. - */ - public void reset() { - } -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/SpringLayout2.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/SpringLayout2.java deleted file mode 100644 index e62a30c198..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/SpringLayout2.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.ConcurrentModificationException; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Graph; - -/** - * The SpringLayout package represents a visualization of a set of nodes. The - * SpringLayout, which is initialized with a Graph, assigns X/Y locations to - * each node. When called relax(), the SpringLayout moves the - * visualization forward one step. - * - * - * - * @author Danyel Fisher - * @author Joshua O'Madadhain - */ -public class SpringLayout2 extends SpringLayout -{ - protected int currentIteration; - protected int averageCounter; - protected int loopCountMax = 4; - protected boolean done; - - protected Point2D averageDelta = new Point2D.Double(); - - /** - * Constructor for a SpringLayout for a raw graph with associated - * dimension--the input knows how big the graph is. Defaults to the unit - * length function. - */ - @SuppressWarnings("unchecked") - public SpringLayout2(Graph g) { - super(g); - } - - /** - * Constructor for a SpringLayout for a raw graph with associated component. - * - * @param g the {@code Graph} to lay out - * @param length_function provides a length for each edge - */ - public SpringLayout2(Graph g, Transformer length_function) - { - super(g, length_function); - } - - /** - * Relaxation step. Moves all nodes a smidge. - */ - @Override - public void step() { - super.step(); - currentIteration++; - testAverageDeltas(); - } - - private void testAverageDeltas() { - double dx = this.averageDelta.getX(); - double dy = this.averageDelta.getY(); - if(Math.abs(dx) < .001 && Math.abs(dy) < .001) { - done = true; - System.err.println("done, dx="+dx+", dy="+dy); - } - if(currentIteration > loopCountMax) { - this.averageDelta.setLocation(0,0); - averageCounter = 0; - currentIteration = 0; - } - } - - @Override - protected void moveNodes() { - synchronized (getSize()) { - try { - for (V v : getGraph().getVertices()) { - if (isLocked(v)) continue; - SpringVertexData vd = springVertexData.get(v); - if(vd == null) continue; - Point2D xyd = transform(v); - - vd.dx += vd.repulsiondx + vd.edgedx; - vd.dy += vd.repulsiondy + vd.edgedy; - -// int currentCount = currentIteration % this.loopCountMax; -// System.err.println(averageCounter+" --- vd.dx="+vd.dx+", vd.dy="+vd.dy); -// System.err.println("averageDelta was "+averageDelta); - - averageDelta.setLocation( - ((averageDelta.getX() * averageCounter) + vd.dx) / (averageCounter+1), - ((averageDelta.getY() * averageCounter) + vd.dy) / (averageCounter+1) - ); -// System.err.println("averageDelta now "+averageDelta); -// System.err.println(); - averageCounter++; - - // keeps nodes from moving any faster than 5 per time unit - xyd.setLocation(xyd.getX()+Math.max(-5, Math.min(5, vd.dx)), - xyd.getY()+Math.max(-5, Math.min(5, vd.dy))); - - Dimension d = getSize(); - int width = d.width; - int height = d.height; - - if (xyd.getX() < 0) { - xyd.setLocation(0, xyd.getY());// setX(0); - } else if (xyd.getX() > width) { - xyd.setLocation(width, xyd.getY()); //setX(width); - } - if (xyd.getY() < 0) { - xyd.setLocation(xyd.getX(),0);//setY(0); - } else if (xyd.getY() > height) { - xyd.setLocation(xyd.getX(), height); //setY(height); - } - - } - } catch(ConcurrentModificationException cme) { - moveNodes(); - } - } - } - - @Override - public boolean done() { - return done; - } - -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/StaticLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/StaticLayout.java deleted file mode 100644 index 31b32554c2..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/StaticLayout.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Created on Jul 21, 2005 - * - * Copyright (c) 2005, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.layout; - -import java.awt.Dimension; -import java.awt.geom.Point2D; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Graph; - -/** - * StaticLayout places the vertices in the locations specified by its Transformer - * initializer. Vertex locations can be placed in a Map and then supplied to - * this layout as follows: - * - Transformer vertexLocations = - TransformerUtils.mapTransformer(map); - * - * @author Tom Nelson - tomnelson@dev.java.net - * - * @param - * @param - */ -public class StaticLayout extends AbstractLayout { - - /** - * Creates an instance for the specified graph, locations, and size. - */ - public StaticLayout(Graph graph, Transformer initializer, Dimension size) { - super(graph, initializer, size); - } - - /** - * Creates an instance for the specified graph and locations, with default size. - */ - public StaticLayout(Graph graph, Transformer initializer) { - super(graph, initializer); - } - - /** - * Creates an instance for the specified graph and default size; vertex locations - * are randomly assigned. - */ - public StaticLayout(Graph graph) { - super(graph); - } - - /** - * Creates an instance for the specified graph and size. - */ - public StaticLayout(Graph graph, Dimension size) { - super(graph, size); - } - - public void initialize() {} - - public void reset() {} - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/TreeLayout.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/TreeLayout.java deleted file mode 100644 index 4bebd3a9b1..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/TreeLayout.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (c) 2005, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * Created on Jul 9, 2005 - */ - -package edu.uci.ics.jung.algorithms.layout; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.geom.Point2D; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.map.LazyMap; - -import edu.uci.ics.jung.graph.Forest; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.TreeUtils; - -/** - * @author Karlheinz Toni - * @author Tom Nelson - converted to jung2 - * - */ - -public class TreeLayout implements Layout { - - protected Dimension size = new Dimension(600,600); - protected Forest graph; - protected Map basePositions = new HashMap(); - - protected Map locations = - LazyMap.decorate(new HashMap(), - new Transformer() { - public Point2D transform(V arg0) { - return new Point2D.Double(); - }}); - - protected transient Set alreadyDone = new HashSet(); - - /** - * The default horizontal vertex spacing. Initialized to 50. - */ - public static int DEFAULT_DISTX = 50; - - /** - * The default vertical vertex spacing. Initialized to 50. - */ - public static int DEFAULT_DISTY = 50; - - /** - * The horizontal vertex spacing. Defaults to {@code DEFAULT_XDIST}. - */ - protected int distX = 50; - - /** - * The vertical vertex spacing. Defaults to {@code DEFAULT_YDIST}. - */ - protected int distY = 50; - - protected transient Point m_currentPoint = new Point(); - - /** - * Creates an instance for the specified graph with default X and Y distances. - */ - public TreeLayout(Forest g) { - this(g, DEFAULT_DISTX, DEFAULT_DISTY); - } - - /** - * Creates an instance for the specified graph and X distance with - * default Y distance. - */ - public TreeLayout(Forest g, int distx) { - this(g, distx, DEFAULT_DISTY); - } - - /** - * Creates an instance for the specified graph, X distance, and Y distance. - */ - public TreeLayout(Forest g, int distx, int disty) { - if (g == null) - throw new IllegalArgumentException("Graph must be non-null"); - if (distx < 1 || disty < 1) - throw new IllegalArgumentException("X and Y distances must each be positive"); - this.graph = g; - this.distX = distx; - this.distY = disty; - buildTree(); - } - - protected void buildTree() { - this.m_currentPoint = new Point(0, 20); - Collection roots = TreeUtils.getRoots(graph); - if (roots.size() > 0 && graph != null) { - calculateDimensionX(roots); - for(V v : roots) { - calculateDimensionX(v); - m_currentPoint.x += this.basePositions.get(v)/2 + this.distX; - buildTree(v, this.m_currentPoint.x); - } - } - int width = 0; - for(V v : roots) { - width += basePositions.get(v); - } - } - - protected void buildTree(V v, int x) { - - if (!alreadyDone.contains(v)) { - alreadyDone.add(v); - - //go one level further down - this.m_currentPoint.y += this.distY; - this.m_currentPoint.x = x; - - this.setCurrentPositionFor(v); - - int sizeXofCurrent = basePositions.get(v); - - int lastX = x - sizeXofCurrent / 2; - - int sizeXofChild; - int startXofChild; - - for (V element : graph.getSuccessors(v)) { - sizeXofChild = this.basePositions.get(element); - startXofChild = lastX + sizeXofChild / 2; - buildTree(element, startXofChild); - lastX = lastX + sizeXofChild + distX; - } - this.m_currentPoint.y -= this.distY; - } - } - - private int calculateDimensionX(V v) { - - int size = 0; - int childrenNum = graph.getSuccessors(v).size(); - - if (childrenNum != 0) { - for (V element : graph.getSuccessors(v)) { - size += calculateDimensionX(element) + distX; - } - } - size = Math.max(0, size - distX); - basePositions.put(v, size); - - return size; - } - - private int calculateDimensionX(Collection roots) { - - int size = 0; - for(V v : roots) { - int childrenNum = graph.getSuccessors(v).size(); - - if (childrenNum != 0) { - for (V element : graph.getSuccessors(v)) { - size += calculateDimensionX(element) + distX; - } - } - size = Math.max(0, size - distX); - basePositions.put(v, size); - } - - return size; - } - - /** - * This method is not supported by this class. The size of the layout - * is determined by the topology of the tree, and by the horizontal - * and vertical spacing (optionally set by the constructor). - */ - public void setSize(Dimension size) { - throw new UnsupportedOperationException("Size of TreeLayout is set" + - " by vertex spacing in constructor"); - } - - protected void setCurrentPositionFor(V vertex) { - int x = m_currentPoint.x; - int y = m_currentPoint.y; - if(x < 0) size.width -= x; - - if(x > size.width-distX) - size.width = x + distX; - - if(y < 0) size.height -= y; - if(y > size.height-distY) - size.height = y + distY; - locations.get(vertex).setLocation(m_currentPoint); - - } - - public Graph getGraph() { - return graph; - } - - public Dimension getSize() { - return size; - } - - public void initialize() { - - } - - public boolean isLocked(V v) { - return false; - } - - public void lock(V v, boolean state) { - } - - public void reset() { - } - - public void setGraph(Graph graph) { - if(graph instanceof Forest) { - this.graph = (Forest)graph; - buildTree(); - } else { - throw new IllegalArgumentException("graph must be a Forest"); - } - } - - public void setInitializer(Transformer initializer) { - } - - /** - * Returns the center of this layout's area. - */ - public Point2D getCenter() { - return new Point2D.Double(size.getWidth()/2,size.getHeight()/2); - } - - public void setLocation(V v, Point2D location) { - locations.get(v).setLocation(location); - } - - public Point2D transform(V v) { - return locations.get(v); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/package.html deleted file mode 100644 index a5ed0d05a2..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/package.html +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - -Algorithms for assigning 2D coordinates (typically used for graph visualizations) -to vertices. -Current layout algorithms include: -
          -
        • Layout, AbstractLayout: interface and abstract class defining the Layout contract and handling -some common implementation details -
        • AggregateLayout: allows multiple layouts to be combined and manipulated as one layout -
        • BalloonLayout: places vertices on nested circles (trees/forests only) -
        • CircleLayout: places vertices on a circle -
        • DAGLayout: places vertices in a hierarchy (directed acyclic graphs only) -
        • FRLayout: Fruchterman-Reingold algorithm (force-directed) -
        • ISOMLayout: self-organizing map layout -
        • KKLayout: Kamada-Kawai algorithm (tries to maintain specified distances) -
        • RadialTreeLayout: places vertices on concentric circles (trees only) -
        • SpringLayout: simple force-directed layout -
        • StaticLayout: places vertices at user-specified locations -
        • TreeLayout: simple tree/forest layout -
        - -Rendering and other aspects of visualization are handled in the visualization package. - - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/RandomLocationTransformer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/RandomLocationTransformer.java deleted file mode 100644 index 34428b18fb..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/RandomLocationTransformer.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Created on Jul 19, 2005 - * - * Copyright (c) 2005, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.layout.util; - -import java.awt.Dimension; -import java.awt.geom.Point2D; -import java.util.Date; -import java.util.Random; - -import org.apache.commons.collections15.Transformer; - -/** - * Transforms the input type into a random location within - * the bounds of the Dimension property. - * This is used as the backing Transformer for the LazyMap - * for many Layouts, - * and provides a random location for unmapped vertices - * the first time they are accessed. - * - * @author Tom Nelson - * - * @param - */ -public class RandomLocationTransformer implements Transformer { - - Dimension d; - Random random; - - /** - * Creates an instance with the specified size which uses the current time - * as the random seed. - */ - public RandomLocationTransformer(Dimension d) { - this(d, new Date().getTime()); - } - - /** - * Creates an instance with the specified dimension and random seed. - * @param d - * @param seed - */ - public RandomLocationTransformer(final Dimension d, long seed) { - this.d = d; - this.random = new Random(seed); - } - - public Point2D transform(V v) { - return new Point2D.Double(random.nextDouble() * d.width, random.nextDouble() * d.height); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/Relaxer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/Relaxer.java deleted file mode 100644 index a31113f190..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/Relaxer.java +++ /dev/null @@ -1,43 +0,0 @@ -package edu.uci.ics.jung.algorithms.layout.util; - -/** - * Interface for operating the relax iterations on a layout. - * - * @author Tom Nelson - tomnelson@dev.java.net - * - */ -public interface Relaxer { - - /** - * Execute a loop of steps in a new Thread, - * firing an event after each step. - */ - void relax(); - - /** - * Execute a loop of steps in the calling - * thread, firing no events. - */ - void prerelax(); - - /** - * Make the relaxer thread wait. - */ - void pause(); - - /** - * Make the relaxer thread resume. - * - */ - void resume(); - - /** - * Set flags to stop the relaxer thread. - */ - void stop(); - - /** - * Sets the sleep time. - */ - void setSleepTime(long i); -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/VisRunner.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/VisRunner.java deleted file mode 100644 index 14f6dfc86c..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/VisRunner.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2005, the JUNG Project and the Regents of the University of - * California All rights reserved. - * - * This software is open-source under the BSD license; see either "license.txt" - * or http://jung.sourceforge.net/license.txt for a description. - * - * - */ -package edu.uci.ics.jung.algorithms.layout.util; - -import edu.uci.ics.jung.algorithms.util.IterativeContext; - -/** - * - * Implementation of a relaxer thread for layouts. - * Extracted from the {@code VisualizationModel} in previous - * versions of JUNG. - * - * @author Tom Nelson - tomnelson@dev.java.net - * - */ -public class VisRunner implements Relaxer, Runnable { - - protected boolean running; - protected IterativeContext process; - protected boolean stop; - protected boolean manualSuspend; - protected Thread thread; - - /** - * how long the relaxer thread pauses between iteration loops. - */ - protected long sleepTime = 100L; - - - /** - * Creates an instance for the specified process. - */ - public VisRunner(IterativeContext process) { - this.process = process; - } - - /** - * @return the relaxerThreadSleepTime - */ - public long getSleepTime() { - return sleepTime; - } - - /** - * @param sleepTime the sleep time to set for this thread - */ - public void setSleepTime(long sleepTime) { - this.sleepTime = sleepTime; - } - - public void prerelax() { - manualSuspend = true; - long timeNow = System.currentTimeMillis(); - while (System.currentTimeMillis() - timeNow < 500 && !process.done()) { - process.step(); - } - manualSuspend = false; - } - - public void pause() { - manualSuspend = true; - } - - public void relax() { - // in case its running - stop(); - stop = false; - thread = new Thread(this); - thread.setPriority(Thread.MIN_PRIORITY); - thread.start(); - } - - /** - * Used for synchronization. - */ - public Object pauseObject = new String("PAUSE OBJECT"); - - public void resume() { - manualSuspend = false; - if(running == false) { - prerelax(); - relax(); - } else { - synchronized(pauseObject) { - pauseObject.notifyAll(); - } - } - } - - public synchronized void stop() { - if(thread != null) { - manualSuspend = false; - stop = true; - // interrupt the relaxer, in case it is paused or sleeping - // this should ensure that visRunnerIsRunning gets set to false - try { thread.interrupt(); } - catch(Exception ex) { - // the applet security manager may have prevented this. - // just sleep for a second to let the thread stop on its own - try { Thread.sleep(1000); } - catch(InterruptedException ie) {} // ignore - } - synchronized (pauseObject) { - pauseObject.notifyAll(); - } - } - } - - public void run() { - running = true; - try { - while (!process.done() && !stop) { - synchronized (pauseObject) { - while (manualSuspend && !stop) { - try { - pauseObject.wait(); - } catch (InterruptedException e) { - // ignore - } - } - } - process.step(); - - if (stop) - return; - - try { - Thread.sleep(sleepTime); - } catch (InterruptedException ie) { - // ignore - } - } - - } finally { - running = false; - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/package.html deleted file mode 100644 index 356f7d5f32..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/layout/util/package.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - -Utility classes for updating layout positions. - - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/MatrixElementOperations.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/MatrixElementOperations.java deleted file mode 100644 index 1124bdf0b0..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/MatrixElementOperations.java +++ /dev/null @@ -1,73 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.matrix; - -import java.util.Map; - - -/** - * An interface for specifying the behavior of graph/matrix operations - * for a particular element type. - *

        - * Graph/matrix multiplication requires the definition of two operations: - *

        - *

          - *
        1. - * Calculating an aggregate property of paths of length 2 between two - * vertices v1 and v2 (analogous to element multiplication in matrix - * arithmetic); this is handled by computePathData(). - *
        2. - *
        3. - * Aggregating the properties of all such paths, and assigning the result to - * a new edge in the output graph (analogous to element addition in matrix - * arithmetic); this is handled by mergePaths(). - *
        4. - *
        - *

        - * Together, computePathData() and mergePaths() specify how the equivalent of - * the vector inner (dot) product is to function. - *

        - * For instance, to implement the equivalent of standard matrix multiplication - * on two graphs, computePathData() should return the products of the - * weights of a two-edge path, and mergePaths() should add - * the output of computePathData() to an existing edge (or possibly create such - * an edge if none exists). - * - * @author Joshua O'Madadhain - */ -public interface MatrixElementOperations -{ - /** - * If either e or pathData is null, the effect of mergePaths() is - * implementation-dependent. - * - * @param e (possibly) existing edge in the output graph which - * represents a path in the input graph(s) - * - * @param pathData data (which represents another path with the same source - * and destination as e in the input graphs) which is to be merged into e - */ - public void mergePaths(E e, Object pathData); - - /** - * If either e1 or e2 is null, the Object reference returned should be null. - * - * @param e1 first edge from 2-edge path in input graph(s) - * @param e2 second edge from 2-edge path in input graph(s) - * @return aggregation of data from the edges of the 2-edge path - * (from source of e1 to destination of e2) comprised of (e1, e2) - */ - public Number computePathData(E e1, E e2); - - /** - * Returns a map from edges to values. - */ - public Map getEdgeData(); -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/RealMatrixElementOperations.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/RealMatrixElementOperations.java deleted file mode 100644 index ada1406c48..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/RealMatrixElementOperations.java +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.matrix; - - -import java.util.HashMap; -import java.util.Map; - -/** - * Implements the basic matrix operations on double-precision values. Assumes - * that the edges have a MutableDouble value. - * - * @author Joshua O'Madadhain - */ -public class RealMatrixElementOperations implements MatrixElementOperations -{ - private Map edgeData = new HashMap(); - - /** - * Creates an instance using the specified edge values. - */ - public RealMatrixElementOperations(Map edgeData) - { - this.edgeData = edgeData; - } - - /** - * @see MatrixElementOperations#mergePaths(Object, Object) - */ - public void mergePaths(E e, Object pathData) - { - - Number pd = (Number)pathData; - Number ed = edgeData.get(e); - if (ed == null) { - edgeData.put(e, pd); - - } else { - edgeData.put(e, ed.doubleValue()+pd.doubleValue()); - - } - - } - - /** - * @see MatrixElementOperations#computePathData(Object, Object) - */ - public Number computePathData(E e1, E e2) - { - double d1 = edgeData.get(e1).doubleValue(); - double d2 = edgeData.get(e2).doubleValue(); - return d1*d2; - } - - /** - * @return the edgeData - */ - public Map getEdgeData() { - return edgeData; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/package.html deleted file mode 100644 index 6025a412dc..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/matrix/package.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - -Mechanisms for dealing with graphs as matrices. These include conversion to and -from Colt matrices, and some matrix algorithms. - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/Metrics.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/Metrics.java deleted file mode 100644 index 1dfcf12309..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/Metrics.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * Created on Jun 7, 2008 - * - */ -package edu.uci.ics.jung.algorithms.metrics; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import edu.uci.ics.jung.graph.Graph; - -/** - * A class consisting of static methods for calculating graph metrics. - */ -public class Metrics -{ - /** - * Returns a Map of vertices to their clustering coefficients. - * The clustering coefficient cc(v) of a vertex v is defined as follows: - *

          - *
        • degree(v) == {0,1}: 0 - *
        • degree(v) == n, n >= 2: given S, the set of neighbors - * of v: cc(v) = (the sum over all w in S of the number of - * other elements of w that are neighbors of w) / ((|S| * (|S| - 1) / 2). - * Less formally, the fraction of v's neighbors that are also - * neighbors of each other. - *

          Note: This algorithm treats its argument as an undirected graph; - * edge direction is ignored. - * @param graph the graph whose clustering coefficients are to be calculated - * @see "The structure and function of complex networks, M.E.J. Newman, aps.arxiv.org/abs/cond-mat/0303516" - */ - public static Map clusteringCoefficients(Graph graph) - { - Map coefficients = new HashMap(); - - for (V v : graph.getVertices()) - { - int n = graph.getNeighborCount(v); - if (n < 2) - coefficients.put(v, new Double(0)); - else - { - // how many of v's neighbors are connected to each other? - ArrayList neighbors = new ArrayList(graph.getNeighbors(v)); - double edge_count = 0; - for (int i = 0; i < n; i++) - { - V w = neighbors.get(i); - for (int j = i+1; j < n; j++ ) - { - V x = neighbors.get(j); - edge_count += graph.isNeighbor(w, x) ? 1 : 0; - } - } - double possible_edges = (n * (n - 1))/2.0; - coefficients.put(v, new Double(edge_count / possible_edges)); - } - } - - return coefficients; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/StructuralHoles.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/StructuralHoles.java deleted file mode 100644 index aec84b9b8c..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/StructuralHoles.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Created on Sep 19, 2005 - * - * Copyright (c) 2005, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.metrics; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Graph; - -/** - * Calculates some of the measures from Burt's text "Structural Holes: - * The Social Structure of Competition". - * - *

          Notes: - *

            - *
          • Each of these measures assumes that each edge has an associated - * non-null weight whose value is accessed through the specified - * Transformer instance. - *
          • Nonexistent edges are treated as edges with weight 0 for purposes - * of edge weight calculations. - *
          - * - *

          Based on code donated by Jasper Voskuilen and - * Diederik van Liere of the Department of Information and Decision Sciences - * at Erasmus University.

          - * - * @author Joshua O'Madadhain - * @author Jasper Voskuilen - * @see "Ronald Burt, Structural Holes: The Social Structure of Competition" - * @author Tom Nelson - converted to jung2 - */ -public class StructuralHoles { - - protected Transformer edge_weight; - protected Graph g; - - /** - * Creates a StructuralHoles instance based on the - * edge weights specified by nev. - */ - public StructuralHoles(Graph graph, Transformer nev) - { - this.g = graph; - this.edge_weight = nev; - } - - /** - * Burt's measure of the effective size of a vertex's network. Essentially, the - * number of neighbors minus the average degree of those in v's neighbor set, - * not counting ties to v. Formally: - *
          -     * effectiveSize(v) = v.degree() - (sum_{u in N(v)} sum_{w in N(u), w !=u,v} p(v,w)*m(u,w))
          -     * 
          - * where - *
            - *
          • N(a) = a.getNeighbors() - *
          • p(v,w) = normalized mutual edge weight of v and w - *
          • m(u,w) = maximum-scaled mutual edge weight of u and w - *
          - * @see #normalizedMutualEdgeWeight(Object, Object) - * @see #maxScaledMutualEdgeWeight(Object, Object) - */ - public double effectiveSize(V v) - { - double result = g.degree(v); - for(V u : g.getNeighbors(v)) { - - for(V w : g.getNeighbors(u)) { - - if (w != v && w != u) - result -= normalizedMutualEdgeWeight(v,w) * - maxScaledMutualEdgeWeight(u,w); - } - } - return result; - } - - /** - * Returns the effective size of v divided by the number of - * alters in v's network. (In other words, - * effectiveSize(v) / v.degree().) - * If v.degree() == 0, returns 0. - */ - public double efficiency(V v) { - double degree = g.degree(v); - - if (degree == 0) - return 0; - else - return effectiveSize(v) / degree; - } - - /** - * Burt's constraint measure (equation 2.4, page 55 of Burt, 1992). Essentially a - * measure of the extent to which v is invested in people who are invested in - * other of v's alters (neighbors). The "constraint" is characterized - * by a lack of primary holes around each neighbor. Formally: - *
          -     * constraint(v) = sum_{w in MP(v), w != v} localConstraint(v,w)
          -     * 
          - * where MP(v) is the subset of v's neighbors that are both predecessors and successors of v. - * @see #localConstraint(Object, Object) - */ - public double constraint(V v) { - double result = 0; - for(V w : g.getSuccessors(v)) { - - if (v != w && g.isPredecessor(v,w)) - { - result += localConstraint(v, w); - } - } - - return result; - } - - - /** - * Calculates the hierarchy value for a given vertex. Returns NaN when - * v's degree is 0, and 1 when v's degree is 1. - * Formally: - *
          -     * hierarchy(v) = (sum_{v in N(v), w != v} s(v,w) * log(s(v,w))}) / (v.degree() * Math.log(v.degree()) 
          -     * 
          - * where - *
            - *
          • N(v) = v.getNeighbors() - *
          • s(v,w) = localConstraint(v,w) / (aggregateConstraint(v) / v.degree()) - *
          - * @see #localConstraint(Object, Object) - * @see #aggregateConstraint(Object) - */ - public double hierarchy(V v) - { - double v_degree = g.degree(v); - - if (v_degree == 0) - return Double.NaN; - if (v_degree == 1) - return 1; - - double v_constraint = aggregateConstraint(v); - - double numerator = 0; - for (V w : g.getNeighbors(v)) { - - if (v != w) - { - double sl_constraint = localConstraint(v, w) / (v_constraint / v_degree); - numerator += sl_constraint * Math.log(sl_constraint); - } - } - - return numerator / (v_degree * Math.log(v_degree)); - } - - /** - * Returns the local constraint on v from a lack of primary holes - * around its neighbor v2. - * Based on Burt's equation 2.4. Formally: - *
          -     * localConstraint(v1, v2) = ( p(v1,v2) + ( sum_{w in N(v)} p(v1,w) * p(w, v2) ) )^2
          -     * 
          - * where - *
            - *
          • N(v) = v.getNeighbors() - *
          • p(v,w) = normalized mutual edge weight of v and w - *
          - * @see #normalizedMutualEdgeWeight(Object, Object) - */ - public double localConstraint(V v1, V v2) - { - double nmew_vw = normalizedMutualEdgeWeight(v1, v2); - double inner_result = 0; - for (V w : g.getNeighbors(v1)) { - - inner_result += normalizedMutualEdgeWeight(v1,w) * - normalizedMutualEdgeWeight(w,v2); - } - return (nmew_vw + inner_result) * (nmew_vw + inner_result); - } - - /** - * The aggregate constraint on v. Based on Burt's equation 2.7. - * Formally: - *
          -     * aggregateConstraint(v) = sum_{w in N(v)} localConstraint(v,w) * O(w)
          -     * 
          - * where - *
            - *
          • N(v) = v.getNeighbors() - *
          • O(w) = organizationalMeasure(w) - *
          - */ - public double aggregateConstraint(V v) - { - double result = 0; - for (V w : g.getNeighbors(v)) { - - result += localConstraint(v, w) * organizationalMeasure(g, w); - } - return result; - } - - /** - * A measure of the organization of individuals within the subgraph - * centered on v. Burt's text suggests that this is - * in some sense a measure of how "replaceable" v is by - * some other element of this subgraph. Should be a number in the - * closed interval [0,1]. - * - *

          This implementation returns 1. Users may wish to override this - * method in order to define their own behavior.

          - */ - protected double organizationalMeasure(Graph g, V v) { - return 1.0; - } - - - /** - * Returns the proportion of v1's network time and energy invested - * in the relationship with v2. Formally: - *
          -     * normalizedMutualEdgeWeight(a,b) = mutual_weight(a,b) / (sum_c mutual_weight(a,c))
          -     * 
          - * Returns 0 if either numerator or denominator = 0, or if v1 == v2. - * @see #mutualWeight(Object, Object) - */ - protected double normalizedMutualEdgeWeight(V v1, V v2) - { - if (v1 == v2) - return 0; - - double numerator = mutualWeight(v1, v2); - - if (numerator == 0) - return 0; - - double denominator = 0; - for (V v : g.getNeighbors(v1)) { - denominator += mutualWeight(v1, v); - } - if (denominator == 0) - return 0; - - return numerator / denominator; - } - - /** - * Returns the weight of the edge from v1 to v2 - * plus the weight of the edge from v2 to v1; - * if either edge does not exist, it is treated as an edge with weight 0. - * Undirected edges are treated as two antiparallel directed edges (that - * is, if there is one undirected edge with weight w connecting - * v1 to v2, the value returned is 2w). - * Ignores parallel edges; if there are any such, one is chosen at random. - * Throws NullPointerException if either edge is - * present but not assigned a weight by the constructor-specified - * NumberEdgeValue. - */ - protected double mutualWeight(V v1, V v2) - { - E e12 = g.findEdge(v1,v2); - E e21 = g.findEdge(v2,v1); - double w12 = (e12 != null ? edge_weight.transform(e12).doubleValue() : 0); - double w21 = (e21 != null ? edge_weight.transform(e21).doubleValue() : 0); - - return w12 + w21; - } - - /** - * The marginal strength of v1's relation with contact vertex2. - * Formally: - *
          -     * normalized_mutual_weight = mutual_weight(a,b) / (max_c mutual_weight(a,c))
          -     * 
          - * Returns 0 if either numerator or denominator is 0, or if v1 == v2. - * @see #mutualWeight(Object, Object) - */ - protected double maxScaledMutualEdgeWeight(V v1, V v2) - { - if (v1 == v2) - return 0; - - double numerator = mutualWeight(v1, v2); - - if (numerator == 0) - return 0; - - double denominator = 0; - for (V w : g.getNeighbors(v1)) { - - if (v2 != w) - denominator = Math.max(numerator, mutualWeight(v1, w)); - } - - if (denominator == 0) - return 0; - - return numerator / denominator; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/TriadicCensus.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/TriadicCensus.java deleted file mode 100644 index 634eb3bcdf..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/TriadicCensus.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.metrics; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.commons.collections15.CollectionUtils; - -import edu.uci.ics.jung.graph.DirectedGraph; -import edu.uci.ics.jung.graph.Graph; - - -/** - * TriadicCensus is a standard social network tool that counts, for each of the - * different possible configurations of three vertices, the number of times - * that that configuration occurs in the given graph. - * This may then be compared to the set of expected counts for this particular - * graph or to an expected sample. This is often used in p* modeling. - *

          - * To use this class, - *

          - * long[] triad_counts = TriadicCensus(dg);
          - * 
          - * where dg is a DirectedGraph. - * ith element of the array (for i in [1,16]) is the number of - * occurrences of the corresponding triad type. - * (The 0th element is not meaningful; this array is effectively 1-based.) - * To get the name of the ith triad (e.g. "003"), - * look at the global constant array c.TRIAD_NAMES[i] - *

          - * Triads are named as - * (number of pairs that are mutually tied) - * (number of pairs that are one-way tied) - * (number of non-tied pairs) - * in the triple. Since there are be only three pairs, there is a finite - * set of these possible triads. - *

          - * In fact, there are exactly 16, conventionally sorted by the number of - * realized edges in the triad: - *

      - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
      Number Configuration Notes
      1003The empty triad
      2012
      3102
      4021D"Down": the directed edges point away
      5021U"Up": the directed edges meet
      6021C"Circle": one in, one out
      7111D"Down": 021D but one edge is mutual
      8111U"Up": 021U but one edge is mutual
      9030T"Transitive": two point to the same vertex
      10030C"Circle": A->B->C->A
      11201
      12120D"Down": 021D but the third edge is mutual
      13120U"Up": 021U but the third edge is mutual
      14120C"Circle": 021C but the third edge is mutual
      15210
      16300The complete
      - *

      - * This implementation takes O( m ), m is the number of edges in the graph. - *
      - * It is based on - * - * A subquadratic triad census algorithm for large sparse networks - * with small maximum degree - * Vladimir Batagelj and Andrej Mrvar, University of Ljubljana - * Published in Social Networks. - * @author Danyel Fisher - * @author Tom Nelson - converted to jung2 - * - */ -public class TriadicCensus { - - // NOTE THAT THIS RETURNS STANDARD 1-16 COUNT! - - // and their types - public static final String[] TRIAD_NAMES = { "N/A", "003", "012", "102", "021D", - "021U", "021C", "111D", "111U", "030T", "030C", "201", "120D", - "120U", "120C", "210", "300" }; - - public static final int MAX_TRIADS = TRIAD_NAMES.length; - - /** - * Returns an array whose ith element (for i in [1,16]) is the number of - * occurrences of the corresponding triad type in g. - * (The 0th element is not meaningful; this array is effectively 1-based.) - * - * @param g - */ - public static long[] getCounts(DirectedGraph g) { - long[] count = new long[MAX_TRIADS]; - - List id = new ArrayList(g.getVertices()); - - // apply algorithm to each edge, one at at time - for (int i_v = 0; i_v < g.getVertexCount(); i_v++) { - V v = id.get(i_v); - for(V u : g.getNeighbors(v)) { - int triType = -1; - if (id.indexOf(u) <= i_v) - continue; - Set neighbors = new HashSet(CollectionUtils.union(g.getNeighbors(u), g.getNeighbors(v))); - neighbors.remove(u); - neighbors.remove(v); - if (g.isSuccessor(v,u) && g.isSuccessor(u,v)) { - triType = 3; - } else { - triType = 2; - } - count[triType] += g.getVertexCount() - neighbors.size() - 2; - for (V w : neighbors) { - if (shouldCount(g, id, u, v, w)) { - count [ triType ( triCode(g, u, v, w) ) ] ++; - } - } - } - } - int sum = 0; - for (int i = 2; i <= 16; i++) { - sum += count[i]; - } - int n = g.getVertexCount(); - count[1] = n * (n-1) * (n-2) / 6 - sum; - return count; - } - - /** - * This is the core of the technique in the paper. Returns an int from 0 to - * 65 based on: WU -> 32 UW -> 16 WV -> 8 VW -> 4 UV -> 2 VU -> 1 - * - */ - public static int triCode(Graph g, V u, V v, V w) { - int i = 0; - i += link(g, v, u ) ? 1 : 0; - i += link(g, u, v ) ? 2 : 0; - i += link(g, v, w ) ? 4 : 0; - i += link(g, w, v ) ? 8 : 0; - i += link(g, u, w ) ? 16 : 0; - i += link(g, w, u ) ? 32 : 0; - return i; - } - - protected static boolean link(Graph g, V a, V b) { - return g.isPredecessor(b, a); - } - - - /** - * Simply returns the triCode. - * @param triCode - * @return the string code associated with the numeric type - */ - public static int triType( int triCode ) { - return codeToType[ triCode ]; - } - - /** - * For debugging purposes, this is copied straight out of the paper which - * means that they refer to triad types 1-16. - */ - protected static final int[] codeToType = { 1, 2, 2, 3, 2, 4, 6, 8, 2, 6, 5, 7, 3, 8, - 7, 11, 2, 6, 4, 8, 5, 9, 9, 13, 6, 10, 9, 14, 7, 14, 12, 15, 2, 5, - 6, 7, 6, 9, 10, 14, 4, 9, 9, 12, 8, 13, 14, 15, 3, 7, 8, 11, 7, 12, - 14, 15, 8, 14, 13, 15, 11, 15, 15, 16 }; - - /** - * Make sure we have a canonical ordering: Returns true if u < w, or v < w < - * u and v doesn't link to w - * - * @param id - * @param u - * @param v - * @param w - * @return true if u < w, or if v < w < u and v doesn't link to w; false otherwise - */ - protected static boolean shouldCount(Graph g, List id, V u, V v, V w) { - int i_u = id.indexOf(u); - int i_w = id.indexOf(w); - if (i_u < i_w) - return true; - int i_v = id.indexOf(v); - if ((i_v < i_w) && (i_w < i_u) && (!g.isNeighbor(w,v))) - return true; - return false; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/package.html deleted file mode 100644 index ce5144b956..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/metrics/package.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - -Specialized measures for graph properties. These currently include: - -

        -
      • StructuralHoles: calculates some of Burt's 'structural holes' -measures (e.g. efficiency, hierarchy, constraint). -
      • TriadicCensus: returns counts for each triad type found in a -graph. -
      - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/package.html deleted file mode 100644 index f9d2e2509e..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/package.html +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - -

      Algorithms for graphs and networks.

      - -

      These algorithms are divided into categories as follows: -

        -
      • blockmodel: dividing graph elements (typically vertices) into -equivalence classes, -generally by topological properties (e.g. structural equivalence) -
      • cluster: identifying coherent (not necessarily disjoint) groups of elements -(e.g. weakly connected components, edge betweenness clustering) -
      • filters: removing parts of a graph according to specified criteria -
      • flows: calculating properties relating to network flows -(e.g. max flow/min cut) -
      • generators: creating graphs with certain properties -
      • importance (deprecated): assigning values to vertices/edges -based on topological properties -
      • layout: arrangement of graph elements, generally for visualization -
      • metrics: calculating structural properties (triad census, structural -holes) -
      • scoring: assigning values (denoting significance, influence, -centrality, etc.) to vertices/edges based on topological properties, -e.g. PageRank, HITS, betweenness centrality (replaces "importance", above) -
      • shortestpath: calculation of shortest paths between vertices -
      • util: low-level utility classes used in a variety of algorithms -
      - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/AbstractIterativeScorer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/AbstractIterativeScorer.java deleted file mode 100644 index 70d677b518..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/AbstractIterativeScorer.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Created on Jul 6, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.util.DelegateToEdgeTransformer; -import edu.uci.ics.jung.algorithms.scoring.util.VEPair; -import edu.uci.ics.jung.algorithms.util.IterativeContext; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * An abstract class for algorithms that assign scores to vertices based on iterative methods. - * Generally, any (concrete) subclass will function by creating an instance, and then either calling - * evaluate (if the user wants to iterate until the algorithms is 'done') or - * repeatedly call step (if the user wants to observe the values at each step). - */ -public abstract class AbstractIterativeScorer implements IterativeContext, VertexScorer -{ - /** - * Maximum number of iterations to use before terminating. Defaults to 100. - */ - protected int max_iterations; - - /** - * Minimum change from one step to the next; if all changes are <= tolerance, - * no further updates will occur. - * Defaults to 0.001. - */ - protected double tolerance; - - /** - * The graph on which the calculations are to be made. - */ - protected Hypergraph graph; - - /** - * The total number of iterations used so far. - */ - protected int total_iterations; - - /** - * The edge weights used by this algorithm. - */ - protected Transformer, ? extends Number> edge_weights; - - /** - * Indicates whether the output and current values are in a 'swapped' state. - * Intended for internal use only. - */ - protected boolean output_reversed; - - /** - * The map in which the output values are stored. - */ - private Map output; - - /** - * The map in which the current values are stored. - */ - private Map current_values; - - /** - * A flag representing whether this instance tolerates disconnected graphs. - * Instances that do not accept disconnected graphs may have unexpected behavior - * on disconnected graphs; they are not guaranteed to do an explicit check. - * Defaults to true. - */ - private boolean accept_disconnected_graph; - - - protected boolean hyperedges_are_self_loops = false; - - /** - * Sets the output value for this vertex. - * @param v the vertex whose output value is to be set - * @param value the value to set - */ - protected void setOutputValue(V v, T value) - { - output.put(v, value); - } - - /** - * Gets the output value for this vertex. - * @param v the vertex whose output value is to be retrieved - * @return the output value for this vertex - */ - protected T getOutputValue(V v) - { - return output.get(v); - } - - /** - * Gets the current value for this vertex - * @param v the vertex whose current value is to be retrieved - * @return the current value for this vertex - */ - protected T getCurrentValue(V v) - { - return current_values.get(v); - } - - /** - * Sets the current value for this vertex. - * @param v the vertex whose current value is to be set - * @param value the current value to set - */ - protected void setCurrentValue(V v, T value) - { - current_values.put(v, value); - } - - /** - * The largest change seen so far among all vertex scores. - */ - protected double max_delta; - - /** - * Creates an instance for the specified graph and edge weights. - * @param g the graph for which the instance is to be created - * @param edge_weights the edge weights for this instance - */ - public AbstractIterativeScorer(Hypergraph g, Transformer edge_weights) - { - this.graph = g; - this.max_iterations = 100; - this.tolerance = 0.001; - this.accept_disconnected_graph = true; - setEdgeWeights(edge_weights); - } - - /** - * Creates an instance for the specified graph g. - * NOTE: This constructor does not set the internal - * edge_weights variable. If this variable is used by - * the subclass which invoked this constructor, it must be initialized - * by that subclass. - * @param g the graph for which the instance is to be created - */ - public AbstractIterativeScorer(Hypergraph g) - { - this.graph = g; - this.max_iterations = 100; - this.tolerance = 0.001; - this.accept_disconnected_graph = true; - } - - /** - * Initializes the internal state for this instance. - */ - protected void initialize() - { - this.total_iterations = 0; - this.max_delta = Double.MIN_VALUE; - this.output_reversed = true; - this.current_values = new HashMap(); - this.output = new HashMap(); - } - - /** - * Steps through this scoring algorithm until a termination condition is reached. - */ - public void evaluate() - { - do - step(); - while (!done()); - } - - /** - * Returns true if the total number of iterations is greater than or equal to - * max_iterations - * or if the maximum value change observed is less than tolerance. - */ - public boolean done() - { - return total_iterations >= max_iterations || max_delta < tolerance; - } - - /** - * Performs one step of this algorithm; updates the state (value) for each vertex. - */ - public void step() - { - swapOutputForCurrent(); - - for (V v : graph.getVertices()) - { - double diff = update(v); - updateMaxDelta(v, diff); - } - total_iterations++; - afterStep(); - } - - /** - * - */ - protected void swapOutputForCurrent() - { - Map tmp = output; - output = current_values; - current_values = tmp; - output_reversed = !output_reversed; - } - - /** - * Updates the value for v. - * This is the key - * @param v the vertex whose value is to be updated - * @return - */ - protected abstract double update(V v); - - protected void updateMaxDelta(V v, double diff) - { - max_delta = Math.max(max_delta, diff); - } - - protected void afterStep() {} - - public T getVertexScore(V v) - { - if (!graph.containsVertex(v)) - throw new IllegalArgumentException("Vertex " + v + " not an element of this graph"); - - return output.get(v); - } - - /** - * Returns the maximum number of iterations that this instance will use. - * @return the maximum number of iterations that evaluate will use - * prior to terminating - */ - public int getMaxIterations() - { - return max_iterations; - } - - /** - * Returns the number of iterations that this instance has used so far. - * @return the number of iterations that this instance has used so far - */ - public int getIterations() - { - return total_iterations; - } - - /** - * Sets the maximum number of times that evaluate will call step. - * @param max_iterations the maximum - */ - public void setMaxIterations(int max_iterations) - { - this.max_iterations = max_iterations; - } - - /** - * Gets the size of the largest change (difference between the current and previous values) - * for any vertex that can be tolerated. Once all changes are less than this value, - * evaluate will terminate. - * @return the size of the largest change that evaluate() will permit - */ - public double getTolerance() - { - return tolerance; - } - - /** - * Sets the size of the largest change (difference between the current and previous values) - * for any vertex that can be tolerated. - * @param tolerance the size of the largest change that evaluate() will permit - */ - public void setTolerance(double tolerance) - { - this.tolerance = tolerance; - } - - /** - * Returns the Transformer that this instance uses to associate edge weights with each edge. - * @return the Transformer that associates an edge weight with each edge - */ - public Transformer, ? extends Number> getEdgeWeights() - { - return edge_weights; - } - - /** - * Sets the Transformer that this instance uses to associate edge weights with each edge - * @param edge_weights the Transformer to use to associate an edge weight with each edge - * @see edu.uci.ics.jung.algorithms.scoring.util.UniformDegreeWeight - */ - public void setEdgeWeights(Transformer edge_weights) - { - this.edge_weights = new DelegateToEdgeTransformer(edge_weights); - } - - /** - * Gets the edge weight for e in the context of its (incident) vertex v. - * @param v the vertex incident to e as a context in which the edge weight is to be calculated - * @param e the edge whose weight is to be returned - * @return the edge weight for e in the context of its (incident) vertex v - */ - protected Number getEdgeWeight(V v, E e) - { - return edge_weights.transform(new VEPair(v,e)); - } - - /** - * Collects the 'potential' from v (its current value) if it has no outgoing edges; this - * can then be redistributed among the other vertices as a means of normalization. - * @param v - */ - protected void collectDisappearingPotential(V v) {} - - /** - * Specifies whether this instance should accept vertices with no outgoing edges. - * @param accept true if this instance should accept vertices with no outgoing edges, false otherwise - */ - public void acceptDisconnectedGraph(boolean accept) - { - this.accept_disconnected_graph = accept; - } - - /** - * Returns true if this instance accepts vertices with no outgoing edges, and false otherwise. - * @return true if this instance accepts vertices with no outgoing edges, otherwise false - */ - public boolean isDisconnectedGraphOK() - { - return this.accept_disconnected_graph; - } - - /** - * Specifies whether hyperedges are to be treated as self-loops. If they - * are, then potential will flow along a hyperedge a vertex to itself, - * just as it does to all other vertices incident to that hyperedge. - * @param arg if {@code true}, hyperedges are treated as self-loops - */ - public void setHyperedgesAreSelfLoops(boolean arg) - { - this.hyperedges_are_self_loops = arg; - } - - /** - * Returns the effective number of vertices incident to this edge. If - * the graph is a binary relation or if hyperedges are treated as self-loops, - * the value returned is {@code graph.getIncidentCount(e)}; otherwise it is - * {@code graph.getIncidentCount(e) - 1}. - */ - protected int getAdjustedIncidentCount(E e) - { - return graph.getIncidentCount(e) - (hyperedges_are_self_loops ? 0 : 1); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/AbstractIterativeScorerWithPriors.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/AbstractIterativeScorerWithPriors.java deleted file mode 100644 index 6883e26384..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/AbstractIterativeScorerWithPriors.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Created on Jul 14, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * An abstract class for iterative random-walk-based vertex scoring algorithms - * that have a - * fixed probability, for each vertex, of 'jumping' to that vertex at each - * step in the algorithm (rather than following a link out of that vertex). - * - * @param the vertex type - * @param the edge type - * @param the score type - */ -public abstract class AbstractIterativeScorerWithPriors extends - AbstractIterativeScorer implements VertexScorer -{ - /** - * The prior probability of each vertex being visited on a given - * 'jump' (non-link-following) step. - */ - protected Transformer vertex_priors; - - /** - * The probability of making a 'jump' at each step. - */ - protected double alpha; - - /** - * Creates an instance for the specified graph, edge weights, vertex - * priors, and jump probability. - * @param g the graph whose vertices are to be assigned scores - * @param edge_weights the edge weights to use in the score assignment - * @param vertex_priors the prior probabilities of each vertex being 'jumped' to - * @param alpha the probability of making a 'jump' at each step - */ - public AbstractIterativeScorerWithPriors(Hypergraph g, - Transformer edge_weights, - Transformer vertex_priors, double alpha) - { - super(g, edge_weights); - this.vertex_priors = vertex_priors; - this.alpha = alpha; - initialize(); - } - - /** - * Creates an instance for the specified graph, vertex priors, and jump - * probability, with edge weights specified by the subclass. - * @param g the graph whose vertices are to be assigned scores - * @param vertex_priors the prior probabilities of each vertex being 'jumped' to - * @param alpha the probability of making a 'jump' at each step - */ - public AbstractIterativeScorerWithPriors(Hypergraph g, - Transformer vertex_priors, double alpha) - { - super(g); - this.vertex_priors = vertex_priors; - this.alpha = alpha; - initialize(); - } - - /** - * Initializes the state of this instance. - */ - @Override - public void initialize() - { - super.initialize(); - // initialize output values to priors - // (output and current are swapped before each step(), so current will - // have priors when update()s start happening) - for (V v : graph.getVertices()) - setOutputValue(v, getVertexPrior(v)); - } - - /** - * Returns the prior probability for v. - * @param v the vertex whose prior probability is being queried - * @return the prior probability for v - */ - protected S getVertexPrior(V v) - { - return vertex_priors.transform(v); - } - - /** - * Returns a Transformer which maps each vertex to its prior probability. - * @return a Transformer which maps each vertex to its prior probability - */ - public Transformer getVertexPriors() - { - return vertex_priors; - } - - /** - * Returns the probability of making a 'jump' (non-link-following step). - * @return the probability of making a 'jump' (non-link-following step) - */ - public double getAlpha() - { - return alpha; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/BarycenterScorer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/BarycenterScorer.java deleted file mode 100644 index 1c9c178c55..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/BarycenterScorer.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Created on Jul 12, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.shortestpath.Distance; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Assigns scores to each vertex according to the sum of its distances to all other vertices. - */ -public class BarycenterScorer extends DistanceCentralityScorer -{ - /** - * Creates an instance with the specified graph and distance metric. - * @param graph the input graph - * @param distance the distance metric to use - */ - public BarycenterScorer(Hypergraph graph, Distance distance) - { - super(graph, distance, false); - } - - /** - * Creates an instance with the specified graph and edge weights. - * Will generate a Distance metric internally based on the edge weights. - * @param graph the input graph - * @param edge_weights the edge weights to use to calculate vertex/vertex distances - */ - public BarycenterScorer(Hypergraph graph, Transformer edge_weights) - { - super(graph, edge_weights, false); - } - - /** - * Creates an instance with the specified graph. - * Will generate a Distance metric internally assuming that the - * graph is unweighted. - * @param graph the input graph - */ - public BarycenterScorer(Hypergraph graph) - { - super(graph, false); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/BetweennessCentrality.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/BetweennessCentrality.java deleted file mode 100644 index 5cfeb1647b..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/BetweennessCentrality.java +++ /dev/null @@ -1,351 +0,0 @@ -/** - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * Created on Sep 16, 2008 - * - */ -package edu.uci.ics.jung.algorithms.scoring; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Stack; - -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.functors.ConstantTransformer; - -import edu.uci.ics.jung.algorithms.util.MapBinaryHeap; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.UndirectedGraph; - -/** - * Computes betweenness centrality for each vertex and edge in the graph. - * - * @see "Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001." - */ -public class BetweennessCentrality - implements VertexScorer, EdgeScorer -{ - protected Graph graph; - protected Map vertex_scores; - protected Map edge_scores; - protected Map vertex_data; - - /** - * Calculates betweenness scores based on the all-pairs unweighted shortest paths - * in the graph. - * @param graph the graph for which the scores are to be calculated - */ - @SuppressWarnings("unchecked") - public BetweennessCentrality(Graph graph) - { - initialize(graph); - computeBetweenness(new LinkedList(), new ConstantTransformer(1)); - } - - /** - * Calculates betweenness scores based on the all-pairs weighted shortest paths in the - * graph. - * - *

      NOTE: This version of the algorithm may not work correctly on all graphs; we're still - * working out the bugs. Use at your own risk. - * @param graph the graph for which the scores are to be calculated - * @param edge_weights the edge weights to be used in the path length calculations - */ - public BetweennessCentrality(Graph graph, - Transformer edge_weights) - { - // reject negative-weight edges up front - for (E e : graph.getEdges()) - { - double e_weight = edge_weights.transform(e).doubleValue(); - if (e_weight < 0) - throw new IllegalArgumentException(String.format( - "Weight for edge '%s' is < 0: %d", e, e_weight)); - } - - initialize(graph); - computeBetweenness(new MapBinaryHeap(new BetweennessComparator()), - edge_weights); - } - - protected void initialize(Graph graph) - { - this.graph = graph; - this.vertex_scores = new HashMap(); - this.edge_scores = new HashMap(); - this.vertex_data = new HashMap(); - - for (V v : graph.getVertices()) - this.vertex_scores.put(v, 0.0); - - for (E e : graph.getEdges()) - this.edge_scores.put(e, 0.0); - } - - protected void computeBetweenness(Queue queue, - Transformer edge_weights) - { - for (V v : graph.getVertices()) - { - // initialize the betweenness data for this new vertex - for (V s : graph.getVertices()) - this.vertex_data.put(s, new BetweennessData()); - -// if (v.equals(new Integer(0))) -// System.out.println("pause"); - - vertex_data.get(v).numSPs = 1; - vertex_data.get(v).distance = 0; - - Stack stack = new Stack(); -// Buffer queue = new UnboundedFifoBuffer(); -// queue.add(v); - queue.offer(v); - - while (!queue.isEmpty()) - { -// V w = queue.remove(); - V w = queue.poll(); - stack.push(w); - BetweennessData w_data = vertex_data.get(w); - - for (E e : graph.getOutEdges(w)) - { - // TODO (jrtom): change this to getOtherVertices(w, e) - V x = graph.getOpposite(w, e); - if (x.equals(w)) - continue; - double wx_weight = edge_weights.transform(e).doubleValue(); - - -// for(V x : graph.getSuccessors(w)) -// { -// if (x.equals(w)) -// continue; - - // FIXME: the other problem is that I need to - // keep putting the neighbors of things we've just - // discovered in the queue, if they're undiscovered or - // at greater distance. - - // FIXME: this is the problem, right here, I think: - // need to update position in queue if distance changes - // (which can only happen with weighted edges). - // for each outgoing edge e from w, get other end x - // if x not already visited (dist x < 0) - // set x's distance to w's dist + edge weight - // add x to queue; pri in queue is x's dist - // if w's dist + edge weight < x's dist - // update x's dist - // update x in queue (MapBinaryHeap) - // clear x's incoming edge list - // if w's dist + edge weight = x's dist - // add e to x's incoming edge list - - BetweennessData x_data = vertex_data.get(x); - double x_potential_dist = w_data.distance + wx_weight; - - if (x_data.distance < 0) - { -// queue.add(x); -// vertex_data.get(x).distance = vertex_data.get(w).distance + 1; - x_data.distance = x_potential_dist; - queue.offer(x); - } - - // note: - // (1) this can only happen with weighted edges - // (2) x's SP count and incoming edges are updated below - if (x_data.distance > x_potential_dist) - { - x_data.distance = x_potential_dist; - // invalidate previously identified incoming edges - // (we have a new shortest path distance to x) - x_data.incomingEdges.clear(); - // update x's position in queue - ((MapBinaryHeap)queue).update(x); - } -// if (vertex_data.get(x).distance == vertex_data.get(w).distance + 1) - // -// if (x_data.distance == x_potential_dist) -// { -// x_data.numSPs += w_data.numSPs; -//// vertex_data.get(x).predecessors.add(w); -// x_data.incomingEdges.add(e); -// } - } - for (E e: graph.getOutEdges(w)) - { - V x = graph.getOpposite(w, e); - if (x.equals(w)) - continue; - double e_weight = edge_weights.transform(e).doubleValue(); - BetweennessData x_data = vertex_data.get(x); - double x_potential_dist = w_data.distance + e_weight; - if (x_data.distance == x_potential_dist) - { - x_data.numSPs += w_data.numSPs; -// vertex_data.get(x).predecessors.add(w); - x_data.incomingEdges.add(e); - } - } - } - while (!stack.isEmpty()) - { - V x = stack.pop(); - -// for (V w : vertex_data.get(x).predecessors) - for (E e : vertex_data.get(x).incomingEdges) - { - V w = graph.getOpposite(x, e); - double partialDependency = - vertex_data.get(w).numSPs / vertex_data.get(x).numSPs * - (1.0 + vertex_data.get(x).dependency); - vertex_data.get(w).dependency += partialDependency; -// E w_x = graph.findEdge(w, x); -// double w_x_score = edge_scores.get(w_x).doubleValue(); -// w_x_score += partialDependency; -// edge_scores.put(w_x, w_x_score); - double e_score = edge_scores.get(e).doubleValue(); - edge_scores.put(e, e_score + partialDependency); - } - if (!x.equals(v)) - { - double x_score = vertex_scores.get(x).doubleValue(); - x_score += vertex_data.get(x).dependency; - vertex_scores.put(x, x_score); - } - } - } - - if(graph instanceof UndirectedGraph) - { - for (V v : graph.getVertices()) { - double v_score = vertex_scores.get(v).doubleValue(); - v_score /= 2.0; - vertex_scores.put(v, v_score); - } - for (E e : graph.getEdges()) { - double e_score = edge_scores.get(e).doubleValue(); - e_score /= 2.0; - edge_scores.put(e, e_score); - } - } - - vertex_data.clear(); - } - -// protected void computeWeightedBetweenness(Transformer edge_weights) -// { -// for (V v : graph.getVertices()) -// { -// // initialize the betweenness data for this new vertex -// for (V s : graph.getVertices()) -// this.vertex_data.put(s, new BetweennessData()); -// vertex_data.get(v).numSPs = 1; -// vertex_data.get(v).distance = 0; -// -// Stack stack = new Stack(); -//// Buffer queue = new UnboundedFifoBuffer(); -// SortedSet pqueue = new TreeSet(new BetweennessComparator()); -//// queue.add(v); -// pqueue.add(v); -// -//// while (!queue.isEmpty()) -// while (!pqueue.isEmpty()) -// { -//// V w = queue.remove(); -// V w = pqueue.first(); -// pqueue.remove(w); -// stack.push(w); -// -//// for(V x : graph.getSuccessors(w)) -// for (E e : graph.getOutEdges(w)) -// { -// // TODO (jrtom): change this to getOtherVertices(w, e) -// V x = graph.getOpposite(w, e); -// if (x.equals(w)) -// continue; -// double e_weight = edge_weights.transform(e).doubleValue(); -// -// if (vertex_data.get(x).distance < 0) -// { -//// queue.add(x); -// pqueue.add(v); -//// vertex_data.get(x).distance = vertex_data.get(w).distance + 1; -// vertex_data.get(x).distance = -// vertex_data.get(w).distance + e_weight; -// } -// -//// if (vertex_data.get(x).distance == vertex_data.get(w).distance + 1) -// if (vertex_data.get(x).distance == -// vertex_data.get(w).distance + e_weight) -// { -// vertex_data.get(x).numSPs += vertex_data.get(w).numSPs; -// vertex_data.get(x).predecessors.add(w); -// } -// } -// } -// updateScores(v, stack); -// } -// -// if(graph instanceof UndirectedGraph) -// adjustUndirectedScores(); -// -// vertex_data.clear(); -// } - - public Double getVertexScore(V v) - { - return vertex_scores.get(v); - } - - public Double getEdgeScore(E e) - { - return edge_scores.get(e); - } - - private class BetweennessData - { - double distance; - double numSPs; -// List predecessors; - List incomingEdges; - double dependency; - - BetweennessData() - { - distance = -1; - numSPs = 0; -// predecessors = new ArrayList(); - incomingEdges = new ArrayList(); - dependency = 0; - } - - @Override - public String toString() - { - return "[d:" + distance + ", sp:" + numSPs + - ", p:" + incomingEdges + ", d:" + dependency + "]\n"; -// ", p:" + predecessors + ", d:" + dependency + "]\n"; - } - } - - private class BetweennessComparator implements Comparator - { - public int compare(V v1, V v2) - { - return vertex_data.get(v1).distance > vertex_data.get(v2).distance ? 1 : -1; - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/ClosenessCentrality.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/ClosenessCentrality.java deleted file mode 100644 index d64f01ed41..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/ClosenessCentrality.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Created on Jul 12, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.shortestpath.Distance; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Assigns scores to each vertex based on the mean distance to each other vertex. - * - * @author Joshua O'Madadhain - */ -public class ClosenessCentrality extends DistanceCentralityScorer -{ - - /** - * Creates an instance using the specified vertex/vertex distance metric. - * @param graph the input - * @param distance the vertex/vertex distance metric. - */ - public ClosenessCentrality(Hypergraph graph, Distance distance) - { - super(graph, distance, true); - } - - /** - * Creates an instance which measures distance using the specified edge weights. - * @param graph the input graph - * @param edge_weights the edge weights to be used to determine vertex/vertex distances - */ - public ClosenessCentrality(Hypergraph graph, Transformer edge_weights) - { - super(graph, edge_weights, true); - } - - /** - * Creates an instance which measures distance on the graph without edge weights. - * @param graph - */ - public ClosenessCentrality(Hypergraph graph) - { - super(graph, true); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/DegreeScorer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/DegreeScorer.java deleted file mode 100644 index 2ec3148104..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/DegreeScorer.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Created on Jul 6, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Assigns a score to each vertex equal to its degree. - * - * @param the vertex type - */ -public class DegreeScorer implements VertexScorer -{ - /** - * The graph for which scores are to be generated. - */ - protected Hypergraph graph; - - /** - * Creates an instance for the specified graph. - * @param graph the input graph - */ - public DegreeScorer(Hypergraph graph) - { - this.graph = graph; - } - - /** - * Returns the degree of the vertex. - * @return the degree of the vertex - */ - public Integer getVertexScore(V v) - { - return graph.degree(v); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/DistanceCentralityScorer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/DistanceCentralityScorer.java deleted file mode 100644 index 16dd86219d..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/DistanceCentralityScorer.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Created on Jul 10, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.shortestpath.DijkstraDistance; -import edu.uci.ics.jung.algorithms.shortestpath.Distance; -import edu.uci.ics.jung.algorithms.shortestpath.UnweightedShortestPath; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Assigns scores to vertices based on their distances to each other vertex - * in the graph. - * - * This class optionally normalizes its results based on the value of its - * 'averaging' constructor parameter. If it is true, - * then the value returned for vertex v is 1 / (_average_ distance from v to all other vertices); - * this is sometimes called closeness centrality. - * If it is false, then the value returned is 1 / (_total_ distance from - * v to all other vertices); this is sometimes referred to as barycenter centrality. - * (If the average/total distance is 0, the value returned is {@code Double.POSITIVE_INFINITY}.) - * - * @see BarycenterScorer - * @see ClosenessCentrality - */ -public class DistanceCentralityScorer implements VertexScorer -{ - /** - * The graph on which the vertex scores are to be calculated. - */ - protected Hypergraph graph; - - /** - * The metric to use for specifying the distance between pairs of vertices. - */ - protected Distance distance; - - /** - * The cache for the output results. Null encodes "not yet calculated", - * < 0 encodes "no such distance exists". - */ - protected Map output; - - /** - * Specifies whether the values returned are the sum of the v-distances - * or the mean v-distance. - */ - protected boolean averaging; - - /** - * Specifies whether, for a vertex v with missing (null) distances, - * v's score should ignore the missing values or be set to 'null'. - * Defaults to 'true'. - */ - protected boolean ignore_missing; - - /** - * Specifies whether the values returned should ignore self-distances - * (distances from v to itself). - * Defaults to 'true'. - */ - protected boolean ignore_self_distances; - - /** - * Creates an instance with the specified graph, distance metric, and - * averaging behavior. - * - * @param graph The graph on which the vertex scores are to be calculated. - * @param distance The metric to use for specifying the distance between - * pairs of vertices. - * @param averaging Specifies whether the values returned is the sum of all - * v-distances or the mean v-distance. - * @param ignore_missing Specifies whether scores for missing distances - * are to ignore missing distances or be set to null. - * @param ignore_self_distances Specifies whether distances from a vertex - * to itself should be included in its score. - */ - public DistanceCentralityScorer(Hypergraph graph, Distance distance, - boolean averaging, boolean ignore_missing, - boolean ignore_self_distances) - { - this.graph = graph; - this.distance = distance; - this.averaging = averaging; - this.ignore_missing = ignore_missing; - this.ignore_self_distances = ignore_self_distances; - this.output = new HashMap(); - } - - /** - * Equivalent to this(graph, distance, averaging, true, true). - * - * @param graph The graph on which the vertex scores are to be calculated. - * @param distance The metric to use for specifying the distance between - * pairs of vertices. - * @param averaging Specifies whether the values returned is the sum of all - * v-distances or the mean v-distance. - */ - public DistanceCentralityScorer(Hypergraph graph, Distance distance, - boolean averaging) - { - this(graph, distance, averaging, true, true); - } - - /** - * Creates an instance with the specified graph and averaging behavior - * whose vertex distances are calculated based on the specified edge - * weights. - * - * @param graph The graph on which the vertex scores are to be - * calculated. - * @param edge_weights The edge weights to use for specifying the distance - * between pairs of vertices. - * @param averaging Specifies whether the values returned is the sum of - * all v-distances or the mean v-distance. - * @param ignore_missing Specifies whether scores for missing distances - * are to ignore missing distances or be set to null. - * @param ignore_self_distances Specifies whether distances from a vertex - * to itself should be included in its score. - */ - public DistanceCentralityScorer(Hypergraph graph, - Transformer edge_weights, boolean averaging, - boolean ignore_missing, boolean ignore_self_distances) - { - this(graph, new DijkstraDistance(graph, edge_weights), averaging, - ignore_missing, ignore_self_distances); - } - - /** - * Equivalent to this(graph, edge_weights, averaging, true, true). - * @param graph The graph on which the vertex scores are to be - * calculated. - * @param edge_weights The edge weights to use for specifying the distance - * between pairs of vertices. - * @param averaging Specifies whether the values returned is the sum of - * all v-distances or the mean v-distance. - */ - public DistanceCentralityScorer(Hypergraph graph, - Transformer edge_weights, boolean averaging) - { - this(graph, new DijkstraDistance(graph, edge_weights), averaging, - true, true); - } - - /** - * Creates an instance with the specified graph and averaging behavior - * whose vertex distances are calculated on the unweighted graph. - * - * @param graph The graph on which the vertex scores are to be - * calculated. - * @param averaging Specifies whether the values returned is the sum of - * all v-distances or the mean v-distance. - * @param ignore_missing Specifies whether scores for missing distances - * are to ignore missing distances or be set to null. - * @param ignore_self_distances Specifies whether distances from a vertex - * to itself should be included in its score. - */ - public DistanceCentralityScorer(Hypergraph graph, boolean averaging, - boolean ignore_missing, boolean ignore_self_distances) - { - this(graph, new UnweightedShortestPath(graph), averaging, - ignore_missing, ignore_self_distances); - } - - /** - * Equivalent to this(graph, averaging, true, true). - * @param graph The graph on which the vertex scores are to be - * calculated. - * @param averaging Specifies whether the values returned is the sum of - * all v-distances or the mean v-distance. - */ - public DistanceCentralityScorer(Hypergraph graph, boolean averaging) - { - this(graph, new UnweightedShortestPath(graph), averaging, true, true); - } - - /** - * Calculates the score for the specified vertex. Returns {@code null} if - * there are missing distances and such are not ignored by this instance. - */ - public Double getVertexScore(V v) - { - Double value = output.get(v); - if (value != null) - { - if (value < 0) - return null; - return value; - } - - Map v_distances = new HashMap(distance.getDistanceMap(v)); - if (ignore_self_distances) - v_distances.remove(v); - - // if we don't ignore missing distances and there aren't enough - // distances, output null (shortcut) - if (!ignore_missing) - { - int num_dests = graph.getVertexCount() - - (ignore_self_distances ? 1 : 0); - if (v_distances.size() != num_dests) - { - output.put(v, -1.0); - return null; - } - } - - Double sum = 0.0; - for (V w : graph.getVertices()) - { - if (w.equals(v) && ignore_self_distances) - continue; - Number w_distance = v_distances.get(w); - if (w_distance == null) - if (ignore_missing) - continue; - else - { - output.put(v, -1.0); - return null; - } - else - sum += w_distance.doubleValue(); - } - value = sum; - if (averaging) - value /= v_distances.size(); - - double score = value == 0 ? - Double.POSITIVE_INFINITY : - 1.0 / value; - output.put(v, score); - - return score; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/EdgeScorer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/EdgeScorer.java deleted file mode 100644 index 7e648746d0..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/EdgeScorer.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Created on Jul 6, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - - -/** - * An interface for algorithms that assign scores to edges. - * - * @param the edge type - * @param the score type - */ -public interface EdgeScorer -{ - /** - * Returns the algorithm's score for this edge. - * @return the algorithm's score for this edge - */ - public S getEdgeScore(E e); -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/EigenvectorCentrality.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/EigenvectorCentrality.java deleted file mode 100644 index 87d7f3ae10..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/EigenvectorCentrality.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Created on Jul 12, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Calculates eigenvector centrality for each vertex in the graph. - * The 'eigenvector centrality' for a vertex is defined as the fraction of - * time that a random walk(er) will spend at that vertex over an infinite - * time horizon. - * Assumes that the graph is strongly connected. - */ -public class EigenvectorCentrality extends PageRank -{ - /** - * Creates an instance with the specified graph and edge weights. - * The outgoing edge weights for each edge must sum to 1. - * (See UniformDegreeWeight for one way to handle this for - * undirected graphs.) - * @param graph the graph for which the centrality is to be calculated - * @param edge_weights the edge weights - */ - public EigenvectorCentrality(Hypergraph graph, - Transformer edge_weights) - { - super(graph, edge_weights, 0); - acceptDisconnectedGraph(false); - } - - /** - * Creates an instance with the specified graph and default edge weights. - * (Default edge weights: UniformDegreeWeight.) - * @param graph the graph for which the centrality is to be calculated. - */ - public EigenvectorCentrality(Hypergraph graph) - { - super(graph, 0); - acceptDisconnectedGraph(false); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/HITS.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/HITS.java deleted file mode 100644 index b1b4f42899..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/HITS.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Created on Jul 15, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import edu.uci.ics.jung.algorithms.scoring.util.ScoringUtils; -import edu.uci.ics.jung.graph.Graph; - -import org.apache.commons.collections15.Transformer; - -/** - * Assigns hub and authority scores to each vertex depending on the topology of - * the network. The essential idea is that a vertex is a hub to the extent - * that it links to authoritative vertices, and is an authority to the extent - * that it links to 'hub' vertices. - * - *

      The classic HITS algorithm essentially proceeds as follows: - *

      - * assign equal initial hub and authority values to each vertex
      - * repeat
      - *   for each vertex w:
      - *     w.hub = sum over successors x of x.authority
      - *     w.authority = sum over predecessors v of v.hub
      - *   normalize hub and authority scores so that the sum of the squares of each = 1
      - * until scores converge
      - * 
      - * - * HITS is somewhat different from random walk/eigenvector-based algorithms - * such as PageRank in that: - *
        - *
      • there are two mutually recursive scores being calculated, rather than - * a single value - *
      • the edge weights are effectively all 1, i.e., they can't be interpreted - * as transition probabilities. This means that the more inlinks and outlinks - * that a vertex has, the better, since adding an inlink (or outlink) does - * not dilute the influence of the other inlinks (or outlinks) as in - * random walk-based algorithms. - *
      • the scores cannot be interpreted as posterior probabilities (due to the different - * normalization) - *
      - * - * This implementation has the classic behavior by default. However, it has - * been generalized somewhat so that it can act in a more "PageRank-like" fashion: - *
        - *
      • this implementation has an optional 'random jump probability' parameter analogous - * to the 'alpha' parameter used by PageRank. Varying this value between 0 and 1 - * allows the user to vary between the classic HITS behavior and one in which the - * scores are smoothed to a uniform distribution. - * The default value for this parameter is 0 (no random jumps possible). - *
      • the edge weights can be set to anything the user likes, and in - * particular they can be set up (e.g. using UniformDegreeWeight) - * so that the weights of the relevant edges incident to a vertex sum to 1. - *
      • The vertex score normalization has been factored into its own method - * so that it can be overridden by a subclass. Thus, for example, - * since the vertices' values are set to sum to 1 initially, if the weights of the - * relevant edges incident to a vertex sum to 1, then the vertices' values - * will continue to sum to 1 if the "sum-of-squares" normalization code - * is overridden to a no-op. (Other normalization methods may also be employed.) - *
      - * - * @param the vertex type - * @param the edge type - * - * @see "'Authoritative sources in a hyperlinked environment' by Jon Kleinberg, 1997" - */ -public class HITS extends HITSWithPriors -{ - - /** - * Creates an instance for the specified graph, edge weights, and alpha - * (random jump probability) parameter. - * @param g the input graph - * @param edge_weights the weights to use for each edge - * @param alpha the probability of a hub giving some authority to all vertices, - * and of an authority increasing the score of all hubs (not just those connected - * via links) - */ - public HITS(Graph g, Transformer edge_weights, double alpha) - { - super(g, edge_weights, ScoringUtils.getHITSUniformRootPrior(g.getVertices()), alpha); - } - - /** - * Creates an instance for the specified graph and alpha (random jump probability) - * parameter. The edge weights are all set to 1. - * @param g the input graph - * @param alpha the probability of a hub giving some authority to all vertices, - * and of an authority increasing the score of all hubs (not just those connected - * via links) - */ - public HITS(Graph g, double alpha) - { - super(g, ScoringUtils.getHITSUniformRootPrior(g.getVertices()), alpha); - } - - /** - * Creates an instance for the specified graph. The edge weights are all set to 1 - * and alpha is set to 0. - * @param g the input graph - */ - public HITS(Graph g) - { - this(g, 0.0); - } - - - /** - * Maintains hub and authority score information for a vertex. - */ - public static class Scores - { - /** - * The hub score for a vertex. - */ - public double hub; - - /** - * The authority score for a vertex. - */ - public double authority; - - /** - * Creates an instance with the specified hub and authority score. - */ - public Scores(double hub, double authority) - { - this.hub = hub; - this.authority = authority; - } - - @Override - public String toString() - { - return String.format("[h:%.4f,a:%.4f]", this.hub, this.authority); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/HITSWithPriors.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/HITSWithPriors.java deleted file mode 100644 index 51ba71903e..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/HITSWithPriors.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Created on Jul 14, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.functors.ConstantTransformer; - -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * A generalization of HITS that permits non-uniformly-distributed random jumps. - * The 'vertex_priors' (that is, prior probabilities for each vertex) may be - * thought of as the fraction of the total 'potential' (hub or authority score) - * that is assigned to that vertex out of the portion that is assigned according - * to random jumps. - * - * @see "Algorithms for Estimating Relative Importance in Graphs by Scott White and Padhraic Smyth, 2003" - */ -public class HITSWithPriors - extends AbstractIterativeScorerWithPriors -{ - /** - * The sum of the potential, at each step, associated with vertices with no outedges (authority) - * or no inedges (hub). - */ - protected HITS.Scores disappearing_potential; - - /** - * Creates an instance for the specified graph, edge weights, vertex prior probabilities, - * and random jump probability (alpha). - * @param g the input graph - * @param edge_weights the edge weights - * @param vertex_priors the prior probability for each vertex - * @param alpha the probability of a random jump at each step - */ - public HITSWithPriors(Hypergraph g, - Transformer edge_weights, - Transformer vertex_priors, double alpha) - { - super(g, edge_weights, vertex_priors, alpha); - disappearing_potential = new HITS.Scores(0,0); - } - - /** - * Creates an instance for the specified graph, vertex priors, and random - * jump probability (alpha). The edge weights default to 1.0. - * @param g the input graph - * @param vertex_priors the prior probability for each vertex - * @param alpha the probability of a random jump at each step - */ - @SuppressWarnings("unchecked") - public HITSWithPriors(Hypergraph g, - Transformer vertex_priors, double alpha) - { - super(g, new ConstantTransformer(1.0), vertex_priors, alpha); - disappearing_potential = new HITS.Scores(0,0); - } - - /** - * Updates the value for this vertex. - */ - @Override - protected double update(V v) - { - collectDisappearingPotential(v); - - double v_auth = 0; - for (E e : graph.getInEdges(v)) - { - int incident_count = getAdjustedIncidentCount(e); - for (V w : graph.getIncidentVertices(e)) - { - if (!w.equals(v) || hyperedges_are_self_loops) - v_auth += (getCurrentValue(w).hub * - getEdgeWeight(w,e).doubleValue() / incident_count); - } -// V w = graph.getOpposite(v, e); -// auth += (getCurrentValue(w).hub * getEdgeWeight(w, e).doubleValue()); - } - - double v_hub = 0; - for (E e : graph.getOutEdges(v)) - { - int incident_count = getAdjustedIncidentCount(e); - for (V w : graph.getIncidentVertices(e)) - { - if (!w.equals(v) || hyperedges_are_self_loops) - v_hub += (getCurrentValue(w).authority * - getEdgeWeight(w,e).doubleValue() / incident_count); - } -// V x = graph.getOpposite(v,e); -// hub += (getCurrentValue(x).authority * getEdgeWeight(x, e).doubleValue()); - } - - // modify total_input according to alpha - if (alpha > 0) - { - v_auth = v_auth * (1 - alpha) + getVertexPrior(v).authority * alpha; - v_hub = v_hub * (1 - alpha) + getVertexPrior(v).hub * alpha; - } - setOutputValue(v, new HITS.Scores(v_hub, v_auth)); - - return Math.max(Math.abs(getCurrentValue(v).hub - v_hub), - Math.abs(getCurrentValue(v).authority - v_auth)); - } - - /** - * Code which is executed after each step. In this case, deals with the - * 'disappearing potential', normalizes the scores, and then calls - * super.afterStep(). - * @see #collectDisappearingPotential(Object) - */ - @Override - protected void afterStep() - { - if (disappearing_potential.hub > 0 || disappearing_potential.authority > 0) - { - for (V v : graph.getVertices()) - { - double new_hub = getOutputValue(v).hub + - (1 - alpha) * (disappearing_potential.hub * getVertexPrior(v).hub); - double new_auth = getOutputValue(v).authority + - (1 - alpha) * (disappearing_potential.authority * getVertexPrior(v).authority); - setOutputValue(v, new HITS.Scores(new_hub, new_auth)); - } - disappearing_potential.hub = 0; - disappearing_potential.authority = 0; - } - - normalizeScores(); - - super.afterStep(); - } - - /** - * Normalizes scores so that sum of their squares = 1. - * This method may be overridden so as to yield different - * normalizations. - */ - protected void normalizeScores() { - double hub_ssum = 0; - double auth_ssum = 0; - for (V v : graph.getVertices()) - { - double hub_val = getOutputValue(v).hub; - double auth_val = getOutputValue(v).authority; - hub_ssum += (hub_val * hub_val); - auth_ssum += (auth_val * auth_val); - } - - hub_ssum = Math.sqrt(hub_ssum); - auth_ssum = Math.sqrt(auth_ssum); - - for (V v : graph.getVertices()) - { - HITS.Scores values = getOutputValue(v); - setOutputValue(v, new HITS.Scores( - values.hub / hub_ssum, - values.authority / auth_ssum)); - } - } - - /** - * Collects the "disappearing potential" associated with vertices that have either - * no incoming edges, no outgoing edges, or both. Vertices that have no incoming edges - * do not directly contribute to the hub scores of other vertices; similarly, vertices - * that have no outgoing edges do not directly contribute to the authority scores of - * other vertices. These values are collected at each step and then distributed across all vertices - * as a part of the normalization process. (This process is not required for, and does - * not affect, the 'sum-of-squares'-style normalization.) - */ - @Override - protected void collectDisappearingPotential(V v) - { - if (graph.outDegree(v) == 0) - { - if (isDisconnectedGraphOK()) - disappearing_potential.hub += getCurrentValue(v).authority; - else - throw new IllegalArgumentException("Outdegree of " + v + " must be > 0"); - } - if (graph.inDegree(v) == 0) - { - if (isDisconnectedGraphOK()) - disappearing_potential.authority += getCurrentValue(v).hub; - else - throw new IllegalArgumentException("Indegree of " + v + " must be > 0"); - } - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/KStepMarkov.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/KStepMarkov.java deleted file mode 100644 index e640b1b3f3..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/KStepMarkov.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * Created on Aug 22, 2008 - * - */ -package edu.uci.ics.jung.algorithms.scoring; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.util.ScoringUtils; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * A special case of {@code PageRankWithPriors} in which the final scores - * represent a probability distribution over position assuming a random (Markovian) - * walk of exactly k steps, based on the initial distribution specified by the priors. - * - *

      NOTE: The version of {@code KStepMarkov} in {@code algorithms.importance} - * (and in JUNG 1.x) is believed to be incorrect: rather than returning - * a score which represents a probability distribution over position assuming - * a k-step random walk, it returns a score which represents the sum over all steps - * of the probability for each step. If you want that behavior, set the - * 'cumulative' flag as follows before calling {@code evaluate()}: - *

      - *     KStepMarkov ksm = new KStepMarkov(...);
      - *     ksm.setCumulative(true);
      - *     ksm.evaluate();
      - * 
      - * - * By default, the 'cumulative' flag is set to false. - * - * NOTE: THIS CLASS IS NOT YET COMPLETE. USE AT YOUR OWN RISK. (The original behavior - * is captured by the version still available in {@code algorithms.importance}.) - * - * @see "Algorithms for Estimating Relative Importance in Graphs by Scott White and Padhraic Smyth, 2003" - * @see PageRank - * @see PageRankWithPriors - */ -public class KStepMarkov extends PageRankWithPriors -{ - private boolean cumulative; - - /** - * Creates an instance based on the specified graph, edge weights, vertex - * priors (initial scores), and number of steps to take. - * @param graph the input graph - * @param edge_weights the edge weights (transition probabilities) - * @param vertex_priors the initial probability distribution (score assignment) - * @param steps the number of times that {@code step()} will be called by {@code evaluate} - */ - public KStepMarkov(Hypergraph graph, Transformer edge_weights, - Transformer vertex_priors, int steps) - { - super(graph, edge_weights, vertex_priors, 0); - initialize(steps); - } - - /** - * Creates an instance based on the specified graph, vertex - * priors (initial scores), and number of steps to take. The edge - * weights (transition probabilities) are set to default values (a uniform - * distribution over all outgoing edges). - * @param graph the input graph - * @param vertex_priors the initial probability distribution (score assignment) - * @param steps the number of times that {@code step()} will be called by {@code evaluate} - */ - public KStepMarkov(Hypergraph graph, Transformer vertex_priors, int steps) - { - super(graph, vertex_priors, 0); - initialize(steps); - } - - /** - * Creates an instance based on the specified graph and number of steps to - * take. The edge weights (transition probabilities) and vertex initial scores - * (prior probabilities) are set to default values (a uniform - * distribution over all outgoing edges, and a uniform distribution over - * all vertices, respectively). - * @param graph the input graph - * @param steps the number of times that {@code step()} will be called by {@code evaluate} - */ - public KStepMarkov(Hypergraph graph, int steps) - { - super(graph, ScoringUtils.getUniformRootPrior(graph.getVertices()), 0); - initialize(steps); - } - - private void initialize(int steps) - { - this.acceptDisconnectedGraph(false); - - if (steps <= 0) - throw new IllegalArgumentException("Number of steps must be > 0"); - - this.max_iterations = steps; - this.tolerance = -1.0; - - this.cumulative = false; - } - - /** - * Specifies whether this instance should assign a score to each vertex - * based on the - * @param cumulative - */ - public void setCumulative(boolean cumulative) - { - this.cumulative = cumulative; - } - - /** - * Updates the value for this vertex. Called by step(). - */ - @Override - public double update(V v) - { - if (!cumulative) - return super.update(v); - - collectDisappearingPotential(v); - - double v_input = 0; - for (E e : graph.getInEdges(v)) - { - // For graphs, the code below is equivalent to -// V w = graph.getOpposite(v, e); -// total_input += (getCurrentValue(w) * getEdgeWeight(w,e).doubleValue()); - // For hypergraphs, this divides the potential coming from w - // by the number of vertices in the connecting edge e. - int incident_count = getAdjustedIncidentCount(e); - for (V w : graph.getIncidentVertices(e)) - { - if (!w.equals(v) || hyperedges_are_self_loops) - v_input += (getCurrentValue(w) * - getEdgeWeight(w,e).doubleValue() / incident_count); - } - } - - // modify total_input according to alpha - double new_value = alpha > 0 ? - v_input * (1 - alpha) + getVertexPrior(v) * alpha : - v_input; - setOutputValue(v, new_value + getCurrentValue(v)); - - // FIXME: DO WE NEED TO CHANGE HOW DISAPPEARING IS COUNTED? NORMALIZE? - - return Math.abs(getCurrentValue(v) - new_value); - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/PageRank.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/PageRank.java deleted file mode 100644 index ca7266d58f..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/PageRank.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Created on Jul 12, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.util.ScoringUtils; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Assigns scores to each vertex according to the PageRank algorithm. - * - *

      PageRank is an eigenvector-based algorithm. The score for a given vertex may be thought of - * as the fraction of time spent 'visiting' that vertex (measured over all time) - * in a random walk over the vertices (following outgoing edges from each vertex). - * PageRank modifies this random walk by adding to the model a probability (specified as 'alpha' - * in the constructor) of jumping to any vertex. If alpha is 0, this is equivalent to the - * eigenvector centrality algorithm; if alpha is 1, all vertices will receive the same score - * (1/|V|). Thus, alpha acts as a sort of score smoothing parameter. - * - *

      The original algorithm assumed that, for a given vertex, the probability of following any - * outgoing edge was the same; this is the default if edge weights are not specified. - * This implementation generalizes the original by permitting - * the user to specify edge weights; in order to maintain the original semantics, however, - * the weights on the outgoing edges for a given vertex must represent transition probabilities; - * that is, they must sum to 1. - * - *

      If a vertex has no outgoing edges, then the probability of taking a random jump from that - * vertex is (by default) effectively 1. If the user wishes to instead throw an exception when this happens, - * call acceptDisconnectedGraph(false) on this instance. - * - *

      Typical values for alpha (according to the original paper) are in the range [0.1, 0.2] - * but may be any value between 0 and 1 inclusive. - * - * @see "The Anatomy of a Large-Scale Hypertextual Web Search Engine by L. Page and S. Brin, 1999" - */ -public class PageRank extends PageRankWithPriors -{ - - /** - * Creates an instance for the specified graph, edge weights, and random jump probability. - * @param graph the input graph - * @param edge_weight the edge weights (transition probabilities) - * @param alpha the probability of taking a random jump to an arbitrary vertex - */ - public PageRank(Hypergraph graph, Transformer edge_weight, double alpha) - { - super(graph, edge_weight, ScoringUtils.getUniformRootPrior(graph.getVertices()), alpha); - } - - /** - * Creates an instance for the specified graph and random jump probability; the probability - * of following any outgoing edge from a given vertex is the same. - * @param graph the input graph - * @param alpha the probability of taking a random jump to an arbitrary vertex - */ - public PageRank(Hypergraph graph, double alpha) - { - super(graph, ScoringUtils.getUniformRootPrior(graph.getVertices()), alpha); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/PageRankWithPriors.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/PageRankWithPriors.java deleted file mode 100644 index 717d5eafe1..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/PageRankWithPriors.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Created on Jul 6, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.util.UniformDegreeWeight; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * A generalization of PageRank that permits non-uniformly-distributed random jumps. - * The 'vertex_priors' (that is, prior probabilities for each vertex) may be - * thought of as the fraction of the total 'potential' that is assigned to that - * vertex at each step out of the portion that is assigned according - * to random jumps (this portion is specified by 'alpha'). - * - * @see "Algorithms for Estimating Relative Importance in Graphs by Scott White and Padhraic Smyth, 2003" - * @see PageRank - */ -public class PageRankWithPriors - extends AbstractIterativeScorerWithPriors -{ - /** - * Maintains the amount of potential associated with vertices with no out-edges. - */ - protected double disappearing_potential = 0.0; - - /** - * Creates an instance with the specified graph, edge weights, vertex priors, and - * 'random jump' probability (alpha). - * @param graph the input graph - * @param edge_weights the edge weights, denoting transition probabilities from source to destination - * @param vertex_priors the prior probabilities for each vertex - * @param alpha the probability of executing a 'random jump' at each step - */ - public PageRankWithPriors(Hypergraph graph, - Transformer edge_weights, - Transformer vertex_priors, double alpha) - { - super(graph, edge_weights, vertex_priors, alpha); - } - - /** - * Creates an instance with the specified graph, vertex priors, and - * 'random jump' probability (alpha). The outgoing edge weights for each - * vertex will be equal and sum to 1. - * @param graph the input graph - * @param vertex_priors the prior probabilities for each vertex - * @param alpha the probability of executing a 'random jump' at each step - */ - public PageRankWithPriors(Hypergraph graph, - Transformer vertex_priors, double alpha) - { - super(graph, vertex_priors, alpha); - this.edge_weights = new UniformDegreeWeight(graph); - } - - /** - * Updates the value for this vertex. Called by step(). - */ - @Override - public double update(V v) - { - collectDisappearingPotential(v); - - double v_input = 0; - for (E e : graph.getInEdges(v)) - { - // For graphs, the code below is equivalent to -// V w = graph.getOpposite(v, e); -// total_input += (getCurrentValue(w) * getEdgeWeight(w,e).doubleValue()); - // For hypergraphs, this divides the potential coming from w - // by the number of vertices in the connecting edge e. - int incident_count = getAdjustedIncidentCount(e); - for (V w : graph.getIncidentVertices(e)) - { - if (!w.equals(v) || hyperedges_are_self_loops) - v_input += (getCurrentValue(w) * - getEdgeWeight(w,e).doubleValue() / incident_count); - } - } - - // modify total_input according to alpha - double new_value = alpha > 0 ? - v_input * (1 - alpha) + getVertexPrior(v) * alpha : - v_input; - setOutputValue(v, new_value); - - return Math.abs(getCurrentValue(v) - new_value); - } - - /** - * Cleans up after each step. In this case that involves allocating the disappearing - * potential (thus maintaining normalization of the scores) according to the vertex - * probability priors, and then calling - * super.afterStep. - */ - @Override - protected void afterStep() - { - // distribute disappearing potential according to priors - if (disappearing_potential > 0) - { - for (V v : graph.getVertices()) - { - setOutputValue(v, getOutputValue(v) + - (1 - alpha) * (disappearing_potential * getVertexPrior(v))); - } - disappearing_potential = 0; - } - - super.afterStep(); - } - - /** - * Collects the "disappearing potential" associated with vertices that have - * no outgoing edges. Vertices that have no outgoing edges do not directly - * contribute to the scores of other vertices. These values are collected - * at each step and then distributed across all vertices - * as a part of the normalization process. - */ - @Override - protected void collectDisappearingPotential(V v) - { - if (graph.outDegree(v) == 0) - { - if (isDisconnectedGraphOK()) - disappearing_potential += getCurrentValue(v); - else - throw new IllegalArgumentException("Outdegree of " + v + " must be > 0"); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/VertexScorer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/VertexScorer.java deleted file mode 100644 index 610de6b5a6..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/VertexScorer.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Created on Jul 6, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - - -/** - * An interface for algorithms that assign scores to vertices. - * - * @param the vertex type - * @param the score type - */ -public interface VertexScorer -{ - /** - * Returns the algorithm's score for this vertex. - * @return the algorithm's score for this vertex - */ - public S getVertexScore(V v); -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/VoltageScorer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/VoltageScorer.java deleted file mode 100644 index f05b911091..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/VoltageScorer.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Created on Jul 15, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.util.UniformDegreeWeight; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Assigns scores to vertices according to their 'voltage' in an approximate - * solution to the Kirchoff equations. This is accomplished by tying "source" - * vertices to specified positive voltages, "sink" vertices to 0 V, and - * iteratively updating the voltage of each other vertex to the (weighted) - * average of the voltages of its neighbors. - * - *

      The resultant voltages will all be in the range [0, max] - * where max is the largest voltage of any source vertex (in the - * absence of negative source voltages; see below). - * - *

      A few notes about this algorithm's interpretation of the graph data: - *

        - *
      • Higher edge weights are interpreted as indicative of greater - * influence/effect than lower edge weights. - *
      • Negative edge weights (and negative "source" voltages) invalidate - * the interpretation of the resultant values as voltages. However, this - * algorithm will not reject graphs with negative edge weights or source voltages. - *
      • Parallel edges are equivalent to a single edge whose weight is the - * sum of the weights on the parallel edges. - *
      • Current flows along undirected edges in both directions, - * but only flows along directed edges in the direction of the edge. - *
      - *

      - */ -public class VoltageScorer extends AbstractIterativeScorer - implements VertexScorer -{ - protected Map source_voltages; - protected Collection sinks; - - /** - * Creates an instance with the specified graph, edge weights, source voltages, - * and sinks. - * @param g the input graph - * @param edge_weights the edge weights, representing conductivity - * @param source_voltages the (fixed) voltage for each source - * @param sinks the vertices whose voltages are tied to 0 - */ - public VoltageScorer(Hypergraph g, Transformer edge_weights, - Map source_voltages, Collection sinks) - { - super(g, edge_weights); - this.source_voltages = source_voltages; - this.sinks = sinks; - initialize(); - } - - /** - * Creates an instance with the specified graph, edge weights, source vertices - * (each of whose 'voltages' are tied to 1), and sinks. - * @param g the input graph - * @param edge_weights the edge weights, representing conductivity - * @param sources the vertices whose voltages are tied to 1 - * @param sinks the vertices whose voltages are tied to 0 - */ - public VoltageScorer(Hypergraph g, Transformer edge_weights, - Collection sources, Collection sinks) - { - super(g, edge_weights); - - Map unit_voltages = new HashMap(); - for(V v : sources) - unit_voltages.put(v, new Double(1.0)); - this.source_voltages = unit_voltages; - this.sinks = sinks; - initialize(); - } - - /** - * Creates an instance with the specified graph, source vertices - * (each of whose 'voltages' are tied to 1), and sinks. - * The outgoing edges for each vertex are assigned - * weights that sum to 1. - * @param g the input graph - * @param sources the vertices whose voltages are tied to 1 - * @param sinks the vertices whose voltages are tied to 0 - */ - public VoltageScorer(Hypergraph g, Collection sources, Collection sinks) - { - super(g); - - Map unit_voltages = new HashMap(); - for(V v : sources) - unit_voltages.put(v, new Double(1.0)); - this.source_voltages = unit_voltages; - this.sinks = sinks; - initialize(); - } - - /** - * Creates an instance with the specified graph, source voltages, - * and sinks. The outgoing edges for each vertex are assigned - * weights that sum to 1. - * @param g the input graph - * @param source_voltages the (fixed) voltage for each source - * @param sinks the vertices whose voltages are tied to 0 - */ - public VoltageScorer(Hypergraph g, Map source_voltages, - Collection sinks) - { - super(g); - this.source_voltages = source_voltages; - this.sinks = sinks; - this.edge_weights = new UniformDegreeWeight(g); - initialize(); - } - - /** - * Creates an instance with the specified graph, edge weights, source, and - * sink. The source vertex voltage is tied to 1. - * @param g the input graph - * @param edge_weights the edge weights, representing conductivity - * @param source the vertex whose voltage is tied to 1 - * @param sink the vertex whose voltage is tied to 0 - */ - public VoltageScorer(Hypergraph g, Transformer edge_weights, - V source, V sink) - { - this(g, edge_weights, Collections.singletonMap(source, 1.0), Collections.singletonList(sink)); - initialize(); - } - - /** - * Creates an instance with the specified graph, edge weights, source, and - * sink. The source vertex voltage is tied to 1. - * The outgoing edges for each vertex are assigned - * weights that sum to 1. - * @param g the input graph - * @param source the vertex whose voltage is tied to 1 - * @param sink the vertex whose voltage is tied to 0 - */ - public VoltageScorer(Hypergraph g, V source, V sink) - { - this(g, Collections.singletonMap(source, 1.0), Collections.singletonList(sink)); - initialize(); - } - - - /** - * Initializes the state of this instance. - */ - @Override - public void initialize() - { - super.initialize(); - - // sanity check - if (source_voltages.isEmpty() || sinks.isEmpty()) - throw new IllegalArgumentException("Both sources and sinks (grounds) must be defined"); - - if (source_voltages.size() + sinks.size() > graph.getVertexCount()) - throw new IllegalArgumentException("Source/sink sets overlap, or contain vertices not in graph"); - - for (Map.Entry entry : source_voltages.entrySet()) - { - V v = entry.getKey(); - if (sinks.contains(v)) - throw new IllegalArgumentException("Vertex " + v + " is incorrectly specified as both source and sink"); - double value = entry.getValue().doubleValue(); - if (value <= 0) - throw new IllegalArgumentException("Source vertex " + v + " has negative voltage"); - } - - // set up initial voltages - for (V v : graph.getVertices()) - { - if (source_voltages.containsKey(v)) - setOutputValue(v, source_voltages.get(v).doubleValue()); - else - setOutputValue(v, 0.0); - } - } - - /** - * @see edu.uci.ics.jung.algorithms.scoring.AbstractIterativeScorer#update(Object) - */ - @Override - public double update(V v) - { - // if it's a voltage source or sink, we're done - Number source_volts = source_voltages.get(v); - if (source_volts != null) - { - setOutputValue(v, source_volts.doubleValue()); - return 0.0; - } - if (sinks.contains(v)) - { - setOutputValue(v, 0.0); - return 0.0; - } - - Collection edges = graph.getInEdges(v); - double voltage_sum = 0; - double weight_sum = 0; - for (E e: edges) - { - int incident_count = getAdjustedIncidentCount(e); - for (V w : graph.getIncidentVertices(e)) - { - if (!w.equals(v) || hyperedges_are_self_loops) - { - double weight = getEdgeWeight(w,e).doubleValue() / incident_count; - voltage_sum += getCurrentValue(w).doubleValue() * weight; - weight_sum += weight; - } - } -// V w = graph.getOpposite(v, e); -// double weight = getEdgeWeight(w,e).doubleValue(); -// voltage_sum += getCurrentValue(w).doubleValue() * weight; -// weight_sum += weight; - } - - // if either is 0, new value is 0 - if (voltage_sum == 0 || weight_sum == 0) - { - setOutputValue(v, 0.0); - return getCurrentValue(v).doubleValue(); - } - - setOutputValue(v, voltage_sum / weight_sum); - return Math.abs(getCurrentValue(v).doubleValue() - voltage_sum / weight_sum); - } - -} - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/package.html deleted file mode 100644 index a1f8196ebf..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/package.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - -Mechanisms for assigning values (denoting significance, influence, centrality, etc.) -to graph elements based on topological properties. These include: - -
        -
      • BarycenterScorer: assigns a score to each vertex according to -the sum of the distances to all other vertices -
      • ClosenessCentrality: assigns a score to each vertex based on -the mean distance to each other vertex -
      • DegreeScorer: assigns a score to each vertex based on its degree -
      • EigenvectorCentrality: assigns vertex scores based on -long-term probabilities of random walks passing through the vertex at time t -
      • PageRank: like EigenvectorCentrality, but with -a constant probability of the -random walk restarting at a uniform-randomly chosen vertex -
      • PageRankWithPriors: like PageRank, but with a -constant probability of the random -walk restarting at a vertex drawn from an arbitrary distribution -
      • HITS: assigns hubs-and-authorities scores to vertices based on -complementary random walk processes -
      • HITSWithPriors: analogous to HITS -(see PageRankWithPriors) -
      • VoltageScorer: assigns scores to vertices based on simulated -current flow along edges -
      - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/DelegateToEdgeTransformer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/DelegateToEdgeTransformer.java deleted file mode 100644 index f836a9b428..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/DelegateToEdgeTransformer.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Created on Jul 11, 2008 - * - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring.util; - -import org.apache.commons.collections15.Transformer; - -/** - * A Transformer that delegates its operation to a - * Transformer. Mainly useful for technical reasons inside - * AbstractIterativeScorer; in essence it allows the edge weight instance - * variable to be of type VEPair,W even if the edge weight - * Transformer only operates on edges. - */ -public class DelegateToEdgeTransformer implements - Transformer,Number> -{ - /** - * The transformer to which this instance delegates its function. - */ - protected Transformer delegate; - - /** - * Creates an instance with the specified delegate transformer. - * @param delegate the Transformer to which this instance will delegate - */ - public DelegateToEdgeTransformer(Transformer delegate) - { - this.delegate = delegate; - } - - /** - * @see Transformer#transform(Object) - */ - public Number transform(VEPair arg0) - { - return delegate.transform(arg0.getE()); - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/ScoringUtils.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/ScoringUtils.java deleted file mode 100644 index 793944b295..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/ScoringUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Created on Jul 12, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring.util; - -import java.util.Collection; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.HITS; - -/** - * Methods for assigning values (to be interpreted as prior probabilities) to vertices in the context - * of random-walk-based scoring algorithms. - */ -public class ScoringUtils -{ - /** - * Assigns a probability of 1/roots.size() to each of the elements of roots. - * @param the vertex type - * @param roots the vertices to be assigned nonzero prior probabilities - * @return - */ - public static Transformer getUniformRootPrior(Collection roots) - { - final Collection inner_roots = roots; - Transformer distribution = new Transformer() - { - public Double transform(V input) - { - if (inner_roots.contains(input)) - return new Double(1.0 / inner_roots.size()); - else - return 0.0; - } - }; - - return distribution; - } - - /** - * Returns a Transformer that hub and authority values of 1/roots.size() to each - * element of roots. - * @param the vertex type - * @param roots the vertices to be assigned nonzero scores - * @return a Transformer that assigns uniform prior hub/authority probabilities to each root - */ - public static Transformer getHITSUniformRootPrior(Collection roots) - { - final Collection inner_roots = roots; - Transformer distribution = - new Transformer() - { - public HITS.Scores transform(V input) - { - if (inner_roots.contains(input)) - return new HITS.Scores(1.0 / inner_roots.size(), 1.0 / inner_roots.size()); - else - return new HITS.Scores(0.0, 0.0); - } - }; - return distribution; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/UniformDegreeWeight.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/UniformDegreeWeight.java deleted file mode 100644 index f22bfcc891..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/UniformDegreeWeight.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * Created on Jul 14, 2008 - * - */ -package edu.uci.ics.jung.algorithms.scoring.util; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Hypergraph; -import edu.uci.ics.jung.graph.util.EdgeType; - -/** - * An edge weight function that assigns weights as uniform - * transition probabilities. - * For undirected edges, returns 1/degree(v) (where 'v' is the - * vertex in the VEPair. - * For directed edges, returns 1/outdegree(source(e)) (where 'e' - * is the edge in the VEPair). - * Throws an IllegalArgumentException if the input - * edge is neither EdgeType.UNDIRECTED nor EdgeType.DIRECTED. - * - */ -public class UniformDegreeWeight implements - Transformer, Double> -{ - private Hypergraph graph; - - /** - * Creates an instance for the specified graph. - */ - public UniformDegreeWeight(Hypergraph graph) - { - this.graph = graph; - } - - /** - * @see org.apache.commons.collections15.Transformer#transform(java.lang.Object) - */ - public Double transform(VEPair ve_pair) - { - E e = ve_pair.getE(); - V v = ve_pair.getV(); - EdgeType edge_type = graph.getEdgeType(e); - if (edge_type == EdgeType.UNDIRECTED) - return 1.0 / graph.degree(v); - if (edge_type == EdgeType.DIRECTED) - return 1.0 / graph.outDegree(graph.getSource(e)); - throw new IllegalArgumentException("can't handle edge type: " + edge_type); - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/UniformInOut.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/UniformInOut.java deleted file mode 100644 index 7853f002fd..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/UniformInOut.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Created on Jul 11, 2008 - * - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring.util; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.EdgeType; - -/** - * Assigns weights to directed edges (the edge of the vertex/edge pair) depending on - * whether the vertex is the edge's source or its destination. - * If the vertex v is the edge's source, assigns 1/outdegree(v). - * Otherwise, assigns 1/indegree(w). - * Throws IllegalArgumentException if the edge is not directed. - */ -public class UniformInOut implements Transformer, Double> -{ - /** - * The graph for which the edge weights are defined. - */ - protected Graph graph; - - /** - * Creates an instance for the specified graph. - * @param graph the graph for which the edge weights will be defined - */ - public UniformInOut(Graph graph) - { - this.graph = graph; - } - - /** - * @see org.apache.commons.collections15.Transformer#transform(Object) - * @throws IllegalArgumentException - */ - public Double transform(VEPair ve_pair) - { - V v = ve_pair.getV(); - E e = ve_pair.getE(); - if (graph.getEdgeType(e) != EdgeType.DIRECTED) - throw new IllegalArgumentException("This transformer only" + - " operates on directed edges"); - return 1.0 / (graph.isSource(v, e) ? - graph.outDegree(v) : - graph.inDegree(v)); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/VEPair.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/VEPair.java deleted file mode 100644 index ad9029359b..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/VEPair.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Created on Jul 8, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring.util; - -/** - * Convenience class for associating a vertex and an edge. Used, for example, - * in contexts in which it is necessary to know the origin for an edge traversal - * (that is, the direction in which an (undirected) edge is being traversed). - * - * @param the vertex type - * @param the edge type - */ -public class VEPair -{ - private V v; - private E e; - - /** - * Creates an instance with the specified vertex and edge - * @param v the vertex to add - * @param e the edge to add - */ - public VEPair(V v, E e) - { - if (v == null || e == null) - throw new IllegalArgumentException("elements must be non-null"); - - this.v = v; - this.e = e; - } - - /** - * Returns the vertex of this pair. - */ - public V getV() - { - return v; - } - - /** - * Returns the edge of this pair. - */ - public E getE() - { - return e; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/VertexScoreTransformer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/VertexScoreTransformer.java deleted file mode 100644 index 851c08eef8..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/VertexScoreTransformer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Created on Jul 18, 2008 - * - * Copyright (c) 2008, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.scoring.util; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.VertexScorer; - -/** - * A Transformer convenience wrapper around VertexScorer. - */ -public class VertexScoreTransformer implements Transformer -{ - /** - * The VertexScorer instance that provides the values returned by transform. - */ - protected VertexScorer vs; - - /** - * Creates an instance based on the specified VertexScorer. - */ - public VertexScoreTransformer(VertexScorer vs) - { - this.vs = vs; - } - - /** - * Returns the score for this vertex. - */ - public S transform(V v) - { - return vs.getVertexScore(v); - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/package.html deleted file mode 100644 index 3bf18f3584..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/scoring/util/package.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - -Utility functions for assigning scores to graph elements. These include: -
        -
      • EdgeWeight: interface for classes that associate numeric values -with edges -
      • ScoringUtils: methods for calculating transition probabilities -for random-walk-based algorithms. -
      • UniformOut: an edge weight function that assigns weights as uniform -transition probabilities to all outgoing edges of a vertex. -
      • UniformIncident: an edge weight function that assigns -weights as uniform transition probabilities to all incident edges of a -vertex (useful for undirected graphs). -
      • VEPair: analogous to Pair but specifically -containing an associated vertex and edge. -
      • VertexEdgeWeight: a subtype of EdgeWeight that -assigns edge weights with respect to a specified 'source' vertex. -
      - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/BFSDistanceLabeler.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/BFSDistanceLabeler.java deleted file mode 100644 index 38d3b001d6..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/BFSDistanceLabeler.java +++ /dev/null @@ -1,169 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.shortestpath; - - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Labels each node in the graph according to the BFS distance from the start node(s). If nodes are unreachable, then - * they are assigned a distance of -1. - * All nodes traversed at step k are marked as predecessors of their successors traversed at step k+1. - *

      - * Running time is: O(m) - * @author Scott White - */ -public class BFSDistanceLabeler { - - private Map distanceDecorator = new HashMap(); - private List mCurrentList; - private Set mUnvisitedVertices; - private List mVerticesInOrderVisited; - private Map> mPredecessorMap; - - /** - * Creates a new BFS labeler for the specified graph and root set - * The distances are stored in the corresponding Vertex objects and are of type MutableInteger - */ - public BFSDistanceLabeler() { - mPredecessorMap = new HashMap>(); - } - - /** - * Returns the list of vertices visited in order of traversal - * @return the list of vertices - */ - public List getVerticesInOrderVisited() { - return mVerticesInOrderVisited; - } - - /** - * Returns the set of all vertices that were not visited - * @return the list of unvisited vertices - */ - public Set getUnvisitedVertices() { - return mUnvisitedVertices; - } - - /** - * Given a vertex, returns the shortest distance from any node in the root set to v - * @param v the vertex whose distance is to be retrieved - * @return the shortest distance from any node in the root set to v - */ - public int getDistance(Hypergraph g, V v) { - if (!g.getVertices().contains(v)) { - throw new IllegalArgumentException("Vertex is not contained in the graph."); - } - - return distanceDecorator.get(v).intValue(); - } - - /** - * Returns set of predecessors of the given vertex - * @param v the vertex whose predecessors are to be retrieved - * @return the set of predecessors - */ - public Set getPredecessors(V v) { - return mPredecessorMap.get(v); - } - - protected void initialize(Hypergraph g, Set rootSet) { - mVerticesInOrderVisited = new ArrayList(); - mUnvisitedVertices = new HashSet(); - for(V currentVertex : g.getVertices()) { - mUnvisitedVertices.add(currentVertex); - mPredecessorMap.put(currentVertex,new HashSet()); - } - - mCurrentList = new ArrayList(); - for(V v : rootSet) { - distanceDecorator.put(v, new Integer(0)); - mCurrentList.add(v); - mUnvisitedVertices.remove(v); - mVerticesInOrderVisited.add(v); - } - } - - private void addPredecessor(V predecessor,V sucessor) { - HashSet predecessors = mPredecessorMap.get(sucessor); - predecessors.add(predecessor); - } - - /** - * Computes the distances of all the node from the starting root nodes. If there is more than one root node - * the minimum distance from each root node is used as the designated distance to a given node. Also keeps track - * of the predecessors of each node traversed as well as the order of nodes traversed. - * @param graph the graph to label - * @param rootSet the set of starting vertices to traverse from - */ - public void labelDistances(Hypergraph graph, Set rootSet) { - - initialize(graph,rootSet); - - int distance = 1; - while (true) { - List newList = new ArrayList(); - for(V currentVertex : mCurrentList) { - if(graph.containsVertex(currentVertex)) { - for(V next : graph.getSuccessors(currentVertex)) { - visitNewVertex(currentVertex,next, distance, newList); - } - } - } - if (newList.size() == 0) break; - mCurrentList = newList; - distance++; - } - - for(V v : mUnvisitedVertices) { - distanceDecorator.put(v,new Integer(-1)); - } - } - - /** - * Computes the distances of all the node from the specified root node. Also keeps track - * of the predecessors of each node traversed as well as the order of nodes traversed. - * @param graph the graph to label - * @param root the single starting vertex to traverse from - */ - public void labelDistances(Hypergraph graph, V root) { - labelDistances(graph, Collections.singleton(root)); - } - - private void visitNewVertex(V predecessor, V neighbor, int distance, List newList) { - if (mUnvisitedVertices.contains(neighbor)) { - distanceDecorator.put(neighbor, new Integer(distance)); - newList.add(neighbor); - mVerticesInOrderVisited.add(neighbor); - mUnvisitedVertices.remove(neighbor); - } - int predecessorDistance = distanceDecorator.get(predecessor).intValue(); - int successorDistance = distanceDecorator.get(neighbor).intValue(); - if (predecessorDistance < successorDistance) { - addPredecessor(predecessor,neighbor); - } - } - - /** - * Returns a map from vertices to minimum distances from the original source(s). - * Must be called after {@code labelDistances} in order to contain valid data. - */ - public Map getDistanceDecorator() { - return distanceDecorator; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DijkstraDistance.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DijkstraDistance.java deleted file mode 100644 index 3e99e16096..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DijkstraDistance.java +++ /dev/null @@ -1,582 +0,0 @@ -/* - * Created on Jul 9, 2005 - * - * Copyright (c) 2005, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.functors.ConstantTransformer; - -import edu.uci.ics.jung.algorithms.util.BasicMapEntry; -import edu.uci.ics.jung.algorithms.util.MapBinaryHeap; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - *

      Calculates distances in a specified graph, using - * Dijkstra's single-source-shortest-path algorithm. All edge weights - * in the graph must be nonnegative; if any edge with negative weight is - * found in the course of calculating distances, an - * IllegalArgumentException will be thrown. - * (Note: this exception will only be thrown when such an edge would be - * used to update a given tentative distance; - * the algorithm does not check for negative-weight edges "up front".) - * - *

      Distances and partial results are optionally cached (by this instance) - * for later reference. Thus, if the 10 closest vertices to a specified source - * vertex are known, calculating the 20 closest vertices does not require - * starting Dijkstra's algorithm over from scratch.

      - * - *

      Distances are stored as double-precision values. - * If a vertex is not reachable from the specified source vertex, no - * distance is stored. This is new behavior with version 1.4; - * the previous behavior was to store a value of - * Double.POSITIVE_INFINITY. This change gives the algorithm - * an approximate complexity of O(kD log k), where k is either the number of - * requested targets or the number of reachable vertices (whichever is smaller), - * and D is the average degree of a vertex.

      - * - *

      The elements in the maps returned by getDistanceMap - * are ordered (that is, returned - * by the iterator) by nondecreasing distance from source.

      - * - *

      Users are cautioned that distances calculated should be assumed to - * be invalidated by changes to the graph, and should invoke reset() - * when appropriate so that the distances can be recalculated.

      - * - * @author Joshua O'Madadhain - * @author Tom Nelson converted to jung2 - */ -public class DijkstraDistance implements Distance -{ - protected Hypergraph g; - protected Transformer nev; - protected Map sourceMap; // a map of source vertices to an instance of SourceData - protected boolean cached; - protected double max_distance; - protected int max_targets; - - /** - *

      Creates an instance of DijkstraShortestPath for - * the specified graph and the specified method of extracting weights - * from edges, which caches results locally if and only if - * cached is true. - * - * @param g the graph on which distances will be calculated - * @param nev the class responsible for returning weights for edges - * @param cached specifies whether the results are to be cached - */ - public DijkstraDistance(Hypergraph g, Transformer nev, boolean cached) { - this.g = g; - this.nev = nev; - this.sourceMap = new HashMap(); - this.cached = cached; - this.max_distance = Double.POSITIVE_INFINITY; - this.max_targets = Integer.MAX_VALUE; - } - - /** - *

      Creates an instance of DijkstraShortestPath for - * the specified graph and the specified method of extracting weights - * from edges, which caches results locally. - * - * @param g the graph on which distances will be calculated - * @param nev the class responsible for returning weights for edges - */ - public DijkstraDistance(Hypergraph g, Transformer nev) { - this(g, nev, true); - } - - /** - *

      Creates an instance of DijkstraShortestPath for - * the specified unweighted graph (that is, all weights 1) which - * caches results locally. - * - * @param g the graph on which distances will be calculated - */ - @SuppressWarnings("unchecked") - public DijkstraDistance(Hypergraph g) { - this(g, new ConstantTransformer(1), true); - } - - /** - *

      Creates an instance of DijkstraShortestPath for - * the specified unweighted graph (that is, all weights 1) which - * caches results locally. - * - * @param g the graph on which distances will be calculated - * @param cached specifies whether the results are to be cached - */ - @SuppressWarnings("unchecked") - public DijkstraDistance(Hypergraph g, boolean cached) { - this(g, new ConstantTransformer(1), cached); - } - - /** - * Implements Dijkstra's single-source shortest-path algorithm for - * weighted graphs. Uses a MapBinaryHeap as the priority queue, - * which gives this algorithm a time complexity of O(m lg n) (m = # of edges, n = - * # of vertices). - * This algorithm will terminate when any of the following have occurred (in order - * of priority): - *

        - *
      • the distance to the specified target (if any) has been found - *
      • no more vertices are reachable - *
      • the specified # of distances have been found, or the maximum distance - * desired has been exceeded - *
      • all distances have been found - *
      - * - * @param source the vertex from which distances are to be measured - * @param numDests the number of distances to measure - * @param targets the set of vertices to which distances are to be measured - * @param regular boolean is true if we want regular SP dijkstra. False for MT. - */ - private LinkedHashMap singleSourceShortestPath(V source, Collection targets, int numDests, boolean regular) - { - SourceData sd = getSourceData(source); - - Set to_get = new HashSet(); - if (targets != null) { - to_get.addAll(targets); - Set existing_dists = sd.distances.keySet(); - for(V o : targets) { - if (existing_dists.contains(o)) - to_get.remove(o); - } - } - - // if we've exceeded the max distance or max # of distances we're willing to calculate, or - // if we already have all the distances we need, - // terminate - if (sd.reached_max || - (targets != null && to_get.isEmpty()) || - (sd.distances.size() >= numDests)) - { - return sd.distances; - } - - while (!sd.unknownVertices.isEmpty() && (sd.distances.size() < numDests || !to_get.isEmpty())) - { - Map.Entry p = sd.getNextVertex(); - V v = p.getKey(); - double v_dist = p.getValue().doubleValue(); - to_get.remove(v); - if (v_dist > this.max_distance) - { - // we're done; put this vertex back in so that we're not including - // a distance beyond what we specified - sd.restoreVertex(v, v_dist); - sd.reached_max = true; - break; - } - sd.dist_reached = v_dist; - - if (sd.distances.size() >= this.max_targets) - { - sd.reached_max = true; - break; - } - - for (E e : getEdgesToCheck(v) ) - { - for (V w : g.getIncidentVertices(e)) - { - if (!sd.distances.containsKey(w)) - { - double edge_weight = nev.transform(e).doubleValue(); - if (edge_weight < 0) - throw new IllegalArgumentException("Edges weights must be non-negative"); - double new_dist; - if (regular == true) { - new_dist = v_dist + edge_weight; - } else { - if (v_dist <= edge_weight) { - new_dist = edge_weight; - } else { - new_dist = v_dist; - } - } - if (!sd.estimatedDistances.containsKey(w)) - { - sd.createRecord(w, e, new_dist); - } - else - { - double w_dist = ((Double)sd.estimatedDistances.get(w)).doubleValue(); - if (new_dist < w_dist) // update tentative distance & path for w - sd.update(w, e, new_dist); - } - } - } - } - } - return sd.distances; - } - - /** - * Implements Dijkstra's single-source shortest-path algorithm for - * weighted graphs. Uses a MapBinaryHeap as the priority queue, - * which gives this algorithm a time complexity of O(m lg n) (m = # of edges, n = - * # of vertices). - * This algorithm will terminate when any of the following have occurred (in order - * of priority): - *
        - *
      • the distance to the specified target (if any) has been found - *
      • no more vertices are reachable - *
      • the specified # of distances have been found, or the maximum distance - * desired has been exceeded - *
      • all distances have been found - *
      - * - * @param source the vertex from which distances are to be measured - * @param numDests the number of distances to measure - * @param targets the set of vertices to which distances are to be measured - */ - protected LinkedHashMap singleSourceShortestPath(V source, Collection targets, int numDests) - { - return singleSourceShortestPath(source, targets, numDests, true); - } - - /** - * Implements Dijkstra's single-source shortest-path algorithm for - * weighted graphs. Uses a MapBinaryHeap as the priority queue, - * which gives this algorithm a time complexity of O(m lg n) (m = # of edges, n = - * # of vertices). - * This algorithm will terminate when any of the following have occurred (in order - * of priority): - *
        - *
      • the distance to the specified target (if any) has been found - *
      • no more vertices are reachable - *
      • the specified # of distances have been found, or the maximum distance - * desired has been exceeded - *
      • all distances have been found - *
      - * - * @param source the vertex from which distances are to be measured - * @param numDests the number of distances to measure - * @param targets the set of vertices to which distances are to be measured - */ - protected LinkedHashMap singleSourceMaxThroughputPath(V source, Collection targets, int numDests) - { - return singleSourceShortestPath(source, targets, numDests, false); - } - - protected SourceData getSourceData(V source) - { - SourceData sd = sourceMap.get(source); - if (sd == null) - sd = new SourceData(source); - return sd; - } - - /** - * Returns the set of edges incident to v that should be tested. - * By default, this is the set of outgoing edges for instances of Graph, - * the set of incident edges for instances of Hypergraph, - * and is otherwise undefined. - */ - protected Collection getEdgesToCheck(V v) - { - if (g instanceof Graph) - return ((Graph)g).getOutEdges(v); - else - return g.getIncidentEdges(v); - - } - - - /** - * Returns the length of a shortest path from the source to the target vertex, - * or null if the target is not reachable from the source. - * If either vertex is not in the graph for which this instance - * was created, throws IllegalArgumentException. - * - * @see #getDistanceMap(Object) - * @see #getDistanceMap(Object,int) - */ - public Number getDistance(V source, V target) - { - if (g.containsVertex(target) == false) - throw new IllegalArgumentException("Specified target vertex " + - target + " is not part of graph " + g); - if (g.containsVertex(source) == false) - throw new IllegalArgumentException("Specified source vertex " + - source + " is not part of graph " + g); - - Set targets = new HashSet(); - targets.add(target); - Map distanceMap = getDistanceMap(source, targets); - return distanceMap.get(target); - } - - - /** - * Returns a {@code Map} from each element {@code t} of {@code targets} to the - * shortest-path distance from {@code source} to {@code t}. - */ - public Map getDistanceMap(V source, Collection targets) - { - if (g.containsVertex(source) == false) - throw new IllegalArgumentException("Specified source vertex " + - source + " is not part of graph " + g); - if (targets.size() > max_targets) - throw new IllegalArgumentException("size of target set exceeds maximum " + - "number of targets allowed: " + this.max_targets); - - Map distanceMap = - singleSourceShortestPath(source, targets, - Math.min(g.getVertexCount(), max_targets)); - if (!cached) - reset(source); - - return distanceMap; - } - - /** - *

      Returns a LinkedHashMap which maps each vertex - * in the graph (including the source vertex) - * to its distance from the source vertex. - * The map's iterator will return the elements in order of - * increasing distance from source.

      - * - *

      The size of the map returned will be the number of - * vertices reachable from source.

      - * - * @see #getDistanceMap(Object,int) - * @see #getDistance(Object,Object) - * @param source the vertex from which distances are measured - */ - public Map getDistanceMap(V source) - { - return getDistanceMap(source, Math.min(g.getVertexCount(), max_targets)); - } - - - - /** - *

      Returns a LinkedHashMap which maps each of the closest - * numDist vertices to the source vertex - * in the graph (including the source vertex) - * to its distance from the source vertex. Throws - * an IllegalArgumentException if source - * is not in this instance's graph, or if numDests is - * either less than 1 or greater than the number of vertices in the - * graph.

      - * - *

      The size of the map returned will be the smaller of - * numDests and the number of vertices reachable from - * source. - * - * @see #getDistanceMap(Object) - * @see #getDistance(Object,Object) - * @param source the vertex from which distances are measured - * @param numDests the number of vertices for which to measure distances - */ - public LinkedHashMap getDistanceMap(V source, int numDests) - { - - if(g.getVertices().contains(source) == false) { - throw new IllegalArgumentException("Specified source vertex " + - source + " is not part of graph " + g); - - } - if (numDests < 1 || numDests > g.getVertexCount()) - throw new IllegalArgumentException("numDests must be >= 1 " + - "and <= g.numVertices()"); - - if (numDests > max_targets) - throw new IllegalArgumentException("numDests must be <= the maximum " + - "number of targets allowed: " + this.max_targets); - - LinkedHashMap distanceMap = - singleSourceShortestPath(source, null, numDests); - - if (!cached) - reset(source); - - return distanceMap; - } - - /** - * Allows the user to specify the maximum distance that this instance will calculate. - * Any vertices past this distance will effectively be unreachable from the source, in - * the sense that the algorithm will not calculate the distance to any vertices which - * are farther away than this distance. A negative value for max_dist - * will ensure that no further distances are calculated. - * - *

      This can be useful for limiting the amount of time and space used by this algorithm - * if the graph is very large.

      - * - *

      Note: if this instance has already calculated distances greater than max_dist, - * and the results are cached, those results will still be valid and available; this limit - * applies only to subsequent distance calculations.

      - * @see #setMaxTargets(int) - */ - public void setMaxDistance(double max_dist) - { - this.max_distance = max_dist; - for (V v : sourceMap.keySet()) - { - SourceData sd = sourceMap.get(v); - sd.reached_max = (this.max_distance <= sd.dist_reached) || (sd.distances.size() >= max_targets); - } - } - - /** - * Allows the user to specify the maximum number of target vertices per source vertex - * for which this instance will calculate distances. Once this threshold is reached, - * any further vertices will effectively be unreachable from the source, in - * the sense that the algorithm will not calculate the distance to any more vertices. - * A negative value for max_targets will ensure that no further distances are calculated. - * - *

      This can be useful for limiting the amount of time and space used by this algorithm - * if the graph is very large.

      - * - *

      Note: if this instance has already calculated distances to a greater number of - * targets than max_targets, and the results are cached, those results - * will still be valid and available; this limit applies only to subsequent distance - * calculations.

      - * @see #setMaxDistance(double) - */ - public void setMaxTargets(int max_targets) - { - this.max_targets = max_targets; - for (V v : sourceMap.keySet()) - { - SourceData sd = sourceMap.get(v); - sd.reached_max = (this.max_distance <= sd.dist_reached) || (sd.distances.size() >= max_targets); - } - } - - /** - * Clears all stored distances for this instance. - * Should be called whenever the graph is modified (edge weights - * changed or edges added/removed). If the user knows that - * some currently calculated distances are unaffected by a - * change, reset(V) may be appropriate instead. - * - * @see #reset(Object) - */ - public void reset() - { - sourceMap = new HashMap(); - } - - /** - * Specifies whether or not this instance of DijkstraShortestPath - * should cache its results (final and partial) for future reference. - * - * @param enable true if the results are to be cached, and - * false otherwise - */ - public void enableCaching(boolean enable) - { - this.cached = enable; - } - - /** - * Clears all stored distances for the specified source vertex - * source. Should be called whenever the stored distances - * from this vertex are invalidated by changes to the graph. - * - * @see #reset() - */ - public void reset(V source) - { - sourceMap.put(source, null); - } - - /** - * Compares according to distances, so that the BinaryHeap knows how to - * order the tree. - */ - protected static class VertexComparator implements Comparator - { - private Map distances; - - protected VertexComparator(Map distances) - { - this.distances = distances; - } - - public int compare(V o1, V o2) - { - return ((Double) distances.get(o1)).compareTo((Double) distances.get(o2)); - } - } - - /** - * For a given source vertex, holds the estimated and final distances, - * tentative and final assignments of incoming edges on the shortest path from - * the source vertex, and a priority queue (ordered by estimated distance) - * of the vertices for which distances are unknown. - * - * @author Joshua O'Madadhain - */ - protected class SourceData - { - protected LinkedHashMap distances; - protected Map estimatedDistances; - protected MapBinaryHeap unknownVertices; - protected boolean reached_max = false; - protected double dist_reached = 0; - - protected SourceData(V source) - { - distances = new LinkedHashMap(); - estimatedDistances = new HashMap(); - unknownVertices = new MapBinaryHeap(new VertexComparator(estimatedDistances)); - - sourceMap.put(source, this); - - // initialize priority queue - estimatedDistances.put(source, new Double(0)); // distance from source to itself is 0 - unknownVertices.add(source); - reached_max = false; - dist_reached = 0; - } - - protected Map.Entry getNextVertex() - { - V v = unknownVertices.remove(); - Double dist = (Double)estimatedDistances.remove(v); - distances.put(v, dist); - return new BasicMapEntry(v, dist); - } - - protected void update(V dest, E tentative_edge, double new_dist) - { - estimatedDistances.put(dest, new_dist); - unknownVertices.update(dest); - } - - protected void createRecord(V w, E e, double new_dist) - { - estimatedDistances.put(w, new_dist); - unknownVertices.add(w); - } - - protected void restoreVertex(V v, double dist) - { - estimatedDistances.put(v, dist); - unknownVertices.add(v); - distances.remove(v); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DijkstraShortestPath.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DijkstraShortestPath.java deleted file mode 100644 index 05c008d11f..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DijkstraShortestPath.java +++ /dev/null @@ -1,314 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.graph.Graph; - -/** - *

      Calculates distances and shortest paths using Dijkstra's - * single-source-shortest-path algorithm. This is a lightweight - * extension of DijkstraDistance that also stores - * path information, so that the shortest paths can be reconstructed.

      - * - *

      The elements in the maps returned by - * getIncomingEdgeMap are ordered (that is, returned - * by the iterator) by nondecreasing distance from source.

      - * - * @author Joshua O'Madadhain - * @author Tom Nelson converted to jung2 - * @see DijkstraDistance - */ -public class DijkstraShortestPath extends DijkstraDistance implements ShortestPath -{ - /** - *

      Creates an instance of DijkstraShortestPath for - * the specified graph and the specified method of extracting weights - * from edges, which caches results locally if and only if - * cached is true. - * - * @param g the graph on which distances will be calculated - * @param nev the class responsible for returning weights for edges - * @param cached specifies whether the results are to be cached - */ - public DijkstraShortestPath(Graph g, Transformer nev, boolean cached) - { - super(g, nev, cached); - } - - /** - *

      Creates an instance of DijkstraShortestPath for - * the specified graph and the specified method of extracting weights - * from edges, which caches results locally. - * - * @param g the graph on which distances will be calculated - * @param nev the class responsible for returning weights for edges - */ - public DijkstraShortestPath(Graph g, Transformer nev) - { - super(g, nev); - } - - /** - *

      Creates an instance of DijkstraShortestPath for - * the specified unweighted graph (that is, all weights 1) which - * caches results locally. - * - * @param g the graph on which distances will be calculated - */ - public DijkstraShortestPath(Graph g) - { - super(g); - } - - /** - *

      Creates an instance of DijkstraShortestPath for - * the specified unweighted graph (that is, all weights 1) which - * caches results locally. - * - * @param g the graph on which distances will be calculated - * @param cached specifies whether the results are to be cached - */ - public DijkstraShortestPath(Graph g, boolean cached) - { - super(g, cached); - } - - @Override - protected SourceData getSourceData(V source) - { - SourceData sd = sourceMap.get(source); - if (sd == null) - sd = new SourcePathData(source); - return sd; - } - - /** - *

      Returns the last edge on a shortest path from source - * to target, or null if target is not - * reachable from source.

      - * - *

      If either vertex is not in the graph for which this instance - * was created, throws IllegalArgumentException.

      - */ - public E getIncomingEdge(V source, V target) - { - if (!g.containsVertex(source)) - throw new IllegalArgumentException("Specified source vertex " + - source + " is not part of graph " + g); - - if (!g.containsVertex(target)) - throw new IllegalArgumentException("Specified target vertex " + - target + " is not part of graph " + g); - - Set targets = new HashSet(); - targets.add(target); - singleSourceShortestPath(source, targets, g.getVertexCount()); - Map incomingEdgeMap = - ((SourcePathData)sourceMap.get(source)).incomingEdges; - E incomingEdge = incomingEdgeMap.get(target); - - if (!cached) - reset(source); - - return incomingEdge; - } - - /** - *

      Returns a LinkedHashMap which maps each vertex - * in the graph (including the source vertex) - * to the last edge on the shortest path from the - * source vertex. - * The map's iterator will return the elements in order of - * increasing distance from source.

      - * - * @see DijkstraDistance#getDistanceMap(Object,int) - * @see DijkstraDistance#getDistance(Object,Object) - * @param source the vertex from which distances are measured - */ - public Map getIncomingEdgeMap(V source) - { - return getIncomingEdgeMap(source, g.getVertexCount()); - } - - /** - * Returns a List of the edges on the shortest path from - * source to target, in order of their - * occurrence on this path. - * If either vertex is not in the graph for which this instance - * was created, throws IllegalArgumentException. - */ - private List getPath(V source, V target, boolean spath) - { - if(!g.containsVertex(source)) - throw new IllegalArgumentException("Specified source vertex " + - source + " is not part of graph " + g); - - if(!g.containsVertex(target)) - throw new IllegalArgumentException("Specified target vertex " + - target + " is not part of graph " + g); - - LinkedList path = new LinkedList(); - - // collect path data; must use internal method rather than - // calling getIncomingEdge() because getIncomingEdge() may - // wipe out results if results are not cached - Set targets = new HashSet(); - targets.add(target); - if (spath == true) { - singleSourceShortestPath(source, targets, g.getVertexCount()); - } else { - singleSourceMaxThroughputPath(source, targets, g.getVertexCount()); - } - Map incomingEdges = - ((SourcePathData)sourceMap.get(source)).incomingEdges; - - if (incomingEdges.isEmpty() || incomingEdges.get(target) == null) - return path; - V current = target; - while (!current.equals(source)) - { - E incoming = incomingEdges.get(current); - path.addFirst(incoming); - current = ((Graph)g).getOpposite(current, incoming); - } - return path; - } - - /** - * Returns a List of the edges on the shortest path from - * source to target, in order of their - * occurrence on this path. - * If either vertex is not in the graph for which this instance - * was created, throws IllegalArgumentException. - */ - public List getPath(V source, V target) - { - - return getPath(source,target, true); - } - - /** - * Returns a List of the edges on the Max Througput Shortest - * path from source to target, in order of their - * their occurrence on this path. - * Important - Transformer fn should return the appropriate edge weight - * for this API to return the Path Correctly. - * If either vertex is not in the graph for which this instance - * was created, throws IllegalArgumentException. - */ - public List getMaxThroughputPath(V source, V target) - { - - return getPath(source,target, false); - } - - - /** - *

      Returns a LinkedHashMap which maps each of the closest - * numDist vertices to the source vertex - * in the graph (including the source vertex) - * to the incoming edge along the path from that vertex. Throws - * an IllegalArgumentException if source - * is not in this instance's graph, or if numDests is - * either less than 1 or greater than the number of vertices in the - * graph. - * - * @see #getIncomingEdgeMap(Object) - * @see #getPath(Object,Object) - * @param source the vertex from which distances are measured - * @param numDests the number of vertices for which to measure distances - */ - public LinkedHashMap getIncomingEdgeMap(V source, int numDests) - { - if (g.getVertices().contains(source) == false) - throw new IllegalArgumentException("Specified source vertex " + - source + " is not part of graph " + g); - - if (numDests < 1 || numDests > g.getVertexCount()) - throw new IllegalArgumentException("numDests must be >= 1 " + - "and <= g.numVertices()"); - - singleSourceShortestPath(source, null, numDests); - - LinkedHashMap incomingEdgeMap = - ((SourcePathData)sourceMap.get(source)).incomingEdges; - - if (!cached) - reset(source); - - return incomingEdgeMap; - } - - - /** - * For a given source vertex, holds the estimated and final distances, - * tentative and final assignments of incoming edges on the shortest path from - * the source vertex, and a priority queue (ordered by estimaed distance) - * of the vertices for which distances are unknown. - * - * @author Joshua O'Madadhain - */ - protected class SourcePathData extends SourceData - { - protected Map tentativeIncomingEdges; - protected LinkedHashMap incomingEdges; - - protected SourcePathData(V source) - { - super(source); - incomingEdges = new LinkedHashMap(); - tentativeIncomingEdges = new HashMap(); - } - - @Override - public void update(V dest, E tentative_edge, double new_dist) - { - super.update(dest, tentative_edge, new_dist); - tentativeIncomingEdges.put(dest, tentative_edge); - } - - @Override - public Map.Entry getNextVertex() - { - Map.Entry p = super.getNextVertex(); - V v = p.getKey(); - E incoming = tentativeIncomingEdges.remove(v); - incomingEdges.put(v, incoming); - return p; - } - - @Override - public void restoreVertex(V v, double dist) - { - super.restoreVertex(v, dist); - E incoming = incomingEdges.get(v); - tentativeIncomingEdges.put(v, incoming); - } - - @Override - public void createRecord(V w, E e, double new_dist) - { - super.createRecord(w, e, new_dist); - tentativeIncomingEdges.put(w, e); - } - - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/Distance.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/Distance.java deleted file mode 100644 index 85820d14b8..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/Distance.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Created on Apr 2, 2004 - * - * Copyright (c) 2004, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.Map; - - -/** - * An interface for classes which calculate the distance between - * one vertex and another. - * - * @author Joshua O'Madadhain - */ -public interface Distance -{ - /** - * Returns the distance from the source vertex - * to the target vertex. If target - * is not reachable from source, returns null. - */ - Number getDistance(V source, V target); - - /** - *

      Returns a Map which maps each vertex - * in the graph (including the source vertex) - * to its distance (represented as a Number) - * from source. If any vertex - * is not reachable from source, no - * distance is stored for that vertex. - */ - Map getDistanceMap(V source); -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DistanceStatistics.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DistanceStatistics.java deleted file mode 100644 index f0f20a3241..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/DistanceStatistics.java +++ /dev/null @@ -1,136 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.shortestpath; -import java.util.Collection; - -import org.apache.commons.collections15.Transformer; - -import edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality; -import edu.uci.ics.jung.algorithms.scoring.util.VertexScoreTransformer; -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Statistics relating to vertex-vertex distances in a graph. - * - *

      Formerly known as GraphStatistics in JUNG 1.x.

      - * - * @author Scott White - * @author Joshua O'Madadhain - */ -public class DistanceStatistics -{ - /** - * For each vertex v in graph, - * calculates the average shortest path length from v - * to all other vertices in graph using the metric - * specified by d, and returns the results in a - * Map from vertices to Double values. - * If there exists an ordered pair <u,v> - * for which d.getDistance(u,v) returns null, - * then the average distance value for u will be stored - * as Double.POSITIVE_INFINITY). - * - *

      Does not include self-distances (path lengths from v - * to v). - * - *

      To calculate the average distances, ignoring edge weights if any: - *

      -     * Map distances = DistanceStatistics.averageDistances(g, new UnweightedShortestPath(g));
      -     * 
      - * To calculate the average distances respecting edge weights: - *
      -     * DijkstraShortestPath dsp = new DijkstraShortestPath(g, nev);
      -     * Map distances = DistanceStatistics.averageDistances(g, dsp);
      -     * 
      - * where nev is an instance of Transformer that - * is used to fetch the weight for each edge. - * - * @see edu.uci.ics.jung.algorithms.shortestpath.UnweightedShortestPath - * @see edu.uci.ics.jung.algorithms.shortestpath.DijkstraDistance - */ - public static Transformer averageDistances(Hypergraph graph, Distance d) - { - final ClosenessCentrality cc = new ClosenessCentrality(graph, d); - return new VertexScoreTransformer(cc); - } - - /** - * For each vertex v in g, - * calculates the average shortest path length from v - * to all other vertices in g, ignoring edge weights. - * @see #diameter(Hypergraph) - * @see edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality - */ - public static Transformer averageDistances(Hypergraph g) - { - final ClosenessCentrality cc = new ClosenessCentrality(g, - new UnweightedShortestPath(g)); - return new VertexScoreTransformer(cc); - } - - /** - * Returns the diameter of g using the metric - * specified by d. The diameter is defined to be - * the maximum, over all pairs of vertices u,v, - * of the length of the shortest path from u to - * v. If the graph is disconnected (that is, not - * all pairs of vertices are reachable from one another), the - * value returned will depend on use_max: - * if use_max == true, the value returned - * will be the the maximum shortest path length over all pairs of connected - * vertices; otherwise it will be Double.POSITIVE_INFINITY. - */ - public static double diameter(Hypergraph g, Distance d, boolean use_max) - { - double diameter = 0; - Collection vertices = g.getVertices(); - for(V v : vertices) { - for(V w : vertices) { - - if (v.equals(w) == false) // don't include self-distances - { - Number dist = d.getDistance(v, w); - if (dist == null) - { - if (!use_max) - return Double.POSITIVE_INFINITY; - } - else - diameter = Math.max(diameter, dist.doubleValue()); - } - } - } - return diameter; - } - - /** - * Returns the diameter of g using the metric - * specified by d. The diameter is defined to be - * the maximum, over all pairs of vertices u,v, - * of the length of the shortest path from u to - * v, or Double.POSITIVE_INFINITY - * if any of these distances do not exist. - * @see #diameter(Hypergraph, Distance, boolean) - */ - public static double diameter(Hypergraph g, Distance d) - { - return diameter(g, d, false); - } - - /** - * Returns the diameter of g, ignoring edge weights. - * @see #diameter(Hypergraph, Distance, boolean) - */ - public static double diameter(Hypergraph g) - { - return diameter(g, new UnweightedShortestPath(g)); - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/MinimumSpanningForest.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/MinimumSpanningForest.java deleted file mode 100644 index 18cb0fe026..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/MinimumSpanningForest.java +++ /dev/null @@ -1,165 +0,0 @@ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.functors.ConstantTransformer; -import org.apache.commons.collections15.map.LazyMap; - -import edu.uci.ics.jung.graph.Forest; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.EdgeType; -import edu.uci.ics.jung.graph.util.Pair; - -/** - * For the input Graph, creates a MinimumSpanningTree - * using a variation of Prim's algorithm. - * - * @author Tom Nelson - tomnelson@dev.java.net - * - * @param - * @param - */ -public class MinimumSpanningForest { - - protected Graph graph; - protected Forest forest; - protected Map weights; - - /** - * Creates a Forest from the supplied Graph and supplied Factory, which - * is used to create a new, empty Forest. If non-null, the supplied root - * will be used as the root of the tree/forest. If the supplied root is - * null, or not present in the Graph, then an arbitrary Graph vertex - * will be selected as the root. - * If the Minimum Spanning Tree does not include all vertices of the - * Graph, then a leftover vertex is selected as a root, and another - * tree is created. - * @param graph the input graph - * @param factory the factory to use to create the new forest - * @param root the vertex of the graph to be used as the root of the forest - * @param weights edge weights - */ - public MinimumSpanningForest(Graph graph, Factory> factory, - V root, Map weights) { - this(graph, factory.create(), root, weights); - } - - /** - * Creates a minimum spanning forest from the supplied graph, populating the - * supplied Forest, which must be empty. - * If the supplied root is null, or not present in the Graph, - * then an arbitrary Graph vertex will be selected as the root. - * If the Minimum Spanning Tree does not include all vertices of the - * Graph, then a leftover vertex is selected as a root, and another - * tree is created - * @param graph the Graph to find MST in - * @param forest the Forest to populate. Must be empty - * @param root first Tree root, may be null - * @param weights edge weights, may be null - */ - public MinimumSpanningForest(Graph graph, Forest forest, - V root, Map weights) { - - if(forest.getVertexCount() != 0) { - throw new IllegalArgumentException("Supplied Forest must be empty"); - } - this.graph = graph; - this.forest = forest; - if(weights != null) { - this.weights = weights; - } - Set unfinishedEdges = new HashSet(graph.getEdges()); - if(graph.getVertices().contains(root)) { - this.forest.addVertex(root); - } - updateForest(forest.getVertices(), unfinishedEdges); - } - - /** - * Creates a minimum spanning forest from the supplied graph, populating the - * supplied Forest, which must be empty. - * If the supplied root is null, or not present in the Graph, - * then an arbitrary Graph vertex will be selected as the root. - * If the Minimum Spanning Tree does not include all vertices of the - * Graph, then a leftover vertex is selected as a root, and another - * tree is created - * @param graph the Graph to find MST in - * @param forest the Forest to populate. Must be empty - * @param root first Tree root, may be null - */ - @SuppressWarnings("unchecked") - public MinimumSpanningForest(Graph graph, Forest forest, - V root) { - - if(forest.getVertexCount() != 0) { - throw new IllegalArgumentException("Supplied Forest must be empty"); - } - this.graph = graph; - this.forest = forest; - this.weights = LazyMap.decorate(new HashMap(), - new ConstantTransformer(1.0)); - Set unfinishedEdges = new HashSet(graph.getEdges()); - if(graph.getVertices().contains(root)) { - this.forest.addVertex(root); - } - updateForest(forest.getVertices(), unfinishedEdges); - } - - /** - * Returns the generated forest. - */ - public Forest getForest() { - return forest; - } - - protected void updateForest(Collection tv, Collection unfinishedEdges) { - double minCost = Double.MAX_VALUE; - E nextEdge = null; - V nextVertex = null; - V currentVertex = null; - for(E e : unfinishedEdges) { - - if(forest.getEdges().contains(e)) continue; - // find the lowest cost edge, get its opposite endpoint, - // and then update forest from its Successors - Pair endpoints = graph.getEndpoints(e); - V first = endpoints.getFirst(); - V second = endpoints.getSecond(); - if(tv.contains(first) == true && tv.contains(second) == false) { - if(weights.get(e) < minCost) { - minCost = weights.get(e); - nextEdge = e; - currentVertex = first; - nextVertex = second; - } - } - if(graph.getEdgeType(e) == EdgeType.UNDIRECTED && - tv.contains(second) == true && tv.contains(first) == false) { - if(weights.get(e) < minCost) { - minCost = weights.get(e); - nextEdge = e; - currentVertex = second; - nextVertex = first; - } - } - } - - if(nextVertex != null && nextEdge != null) { - unfinishedEdges.remove(nextEdge); - forest.addEdge(nextEdge, currentVertex, nextVertex); - updateForest(forest.getVertices(), unfinishedEdges); - } - Collection leftovers = new HashSet(graph.getVertices()); - leftovers.removeAll(forest.getVertices()); - if(leftovers.size() > 0) { - V anotherRoot = leftovers.iterator().next(); - forest.addVertex(anotherRoot); - updateForest(forest.getVertices(), unfinishedEdges); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/MinimumSpanningForest2.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/MinimumSpanningForest2.java deleted file mode 100644 index 13e800c7d5..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/MinimumSpanningForest2.java +++ /dev/null @@ -1,104 +0,0 @@ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.Collection; -import java.util.Set; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.functors.ConstantTransformer; - -import edu.uci.ics.jung.algorithms.cluster.WeakComponentClusterer; -import edu.uci.ics.jung.algorithms.filters.FilterUtils; -import edu.uci.ics.jung.graph.Forest; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.Tree; -import edu.uci.ics.jung.graph.util.TreeUtils; - -/** - * For the input Graph, creates a MinimumSpanningTree - * using a variation of Prim's algorithm. - * - * @author Tom Nelson - tomnelson@dev.java.net - * - * @param - * @param - */ -@SuppressWarnings("unchecked") -public class MinimumSpanningForest2 { - - protected Graph graph; - protected Forest forest; - protected Transformer weights = - (Transformer)new ConstantTransformer(1.0); - - /** - * create a Forest from the supplied Graph and supplied Factory, which - * is used to create a new, empty Forest. If non-null, the supplied root - * will be used as the root of the tree/forest. If the supplied root is - * null, or not present in the Graph, then an arbitary Graph vertex - * will be selected as the root. - * If the Minimum Spanning Tree does not include all vertices of the - * Graph, then a leftover vertex is selected as a root, and another - * tree is created - * @param graph - * @param factory - * @param weights - */ - public MinimumSpanningForest2(Graph graph, - Factory> factory, - Factory> treeFactory, - Transformer weights) { - this(graph, factory.create(), - treeFactory, - weights); - } - - /** - * create a forest from the supplied graph, populating the - * supplied Forest, which must be empty. - * If the supplied root is null, or not present in the Graph, - * then an arbitary Graph vertex will be selected as the root. - * If the Minimum Spanning Tree does not include all vertices of the - * Graph, then a leftover vertex is selected as a root, and another - * tree is created - * @param graph the Graph to find MST in - * @param forest the Forest to populate. Must be empty - * @param weights edge weights, may be null - */ - public MinimumSpanningForest2(Graph graph, - Forest forest, - Factory> treeFactory, - Transformer weights) { - - if(forest.getVertexCount() != 0) { - throw new IllegalArgumentException("Supplied Forest must be empty"); - } - this.graph = graph; - this.forest = forest; - if(weights != null) { - this.weights = weights; - } - - WeakComponentClusterer wcc = - new WeakComponentClusterer(); - Set> component_vertices = wcc.transform(graph); - Collection> components = - FilterUtils.createAllInducedSubgraphs(component_vertices, graph); - - for(Graph component : components) { - PrimMinimumSpanningTree mst = - new PrimMinimumSpanningTree(treeFactory, this.weights); - Graph subTree = mst.transform(component); - if(subTree instanceof Tree) { - TreeUtils.addSubTree(forest, (Tree)subTree, null, null); - } - } - } - - /** - * Returns the generated forest. - */ - public Forest getForest() { - return forest; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/PrimMinimumSpanningTree.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/PrimMinimumSpanningTree.java deleted file mode 100644 index b029dda747..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/PrimMinimumSpanningTree.java +++ /dev/null @@ -1,116 +0,0 @@ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.functors.ConstantTransformer; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - -/** - * For the input Graph, creates a MinimumSpanningTree - * using a variation of Prim's algorithm. - * - * @author Tom Nelson - tomnelson@dev.java.net - * - * @param the vertex type - * @param the edge type - */ -@SuppressWarnings("unchecked") -public class PrimMinimumSpanningTree implements Transformer,Graph> { - - protected Factory> treeFactory; - protected Transformer weights; - - /** - * Creates an instance which generates a minimum spanning tree assuming constant edge weights. - */ - public PrimMinimumSpanningTree(Factory> factory) { - this(factory, new ConstantTransformer(1.0)); - } - - /** - * Creates an instance which generates a minimum spanning tree using the input edge weights. - */ - public PrimMinimumSpanningTree(Factory> factory, - Transformer weights) { - this.treeFactory = factory; - if(weights != null) { - this.weights = weights; - } - } - - /** - * @param graph the Graph to find MST in - */ - public Graph transform(Graph graph) { - Set unfinishedEdges = new HashSet(graph.getEdges()); - Graph tree = treeFactory.create(); - V root = findRoot(graph); - if(graph.getVertices().contains(root)) { - tree.addVertex(root); - } else if(graph.getVertexCount() > 0) { - // pick an arbitrary vertex to make root - tree.addVertex(graph.getVertices().iterator().next()); - } - updateTree(tree, graph, unfinishedEdges); - - return tree; - } - - protected V findRoot(Graph graph) { - for(V v : graph.getVertices()) { - if(graph.getInEdges(v).size() == 0) { - return v; - } - } - // if there is no obvious root, pick any vertex - if(graph.getVertexCount() > 0) { - return graph.getVertices().iterator().next(); - } - // this graph has no vertices - return null; - } - - protected void updateTree(Graph tree, Graph graph, Collection unfinishedEdges) { - Collection tv = tree.getVertices(); - double minCost = Double.MAX_VALUE; - E nextEdge = null; - V nextVertex = null; - V currentVertex = null; - for(E e : unfinishedEdges) { - - if(tree.getEdges().contains(e)) continue; - // find the lowest cost edge, get its opposite endpoint, - // and then update forest from its Successors - Pair endpoints = graph.getEndpoints(e); - V first = endpoints.getFirst(); - V second = endpoints.getSecond(); - if((tv.contains(first) == true && tv.contains(second) == false)) { - if(weights.transform(e) < minCost) { - minCost = weights.transform(e); - nextEdge = e; - currentVertex = first; - nextVertex = second; - } - } else if((tv.contains(second) == true && tv.contains(first) == false)) { - if(weights.transform(e) < minCost) { - minCost = weights.transform(e); - nextEdge = e; - currentVertex = second; - nextVertex = first; - } - } - } - - if(nextVertex != null && nextEdge != null) { - unfinishedEdges.remove(nextEdge); - tree.addEdge(nextEdge, currentVertex, nextVertex); - updateTree(tree, graph, unfinishedEdges); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/ShortestPath.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/ShortestPath.java deleted file mode 100644 index a922cdd329..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/ShortestPath.java +++ /dev/null @@ -1,29 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -* -* Created on Feb 12, 2004 -*/ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.Map; - - -/** - * An interface for algorithms that calculate shortest paths. - */ -public interface ShortestPath -{ - /** - *

      Returns a Map which maps each vertex - * in the graph (including the source vertex) - * to the last edge on the shortest path from the - * source vertex. - */ - Map getIncomingEdgeMap(V source); -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/ShortestPathUtils.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/ShortestPathUtils.java deleted file mode 100644 index d3e59ebec9..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/ShortestPathUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Created on Jul 10, 2005 - * - * Copyright (c) 2005, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Pair; - -/** - * Utilities relating to the shortest paths in a graph. - */ -public class ShortestPathUtils -{ - /** - * Returns a List of the edges on the shortest path from - * source to target, in order of their - * occurrence on this path. - */ - public static List getPath(Graph graph, ShortestPath sp, V source, V target) - { - LinkedList path = new LinkedList(); - - Map incomingEdges = sp.getIncomingEdgeMap(source); - - if (incomingEdges.isEmpty() || incomingEdges.get(target) == null) - return path; - V current = target; - while (!current.equals(source)) - { - E incoming = incomingEdges.get(current); - path.addFirst(incoming); - Pair endpoints = graph.getEndpoints(incoming); - if(endpoints.getFirst().equals(current)) { - current = endpoints.getSecond(); - } else { - current = endpoints.getFirst(); - } - //incoming.getOpposite(current); - } - return path; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/UnweightedShortestPath.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/UnweightedShortestPath.java deleted file mode 100644 index 1d3390c058..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/UnweightedShortestPath.java +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.shortestpath; - -import java.util.HashMap; -import java.util.Map; - -import edu.uci.ics.jung.graph.Hypergraph; - -/** - * Computes the shortest path distances for graphs whose edges are not weighted (using BFS). - * - * @author Scott White - */ -public class UnweightedShortestPath - implements ShortestPath, Distance -{ - private Map> mDistanceMap; - private Map> mIncomingEdgeMap; - private Hypergraph mGraph; - private Map distances = new HashMap(); - - /** - * Constructs and initializes algorithm - * @param g the graph - */ - public UnweightedShortestPath(Hypergraph g) - { - mDistanceMap = new HashMap>(); - mIncomingEdgeMap = new HashMap>(); - mGraph = g; - } - - /** - * @see edu.uci.ics.jung.algorithms.shortestpath.Distance#getDistance(Object, Object) - */ - public Number getDistance(V source, V target) - { - Map sourceSPMap = getDistanceMap(source); - return sourceSPMap.get(target); - } - - /** - * @see edu.uci.ics.jung.algorithms.shortestpath.Distance#getDistanceMap(Object) - */ - public Map getDistanceMap(V source) - { - Map sourceSPMap = mDistanceMap.get(source); - if (sourceSPMap == null) - { - computeShortestPathsFromSource(source); - sourceSPMap = mDistanceMap.get(source); - } - return sourceSPMap; - } - - /** - * @see edu.uci.ics.jung.algorithms.shortestpath.ShortestPath#getIncomingEdgeMap(Object) - */ - public Map getIncomingEdgeMap(V source) - { - Map sourceIEMap = mIncomingEdgeMap.get(source); - if (sourceIEMap == null) - { - computeShortestPathsFromSource(source); - sourceIEMap = mIncomingEdgeMap.get(source); - } - return sourceIEMap; - } - - - /** - * Computes the shortest path distances from a given node to all other nodes. - * @param source the source node - */ - private void computeShortestPathsFromSource(V source) - { - BFSDistanceLabeler labeler = new BFSDistanceLabeler(); - labeler.labelDistances(mGraph, source); - distances = labeler.getDistanceDecorator(); - Map currentSourceSPMap = new HashMap(); - Map currentSourceEdgeMap = new HashMap(); - - for(V vertex : mGraph.getVertices()) { - - Number distanceVal = distances.get(vertex); - // BFSDistanceLabeler uses -1 to indicate unreachable vertices; - // don't bother to store unreachable vertices - if (distanceVal != null && distanceVal.intValue() >= 0) - { - currentSourceSPMap.put(vertex, distanceVal); - int minDistance = distanceVal.intValue(); - for(E incomingEdge : mGraph.getInEdges(vertex)) - { - for (V neighbor : mGraph.getIncidentVertices(incomingEdge)) - { - if (neighbor.equals(vertex)) - continue; -// V neighbor = mGraph.getOpposite(vertex, incomingEdge); - - Number predDistanceVal = distances.get(neighbor); - - int pred_distance = predDistanceVal.intValue(); - if (pred_distance < minDistance && pred_distance >= 0) - { - minDistance = predDistanceVal.intValue(); - currentSourceEdgeMap.put(vertex, incomingEdge); - } - } - } - } - } - mDistanceMap.put(source, currentSourceSPMap); - mIncomingEdgeMap.put(source, currentSourceEdgeMap); - } - - /** - * Clears all stored distances for this instance. - * Should be called whenever the graph is modified (edge weights - * changed or edges added/removed). If the user knows that - * some currently calculated distances are unaffected by a - * change, reset(V) may be appropriate instead. - * - * @see #reset(Object) - */ - public void reset() - { - mDistanceMap.clear(); - mIncomingEdgeMap.clear(); - } - - /** - * Clears all stored distances for the specified source vertex - * source. Should be called whenever the stored distances - * from this vertex are invalidated by changes to the graph. - * - * @see #reset() - */ - public void reset(V v) - { - mDistanceMap.remove(v); - mIncomingEdgeMap.remove(v); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/package.html deleted file mode 100644 index 01f27b5f36..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/shortestpath/package.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - -Provides interfaces and classes for calculating (geodesic) distances and shortest paths. Currently includes: -

        -
      • DijkstraDistance: finds the distances from a specified source vertex to other vertices in a -weighted graph with no negative cycles -
      • DijkstraShortestPath: extends DijkstraDistance, also finds shortest paths -
      • Distance: an interface for defining vertex-vertex distances -
      • PrimMinimumSpanningTree: identifies the spanning tree for a graph of least total edge weight -
      • ShortestPath: an interface for shortest-path algorithms -
      • ShortestPathUtils: utility functions for manipulating shortest paths -
      • UnweightedShortestPath: finds the distances from a specified source vertex to other vertices in an -unweighted graph -
      - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/DirectionTransformer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/DirectionTransformer.java deleted file mode 100644 index 8fa33b882d..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/DirectionTransformer.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -/* - * Created on Apr 21, 2004 - */ -package edu.uci.ics.jung.algorithms.transformation; - -import org.apache.commons.collections15.Factory; - -import edu.uci.ics.jung.graph.DirectedGraph; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.UndirectedGraph; -import edu.uci.ics.jung.graph.util.EdgeType; -import edu.uci.ics.jung.graph.util.Pair; - -/** - *

      Functions for transforming graphs into directed or undirected graphs.

      - * - * - * @author Danyel Fisher - * @author Joshua O'Madadhain - */ -public class DirectionTransformer -{ - - /** - * Transforms graph (which may be of any directionality) - * into an undirected graph. (This may be useful for - * visualization tasks). - * Specifically: - *
        - *
      • Vertices are copied from graph. - *
      • Directed edges are 'converted' into a single new undirected edge in the new graph. - *
      • Each undirected edge (if any) in graph is 'recreated' with a new undirected edge in the new - * graph if create_new is true, or copied from graph otherwise. - *
      - * - * @param graph the graph to be transformed - * @param create_new specifies whether existing undirected edges are to be copied or recreated - * @param graph_factory used to create the new graph object - * @param edge_factory used to create new edges - * @return the transformed Graph - */ - public static UndirectedGraph toUndirected(Graph graph, - Factory> graph_factory, - Factory edge_factory, boolean create_new) - { - UndirectedGraph out = graph_factory.create(); - - for (V v : graph.getVertices()) - out.addVertex(v); - - for (E e : graph.getEdges()) - { - Pair endpoints = graph.getEndpoints(e); - V v1 = endpoints.getFirst(); - V v2 = endpoints.getSecond(); - E to_add; - if (graph.getEdgeType(e) == EdgeType.DIRECTED || create_new) - to_add = edge_factory.create(); - else - to_add = e; - out.addEdge(to_add, v1, v2, EdgeType.UNDIRECTED); - } - return out; - } - - /** - * Transforms graph (which may be of any directionality) - * into a directed graph. - * Specifically: - *
        - *
      • Vertices are copied from graph. - *
      • Undirected edges are 'converted' into two new antiparallel directed edges in the new graph. - *
      • Each directed edge (if any) in graph is 'recreated' with a new edge in the new - * graph if create_new is true, or copied from graph otherwise. - *
      - * - * @param graph the graph to be transformed - * @param create_new specifies whether existing directed edges are to be copied or recreated - * @param graph_factory used to create the new graph object - * @param edge_factory used to create new edges - * @return the transformed Graph - */ - public static Graph toDirected(Graph graph, Factory> graph_factory, - Factory edge_factory, boolean create_new) - { - DirectedGraph out = graph_factory.create(); - - for (V v : graph.getVertices()) - out.addVertex(v); - - for (E e : graph.getEdges()) - { - Pair endpoints = graph.getEndpoints(e); - if (graph.getEdgeType(e) == EdgeType.UNDIRECTED) - { - V v1 = endpoints.getFirst(); - V v2 = endpoints.getSecond(); - out.addEdge(edge_factory.create(), v1, v2, EdgeType.DIRECTED); - out.addEdge(edge_factory.create(), v2, v1, EdgeType.DIRECTED); - } - else // if the edge is directed, just add it - { - V source = graph.getSource(e); - V dest = graph.getDest(e); - E to_add = create_new ? edge_factory.create() : e; - out.addEdge(to_add, source, dest, EdgeType.DIRECTED); - } - - } - return out; - } -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/FoldingTransformer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/FoldingTransformer.java deleted file mode 100644 index 2193319484..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/FoldingTransformer.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -/* - * Created on Apr 21, 2004 - */ -package edu.uci.ics.jung.algorithms.transformation; - -import java.util.ArrayList; -import java.util.Collection; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.Predicate; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.Hypergraph; -import edu.uci.ics.jung.graph.KPartiteGraph; - -/** - * Methods for creating a "folded" graph based on a k-partite graph or a - * hypergraph. - * - *

      A "folded" graph is derived from a k-partite graph by identifying - * a partition of vertices which will become the vertices of the new graph, copying - * these vertices into the new graph, and then connecting those vertices whose - * original analogues were connected indirectly through elements - * of other partitions.

      - * - *

      A "folded" graph is derived from a hypergraph by creating vertices based on - * either the vertices or the hyperedges of the original graph, and connecting - * vertices in the new graph if their corresponding vertices/hyperedges share a - * connection with a common hyperedge/vertex.

      - * - * @author Danyel Fisher - * @author Joshua O'Madadhain - */ -public class FoldingTransformer -{ - - /** - * Converts g into a unipartite graph whose vertex set is the - * vertices of g's partition p. For vertices - * a and b in this partition, the resultant - * graph will include the edge (a,b) if the original graph - * contains edges (a,c) and (c,b) for at least - * one vertex c. - * - *

      The vertices of the new graph are the same as the vertices of the - * appropriate partition in the old graph; the edges in the new graph are - * created by the input edge Factory.

      - * - *

      If there is more than 1 such vertex c for a given pair - * (a,b), the type of the output graph will determine whether - * it will contain parallel edges or not.

      - * - *

      This function will not create self-loops.

      - * - * @param vertex type - * @param input edge type - * @param g input k-partite graph - * @param p predicate specifying vertex partition - * @param graph_factory factory used to create the output graph - * @param edge_factory factory used to create the edges in the new graph - * @return a copy of the input graph folded with respect to the input partition - */ - public static Graph foldKPartiteGraph(KPartiteGraph g, Predicate p, - Factory> graph_factory, Factory edge_factory) - { - Graph newGraph = graph_factory.create(); - - // get vertices for the specified partition - Collection vertices = g.getVertices(p); - for (V v : vertices) - { - newGraph.addVertex(v); - for (V s : g.getSuccessors(v)) - { - for (V t : g.getSuccessors(s)) - { - if (!vertices.contains(t) || t.equals(v)) - continue; - newGraph.addVertex(t); - newGraph.addEdge(edge_factory.create(), v, t); - } - } - } - return newGraph; - } - - /** - * Converts g into a unipartite graph whose vertices are the - * vertices of g's partition p, and whose edges - * consist of collections of the intermediate vertices from other partitions. - * For vertices - * a and b in this partition, the resultant - * graph will include the edge (a,b) if the original graph - * contains edges (a,c) and (c,b) for at least - * one vertex c. - * - *

      The vertices of the new graph are the same as the vertices of the - * appropriate partition in the old graph; the edges in the new graph are - * collections of the intermediate vertices c.

      - * - *

      This function will not create self-loops.

      - * - * @param vertex type - * @param input edge type - * @param g input k-partite graph - * @param p predicate specifying vertex partition - * @param graph_factory factory used to create the output graph - * @return the result of folding g into unipartite graph whose vertices - * are those of the p partition of g - */ - public static Graph> foldKPartiteGraph(KPartiteGraph g, Predicate p, - Factory>> graph_factory) - { - Graph> newGraph = graph_factory.create(); - - // get vertices for the specified partition, copy into new graph - Collection vertices = g.getVertices(p); - - for (V v : vertices) - { - newGraph.addVertex(v); - for (V s : g.getSuccessors(v)) - { - for (V t : g.getSuccessors(s)) - { - if (!vertices.contains(t) || t.equals(v)) - continue; - newGraph.addVertex(t); - Collection v_coll = newGraph.findEdge(v, t); - if (v_coll == null) - { - v_coll = new ArrayList(); - newGraph.addEdge(v_coll, v, t); - } - v_coll.add(s); - } - } - } - return newGraph; - } - - /** - * Creates a Graph which is an edge-folded version of h, where - * hyperedges are replaced by k-cliques in the output graph. - * - *

      The vertices of the new graph are the same objects as the vertices of - * h, and a - * is connected to b in the new graph if the corresponding vertices - * in h are connected by a hyperedge. Thus, each hyperedge with - * k vertices in h induces a k-clique in the new graph.

      - * - *

      The edges of the new graph consist of collections of each hyperedge that connected - * the corresponding vertex pair in the original graph.

      - * - * @param vertex type - * @param input edge type - * @param h hypergraph to be folded - * @param graph_factory factory used to generate the output graph - * @return a copy of the input graph where hyperedges are replaced by cliques - */ - public static Graph> foldHypergraphEdges(Hypergraph h, - Factory>> graph_factory) - { - Graph> target = graph_factory.create(); - - for (V v : h.getVertices()) - target.addVertex(v); - - for (E e : h.getEdges()) - { - ArrayList incident = new ArrayList(h.getIncidentVertices(e)); - populateTarget(target, e, incident); - } - return target; - } - - - /** - * Creates a Graph which is an edge-folded version of h, where - * hyperedges are replaced by k-cliques in the output graph. - * - *

      The vertices of the new graph are the same objects as the vertices of - * h, and a - * is connected to b in the new graph if the corresponding vertices - * in h are connected by a hyperedge. Thus, each hyperedge with - * k vertices in h induces a k-clique in the new graph.

      - * - *

      The edges of the new graph are generated by the specified edge factory.

      - * - * @param vertex type - * @param input edge type - * @param h hypergraph to be folded - * @param graph_factory factory used to generate the output graph - * @param edge_factory factory used to create the new edges - * @return a copy of the input graph where hyperedges are replaced by cliques - */ - public static Graph foldHypergraphEdges(Hypergraph h, - Factory> graph_factory, Factory edge_factory) - { - Graph target = graph_factory.create(); - - for (V v : h.getVertices()) - target.addVertex(v); - - for (E e : h.getEdges()) - { - ArrayList incident = new ArrayList(h.getIncidentVertices(e)); - for (int i = 0; i < incident.size(); i++) - for (int j = i+1; j < incident.size(); j++) - target.addEdge(edge_factory.create(), incident.get(i), incident.get(j)); - } - return target; - } - - /** - * Creates a Graph which is a vertex-folded version of h, whose - * vertices are the input's hyperedges and whose edges are induced by adjacent hyperedges - * in the input. - * - *

      The vertices of the new graph are the same objects as the hyperedges of - * h, and a - * is connected to b in the new graph if the corresponding edges - * in h have a vertex in common. Thus, each vertex incident to - * k edges in h induces a k-clique in the new graph.

      - * - *

      The edges of the new graph are created by the specified factory.

      - * - * @param vertex type - * @param input edge type - * @param output edge type - * @param h hypergraph to be folded - * @param graph_factory factory used to generate the output graph - * @param edge_factory factory used to generate the output edges - * @return a transformation of the input graph whose vertices correspond to the input's hyperedges - * and edges are induced by hyperedges sharing vertices in the input - */ - public static Graph foldHypergraphVertices(Hypergraph h, - Factory> graph_factory, Factory edge_factory) - { - Graph target = graph_factory.create(); - - for (E e : h.getEdges()) - target.addVertex(e); - - for (V v : h.getVertices()) - { - ArrayList incident = new ArrayList(h.getIncidentEdges(v)); - for (int i = 0; i < incident.size(); i++) - for (int j = i+1; j < incident.size(); j++) - target.addEdge(edge_factory.create(), incident.get(i), incident.get(j)); - } - - return target; - } - - /** - * Creates a Graph which is a vertex-folded version of h, whose - * vertices are the input's hyperedges and whose edges are induced by adjacent hyperedges - * in the input. - * - *

      The vertices of the new graph are the same objects as the hyperedges of - * h, and a - * is connected to b in the new graph if the corresponding edges - * in h have a vertex in common. Thus, each vertex incident to - * k edges in h induces a k-clique in the new graph.

      - * - *

      The edges of the new graph consist of collections of each vertex incident to - * the corresponding hyperedge pair in the original graph.

      - * - * @param h hypergraph to be folded - * @param graph_factory factory used to generate the output graph - * @return a transformation of the input graph whose vertices correspond to the input's hyperedges - * and edges are induced by hyperedges sharing vertices in the input - */ - public Graph> foldHypergraphVertices(Hypergraph h, - Factory>> graph_factory) - { - Graph> target = graph_factory.create(); - - for (E e : h.getEdges()) - target.addVertex(e); - - for (V v : h.getVertices()) - { - ArrayList incident = new ArrayList(h.getIncidentEdges(v)); - populateTarget(target, v, incident); - } - return target; - } - - /** - * @param target - * @param e - * @param incident - */ - private static void populateTarget(Graph> target, T e, - ArrayList incident) - { - for (int i = 0; i < incident.size(); i++) - { - S v1 = incident.get(i); - for (int j = i+1; j < incident.size(); j++) - { - S v2 = incident.get(j); - Collection e_coll = target.findEdge(v1, v2); - if (e_coll == null) - { - e_coll = new ArrayList(); - target.addEdge(e_coll, v1, v2); - } - e_coll.add(e); - } - } - } - -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/VertexPartitionCollapser.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/VertexPartitionCollapser.java deleted file mode 100644 index e44d05d446..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/VertexPartitionCollapser.java +++ /dev/null @@ -1,103 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.transformation; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections15.Factory; -import org.apache.commons.collections15.Transformer; -import org.apache.commons.collections15.functors.MapTransformer; - -import edu.uci.ics.jung.algorithms.blockmodel.VertexPartition; -import edu.uci.ics.jung.graph.Graph; - -/** - * This class transforms a graph with a known vertex partitioning into a graph whose - * vertices correspond to the input graph's partitions. Two vertices in the output graph - * are connected if and only if there exists at least one edge between vertices in the - * corresponding partitions of the input graph. If the output graph permits parallel edges, - * there will be an edge connecting two vertices in the new graph for each such - * edge connecting constituent vertices in the input graph. - * - *

      Concept based on Danyel Fisher's GraphCollapser in JUNG 1.x. - * - */ -public class VertexPartitionCollapser -{ - protected Factory> graph_factory; - protected Factory vertex_factory; - protected Factory edge_factory; - protected Map, CV> set_collapsedv; - - /** - * Creates an instance with the specified graph and element factories. - * @param vertex_factory used to construct the vertices of the new graph - * @param edge_factory used to construct the edges of the new graph - * @param graph_factory used to construct the new graph - */ - public VertexPartitionCollapser(Factory> graph_factory, - Factory vertex_factory, Factory edge_factory) - { - this.graph_factory = graph_factory; - this.vertex_factory = vertex_factory; - this.edge_factory = edge_factory; - this.set_collapsedv = new HashMap, CV>(); - } - - /** - * Creates a new graph whose vertices correspond to the partitions of the supplied graph. - * @param partitioning - * @return a new graph whose vertices correspond to the partitions of the supplied graph - */ - public Graph collapseVertexPartitions(VertexPartition partitioning) - { - Graph original = partitioning.getGraph(); - Graph collapsed = graph_factory.create(); - - // create vertices in new graph corresponding to equivalence sets in the original graph - for (Set set : partitioning.getVertexPartitions()) - { - CV cv = vertex_factory.create(); - collapsed.addVertex(vertex_factory.create()); - set_collapsedv.put(set, cv); - } - - // create edges in new graph corresponding to edges in original graph - for (E e : original.getEdges()) - { - Collection incident = original.getIncidentVertices(e); - Collection collapsed_vertices = new HashSet(); - Map> vertex_partitions = partitioning.getVertexToPartitionMap(); - // collect the collapsed vertices corresponding to the original incident vertices - for (V v : incident) - collapsed_vertices.add(set_collapsedv.get(vertex_partitions.get(v))); - // if there's only one collapsed vertex, continue (no edges to create) - if (collapsed_vertices.size() > 1) - { - CE ce = edge_factory.create(); - collapsed.addEdge(ce, collapsed_vertices); - } - } - return collapsed; - } - - /** - * Returns a transformer from vertex sets in the original graph to collapsed vertices - * in the transformed graph. - */ - public Transformer, CV> getSetToCollapsedVertexTransformer() - { - return MapTransformer.getInstance(set_collapsedv); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/package.html deleted file mode 100644 index 6680095fb1..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/transformation/package.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - -Mechanisms for graph transformation. These currently include: -

        -
      • DirectionTransformer: generates graphs where input undirected -edges have been converted to directed edges, or vice versa -
      • FoldingTransformer: transforms k-partite graphs or hypergraphs -into unipartite graphs -
      • VertexPartitionCollapser: transforms a graph, given a -partition of its vertices into disjoint sets, into a graph in which each -of these disjoint sets has been 'collapsed' into a single new vertex. -
      - - - diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/BasicMapEntry.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/BasicMapEntry.java deleted file mode 100644 index a82aea6b98..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/BasicMapEntry.java +++ /dev/null @@ -1,80 +0,0 @@ -package edu.uci.ics.jung.algorithms.util; - -import java.util.HashMap; -import java.util.Map; - -/** - * An simple minimal implementation of Map.Entry. - * - * @param the key type - * @param the value type - */ -public class BasicMapEntry implements Map.Entry { - final K key; - V value; - - /** - * Create new entry. - */ - public BasicMapEntry(K k, V v) { - value = v; - key = k; - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - - public V setValue(V newValue) { - V oldValue = value; - value = newValue; - return oldValue; - } - - @SuppressWarnings("unchecked") - @Override - public boolean equals(Object o) { - if (!(o instanceof Map.Entry)) - return false; - Map.Entry e = (Map.Entry)o; - Object k1 = getKey(); - Object k2 = e.getKey(); - if (k1 == k2 || (k1 != null && k1.equals(k2))) { - Object v1 = getValue(); - Object v2 = e.getValue(); - if (v1 == v2 || (v1 != null && v1.equals(v2))) - return true; - } - return false; - } - - @Override - public int hashCode() { - return (key==null ? 0 : key.hashCode()) ^ - (value==null ? 0 : value.hashCode()); - } - - @Override - public String toString() { - return getKey() + "=" + getValue(); - } - - /** - * This method is invoked whenever the value in an entry is - * overwritten by an invocation of put(k,v) for a key k that's already - * in the HashMap. - */ - void recordAccess(HashMap m) { - } - - /** - * This method is invoked whenever the entry is - * removed from the table. - */ - void recordRemoval(HashMap m) { - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/ConstantMap.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/ConstantMap.java deleted file mode 100644 index 53054d71d9..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/ConstantMap.java +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ - -package edu.uci.ics.jung.algorithms.util; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -/** - * An implementation of Map that returns the constructor-supplied - * value for any input. - * - * @param the key type - * @param the value type - */ -public class ConstantMap implements Map { - - private Map delegate; - - /** - * Creates an instance whose {@code get} method always returns {@code value}. - */ - public ConstantMap(V value) { - delegate = Collections.unmodifiableMap(Collections.singletonMap(null, value)); - } - - public V get(Object key) { - return delegate.get(null); - } - - public void clear() { - delegate.clear(); - } - - public boolean containsKey(Object key) { - return true; - } - - public boolean containsValue(Object value) { - return delegate.containsValue(value); - } - - public Set> entrySet() { - return delegate.entrySet(); - } - - @Override - public boolean equals(Object o) { - return delegate.equals(o); - } - - @Override - public int hashCode() { - return delegate.hashCode(); - } - - public boolean isEmpty() { - return delegate.isEmpty(); - } - - public Set keySet() { - return delegate.keySet(); - } - - public V put(K key, V value) { - return delegate.put(key, value); - } - - public void putAll(Map t) { - delegate.putAll(t); - } - - public V remove(Object key) { - return delegate.remove(key); - } - - public int size() { - return delegate.size(); - } - - public Collection values() { - return delegate.values(); - } -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/DiscreteDistribution.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/DiscreteDistribution.java deleted file mode 100644 index 84eadc0735..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/DiscreteDistribution.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * - * Created on Feb 18, 2004 - */ -package edu.uci.ics.jung.algorithms.util; - -import java.util.Collection; -import java.util.Iterator; - -/** - * A utility class for calculating properties of discrete distributions. - * Generally, these distributions are represented as arrays of - * double values, which are assumed to be normalized - * such that the entries in a single array sum to 1. - * - * @author Joshua O'Madadhain - */ -public class DiscreteDistribution -{ - - /** - * Returns the Kullback-Leibler divergence between the - * two specified distributions, which must have the same - * number of elements. This is defined as - * the sum over all i of - * dist[i] * Math.log(dist[i] / reference[i]). - * Note that this value is not symmetric; see - * symmetricKL for a symmetric variant. - * @see #symmetricKL(double[], double[]) - */ - public static double KullbackLeibler(double[] dist, double[] reference) - { - double distance = 0; - - checkLengths(dist, reference); - - for (int i = 0; i < dist.length; i++) - { - if (dist[i] > 0 && reference[i] > 0) - distance += dist[i] * Math.log(dist[i] / reference[i]); - } - return distance; - } - - /** - * Returns KullbackLeibler(dist, reference) + KullbackLeibler(reference, dist). - * @see #KullbackLeibler(double[], double[]) - */ - public static double symmetricKL(double[] dist, double[] reference) - { - return KullbackLeibler(dist, reference) - + KullbackLeibler(reference, dist); - } - - /** - * Returns the squared difference between the - * two specified distributions, which must have the same - * number of elements. This is defined as - * the sum over all i of the square of - * (dist[i] - reference[i]). - */ - public static double squaredError(double[] dist, double[] reference) - { - double error = 0; - - checkLengths(dist, reference); - - for (int i = 0; i < dist.length; i++) - { - double difference = dist[i] - reference[i]; - error += difference * difference; - } - return error; - } - - /** - * Returns the cosine distance between the two - * specified distributions, which must have the same number - * of elements. The distributions are treated as vectors - * in dist.length-dimensional space. - * Given the following definitions - *
        - *
      • v = the sum over all i of dist[i] * dist[i] - *
      • w = the sum over all i of reference[i] * reference[i] - *
      • vw = the sum over all i of dist[i] * reference[i] - *
      - * the value returned is defined as vw / (Math.sqrt(v) * Math.sqrt(w)). - */ - public static double cosine(double[] dist, double[] reference) - { - double v_prod = 0; // dot product x*x - double w_prod = 0; // dot product y*y - double vw_prod = 0; // dot product x*y - - checkLengths(dist, reference); - - for (int i = 0; i < dist.length; i++) - { - vw_prod += dist[i] * reference[i]; - v_prod += dist[i] * dist[i]; - w_prod += reference[i] * reference[i]; - } - // cosine distance between v and w - return vw_prod / (Math.sqrt(v_prod) * Math.sqrt(w_prod)); - } - - /** - * Returns the entropy of this distribution. - * High entropy indicates that the distribution is - * close to uniform; low entropy indicates that the - * distribution is close to a Dirac delta (i.e., if - * the probability mass is concentrated at a single - * point, this method returns 0). Entropy is defined as - * the sum over all i of - * -(dist[i] * Math.log(dist[i])) - */ - public static double entropy(double[] dist) - { - double total = 0; - - for (int i = 0; i < dist.length; i++) - { - if (dist[i] > 0) - total += dist[i] * Math.log(dist[i]); - } - return -total; - } - - /** - * Throws an IllegalArgumentException if the two arrays are not of the same length. - */ - protected static void checkLengths(double[] dist, double[] reference) - { - if (dist.length != reference.length) - throw new IllegalArgumentException("Arrays must be of the same length"); - } - - /** - * Normalizes, with Lagrangian smoothing, the specified double - * array, so that the values sum to 1 (i.e., can be treated as probabilities). - * The effect of the Lagrangian smoothing is to ensure that all entries - * are nonzero; effectively, a value of alpha is added to each - * entry in the original array prior to normalization. - * @param counts - * @param alpha - */ - public static void normalize(double[] counts, double alpha) - { - double total_count = 0; - - for (int i = 0; i < counts.length; i++) - total_count += counts[i]; - - for (int i = 0; i < counts.length; i++) - counts[i] = (counts[i] + alpha) - / (total_count + counts.length * alpha); - } - - /** - * Returns the mean of the specified Collection of - * distributions, which are assumed to be normalized arrays of - * double values. - * @see #mean(double[][]) - */ - public static double[] mean(Collection distributions) - { - if (distributions.isEmpty()) - throw new IllegalArgumentException("Distribution collection must be non-empty"); - Iterator iter = distributions.iterator(); - double[] first = iter.next(); - double[][] d_array = new double[distributions.size()][first.length]; - d_array[0] = first; - for (int i = 1; i < d_array.length; i++) - d_array[i] = iter.next(); - - return mean(d_array); - } - - /** - * Returns the mean of the specified array of distributions, - * represented as normalized arrays of double values. - * Will throw an "index out of bounds" exception if the - * distribution arrays are not all of the same length. - */ - public static double[] mean(double[][] distributions) - { - double[] d_mean = new double[distributions[0].length]; - for (int j = 0; j < d_mean.length; j++) - d_mean[j] = 0; - - for (int i = 0; i < distributions.length; i++) - for (int j = 0; j < d_mean.length; j++) - d_mean[j] += distributions[i][j] / distributions.length; - - return d_mean; - } - -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/Indexer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/Indexer.java deleted file mode 100644 index b8a215e3d5..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/Indexer.java +++ /dev/null @@ -1,56 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.util; - -import java.util.Collection; - -import org.apache.commons.collections15.BidiMap; -import org.apache.commons.collections15.bidimap.DualHashBidiMap; - -/** - * A class providing static methods useful for improving the - * performance of graph algorithms. - * - * @author Tom Nelson - * - */ -public class Indexer { - - /** - * Returns a BidiMap mapping each element of the collection to its - * index as encountered while iterating over the collection. The purpose - * of the index operation is to supply an O(1) replacement operation for the - * O(n) indexOf(element) method of a List - * @param - * @param collection - * @return a bidirectional map from collection elements to 0-based indices - */ - public static BidiMap create(Collection collection) { - return create(collection, 0); - } - /** - * Returns a BidiMap mapping each element of the collection to its - * index as encountered while iterating over the collection. The purpose - * of the index operation is to supply an O(1) replacement operation for the - * O(n) indexOf(element) method of a List - * @param - * @param collection - * @param start start index - * @return a bidirectional map from collection elements to start-based indices - */ - public static BidiMap create(Collection collection, int start) { - BidiMap map = new DualHashBidiMap(); - int i=start; - for(T t : collection) { - map.put(t,i++); - } - return map; - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/IterativeContext.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/IterativeContext.java deleted file mode 100644 index 92bd45d3f4..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/IterativeContext.java +++ /dev/null @@ -1,28 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.util; - - -/** - * An interface for algorithms that proceed iteratively. - * - */ -public interface IterativeContext -{ - /** - * Advances one step. - */ - void step(); - - /** - * Returns true if this iterative process is finished, and false otherwise. - */ - boolean done(); -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/IterativeProcess.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/IterativeProcess.java deleted file mode 100644 index fbe07f4e86..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/IterativeProcess.java +++ /dev/null @@ -1,174 +0,0 @@ -/* -* Copyright (c) 2003, the JUNG Project and the Regents of the University -* of California -* All rights reserved. -* -* This software is open-source under the BSD license; see either -* "license.txt" or -* http://jung.sourceforge.net/license.txt for a description. -*/ -package edu.uci.ics.jung.algorithms.util; - - - -/** - * Provides basic infrastructure for iterative algorithms. Services provided include: - *
        - *
      • storage of current and max iteration count
      • - *
      • framework for initialization, iterative evaluation, and finalization
      • - *
      • test for convergence
      • - *
      • etc.
      • - *
      - *

      - * Algorithms that subclass this class are typically used in the following way:
      - *

      - * FooAlgorithm foo = new FooAlgorithm(...)
      - * foo.setMaximumIterations(100); //set up conditions
      - * ...
      - * foo.evaluate(); //key method which initiates iterative process
      - * foo.getSomeResult();
      - * 
      - * - * @author Scott White (originally written by Didier Besset) - */ -public abstract class IterativeProcess implements IterativeContext { - /** - * Number of iterations performed. - */ - private int iterations; - /** - * Maximum allowed number of iterations. - */ - private int maximumIterations = 50; - /** - * Desired precision. - */ - private double desiredPrecision = Double.MIN_VALUE; - /** - * Achieved precision. - */ - private double precision; - - - /** - * Generic constructor. - */ - public IterativeProcess() { - } - - /** - * Performs the iterative process. - * Note: this method does not return anything because Java does not - * allow mixing double, int, or objects - */ - public void evaluate() { - iterations = 0; - initializeIterations(); - while (iterations++ < maximumIterations) { - step(); - precision = getPrecision(); - if (hasConverged()) - break; - } - finalizeIterations(); - } - - /** - * Evaluate the result of the current iteration. - */ - abstract public void step(); - - /** - * Perform eventual clean-up operations - * (must be implement by subclass when needed). - */ - protected void finalizeIterations() { - } - - /** - * Returns the desired precision. - */ - public double getDesiredPrecision() { - return desiredPrecision; - } - - /** - * Returns the number of iterations performed. - */ - public int getIterations() { - return iterations; - } - - /** - * Returns the maximum allowed number of iterations. - */ - public int getMaximumIterations() { - return maximumIterations; - } - - /** - * Returns the attained precision. - */ - public double getPrecision() { - return precision; - } - - /** - * @param precision the precision to set - */ - public void setPrecision(double precision) { - this.precision = precision; - } - - /** - * - * Check to see if the result has been attained. - * @return boolean - */ - public boolean hasConverged() { - return precision < desiredPrecision; - } - - public boolean done() { - return hasConverged(); - } - - /** - * Initializes internal parameters to start the iterative process. - */ - protected void initializeIterations() { - } - - /** - * - */ - public void reset() { - } - - /** - * @return double - * @param epsilon double - * @param x double - */ - public double relativePrecision(double epsilon, double x) { - return x > desiredPrecision ? epsilon / x: epsilon; - } - - /** - * Defines the desired precision. - */ - public void setDesiredPrecision(double prec) throws IllegalArgumentException { - if (prec <= 0) - throw new IllegalArgumentException("Non-positive precision: " + prec); - desiredPrecision = prec; - } - - /** - * Defines the maximum allowed number of iterations. - */ - public void setMaximumIterations(int maxIter) throws IllegalArgumentException { - if (maxIter < 1) - throw new IllegalArgumentException("Non-positive maximum iteration: " + maxIter); - maximumIterations = maxIter; - } -} \ No newline at end of file diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/KMeansClusterer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/KMeansClusterer.java deleted file mode 100644 index dce550f477..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/KMeansClusterer.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -/* - * Created on Aug 9, 2004 - * - */ -package edu.uci.ics.jung.algorithms.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Random; -import java.util.Set; - - - -/** - * Groups items into a specified number of clusters, based on their proximity in - * d-dimensional space, using the k-means algorithm. Calls to - * cluster will terminate when either of the two following - * conditions is true: - *
        - *
      • the number of iterations is > max_iterations - *
      • none of the centroids has moved as much as convergence_threshold - * since the previous iteration - *
      - * - * @author Joshua O'Madadhain - */ -public class KMeansClusterer -{ - protected int max_iterations; - protected double convergence_threshold; - protected Random rand; - - /** - * Creates an instance whose termination conditions are set according - * to the parameters. - */ - public KMeansClusterer(int max_iterations, double convergence_threshold) - { - this.max_iterations = max_iterations; - this.convergence_threshold = convergence_threshold; - this.rand = new Random(); - } - - /** - * Creates an instance with max iterations of 100 and convergence threshold - * of 0.001. - */ - public KMeansClusterer() - { - this(100, 0.001); - } - - /** - * Returns the maximum number of iterations. - */ - public int getMaxIterations() - { - return max_iterations; - } - - /** - * Sets the maximum number of iterations. - */ - public void setMaxIterations(int max_iterations) - { - if (max_iterations < 0) - throw new IllegalArgumentException("max iterations must be >= 0"); - - this.max_iterations = max_iterations; - } - - /** - * Returns the convergence threshold. - */ - public double getConvergenceThreshold() - { - return convergence_threshold; - } - - /** - * Sets the convergence threshold. - * @param convergence_threshold - */ - public void setConvergenceThreshold(double convergence_threshold) - { - if (convergence_threshold <= 0) - throw new IllegalArgumentException("convergence threshold " + - "must be > 0"); - - this.convergence_threshold = convergence_threshold; - } - - /** - * Returns a Collection of clusters, where each cluster is - * represented as a Map of Objects to locations - * in d-dimensional space. - * @param object_locations a map of the Objects to cluster, to - * double arrays that specify their locations in d-dimensional space. - * @param num_clusters the number of clusters to create - * @throws NotEnoughClustersException - */ - @SuppressWarnings("unchecked") - public Collection> cluster(Map object_locations, int num_clusters) - { - if (object_locations == null || object_locations.isEmpty()) - throw new IllegalArgumentException("'objects' must be non-empty"); - - if (num_clusters < 2 || num_clusters > object_locations.size()) - throw new IllegalArgumentException("number of clusters " + - "must be >= 2 and <= number of objects (" + - object_locations.size() + ")"); - - - Set centroids = new HashSet(); - - Object[] obj_array = object_locations.keySet().toArray(); - Set tried = new HashSet(); - - // create the specified number of clusters - while (centroids.size() < num_clusters && tried.size() < object_locations.size()) - { - T o = (T)obj_array[(int)(rand.nextDouble() * obj_array.length)]; - tried.add(o); - double[] mean_value = object_locations.get(o); - boolean duplicate = false; - for (double[] cur : centroids) - { - if (Arrays.equals(mean_value, cur)) - duplicate = true; - } - if (!duplicate) - centroids.add(mean_value); - } - - if (tried.size() >= object_locations.size()) - throw new NotEnoughClustersException(); - - // put items in their initial clusters - Map> clusterMap = assignToClusters(object_locations, centroids); - - // keep reconstituting clusters until either - // (a) membership is stable, or - // (b) number of iterations passes max_iterations, or - // (c) max movement of any centroid is <= convergence_threshold - int iterations = 0; - double max_movement = Double.POSITIVE_INFINITY; - while (iterations++ < max_iterations && max_movement > convergence_threshold) - { - max_movement = 0; - Set new_centroids = new HashSet(); - // calculate new mean for each cluster - for (Map.Entry> entry : clusterMap.entrySet()) - { - double[] centroid = entry.getKey(); - Map elements = entry.getValue(); - ArrayList locations = new ArrayList(elements.values()); - - double[] mean = DiscreteDistribution.mean(locations); - max_movement = Math.max(max_movement, - Math.sqrt(DiscreteDistribution.squaredError(centroid, mean))); - new_centroids.add(mean); - } - - // TODO: check membership of clusters: have they changed? - - // regenerate cluster membership based on means - clusterMap = assignToClusters(object_locations, new_centroids); - } - return clusterMap.values(); - } - - /** - * Assigns each object to the cluster whose centroid is closest to the - * object. - * @param object_locations a map of objects to locations - * @param centroids the centroids of the clusters to be formed - * @return a map of objects to assigned clusters - */ - protected Map> assignToClusters(Map object_locations, Set centroids) - { - Map> clusterMap = new HashMap>(); - for (double[] centroid : centroids) - clusterMap.put(centroid, new HashMap()); - - for (Map.Entry object_location : object_locations.entrySet()) - { - T object = object_location.getKey(); - double[] location = object_location.getValue(); - - // find the cluster with the closest centroid - Iterator c_iter = centroids.iterator(); - double[] closest = c_iter.next(); - double distance = DiscreteDistribution.squaredError(location, closest); - - while (c_iter.hasNext()) - { - double[] centroid = c_iter.next(); - double dist_cur = DiscreteDistribution.squaredError(location, centroid); - if (dist_cur < distance) - { - distance = dist_cur; - closest = centroid; - } - } - clusterMap.get(closest).put(object, location); - } - - return clusterMap; - } - - /** - * Sets the seed used by the internal random number generator. - * Enables consistent outputs. - */ - public void setSeed(int random_seed) - { - this.rand = new Random(random_seed); - } - - /** - * An exception that indicates that the specified data points cannot be - * clustered into the number of clusters requested by the user. - * This will happen if and only if there are fewer distinct points than - * requested clusters. (If there are fewer total data points than - * requested clusters, IllegalArgumentException will be thrown.) - * - * @author Joshua O'Madadhain - */ - @SuppressWarnings("serial") - public static class NotEnoughClustersException extends RuntimeException - { - @Override - public String getMessage() - { - return "Not enough distinct points in the input data set to form " + - "the requested number of clusters"; - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/MapBinaryHeap.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/MapBinaryHeap.java deleted file mode 100644 index bd00a82810..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/MapBinaryHeap.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Copyright (c) 2003, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -/* - * - * Created on Oct 29, 2003 - */ -package edu.uci.ics.jung.algorithms.util; - -import java.util.AbstractCollection; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Queue; -import java.util.Vector; - -import org.apache.commons.collections15.IteratorUtils; - -/** - * An array-based binary heap implementation of a priority queue, - * which also provides - * efficient update() and contains operations. - * It contains extra infrastructure (a hash table) to keep track of the - * position of each element in the array; thus, if the key value of an element - * changes, it may be "resubmitted" to the heap via update - * so that the heap can reposition it efficiently, as necessary. - * - * @author Joshua O'Madadhain - */ -public class MapBinaryHeap - extends AbstractCollection - implements Queue -{ - private Vector heap = new Vector(); // holds the heap as an implicit binary tree - private Map object_indices = new HashMap(); // maps each object in the heap to its index in the heap - private Comparator comp; - private final static int TOP = 0; // the index of the top of the heap - - /** - * Creates a MapBinaryHeap whose heap ordering - * is based on the ordering of the elements specified by c. - */ - public MapBinaryHeap(Comparator comp) - { - initialize(comp); - } - - /** - * Creates a MapBinaryHeap whose heap ordering - * will be based on the natural ordering of the elements, - * which must be Comparable. - */ - public MapBinaryHeap() - { - initialize(new ComparableComparator()); - } - - /** - * Creates a MapBinaryHeap based on the specified - * collection whose heap ordering - * will be based on the natural ordering of the elements, - * which must be Comparable. - */ - public MapBinaryHeap(Collection c) - { - this(); - addAll(c); - } - - /** - * Creates a MapBinaryHeap based on the specified collection - * whose heap ordering - * is based on the ordering of the elements specified by c. - */ - public MapBinaryHeap(Collection c, Comparator comp) - { - this(comp); - addAll(c); - } - - private void initialize(Comparator comp) - { - this.comp = comp; - clear(); - } - - /** - * @see Collection#clear() - */ - @Override - public void clear() - { - object_indices.clear(); - heap.clear(); - } - - /** - * Inserts o into this collection. - */ - @Override - public boolean add(T o) - { - int i = heap.size(); // index 1 past the end of the heap - heap.setSize(i+1); - percolateUp(i, o); - return true; - } - - /** - * Returns true if this collection contains no elements, and - * false otherwise. - */ - @Override - public boolean isEmpty() - { - return heap.isEmpty(); - } - - /** - * Returns the element at the top of the heap; does not - * alter the heap. - */ - public T peek() - { - if (heap.size() > 0) - return heap.elementAt(TOP); - else - return null; - } - - /** - * Removes the element at the top of this heap, and returns it. - * @deprecated Use {@link MapBinaryHeap#poll()} - * or {@link MapBinaryHeap#remove()} instead. - */ - @Deprecated - public T pop() throws NoSuchElementException - { - return this.remove(); - } - - /** - * Returns the size of this heap. - */ - @Override - public int size() - { - return heap.size(); - } - - /** - * Informs the heap that this object's internal key value has been - * updated, and that its place in the heap may need to be shifted - * (up or down). - * @param o - */ - public void update(T o) - { - // Since we don't know whether the key value increased or - // decreased, we just percolate up followed by percolating down; - // one of the two will have no effect. - - int cur = object_indices.get(o).intValue(); // current index - int new_idx = percolateUp(cur, o); - percolateDown(new_idx); - } - - /** - * @see Collection#contains(java.lang.Object) - */ - @Override - public boolean contains(Object o) - { - return object_indices.containsKey(o); - } - - /** - * Moves the element at position cur closer to - * the bottom of the heap, or returns if no further motion is - * necessary. Calls itself recursively if further motion is - * possible. - */ - private void percolateDown(int cur) - { - int left = lChild(cur); - int right = rChild(cur); - int smallest; - - if ((left < heap.size()) && - (comp.compare(heap.elementAt(left), heap.elementAt(cur)) < 0)) { - smallest = left; - } else { - smallest = cur; - } - - if ((right < heap.size()) && - (comp.compare(heap.elementAt(right), heap.elementAt(smallest)) < 0)) { - smallest = right; - } - - if (cur != smallest) - { - swap(cur, smallest); - percolateDown(smallest); - } - } - - /** - * Moves the element o at position cur - * as high as it can go in the heap. Returns the new position of the - * element in the heap. - */ - private int percolateUp(int cur, T o) - { - int i = cur; - - while ((i > TOP) && (comp.compare(heap.elementAt(parent(i)), o) > 0)) - { - T parentElt = heap.elementAt(parent(i)); - heap.setElementAt(parentElt, i); - object_indices.put(parentElt, new Integer(i)); // reset index to i (new location) - i = parent(i); - } - - // place object in heap at appropriate place - object_indices.put(o, new Integer(i)); - heap.setElementAt(o, i); - - return i; - } - - /** - * Returns the index of the left child of the element at - * index i of the heap. - * @param i - * @return the index of the left child of the element at - * index i of the heap - */ - private int lChild(int i) - { - return (i<<1) + 1; - } - - /** - * Returns the index of the right child of the element at - * index i of the heap. - * @param i - * @return the index of the right child of the element at - * index i of the heap - */ - private int rChild(int i) - { - return (i<<1) + 2; - } - - /** - * Returns the index of the parent of the element at - * index i of the heap. - * @param i - * @return the index of the parent of the element at index i of the heap - */ - private int parent(int i) - { - return (i-1)>>1; - } - - /** - * Swaps the positions of the elements at indices i - * and j of the heap. - * @param i - * @param j - */ - private void swap(int i, int j) - { - T iElt = heap.elementAt(i); - T jElt = heap.elementAt(j); - - heap.setElementAt(jElt, i); - object_indices.put(jElt, new Integer(i)); - - heap.setElementAt(iElt, j); - object_indices.put(iElt, new Integer(j)); - } - - /** - * Comparator used if none is specified in the constructor. - * @author Joshua O'Madadhain - */ - private class ComparableComparator implements Comparator - { - /** - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) - */ - @SuppressWarnings("unchecked") - public int compare(T arg0, T arg1) - { - if (!(arg0 instanceof Comparable) || !(arg1 instanceof Comparable)) - throw new IllegalArgumentException("Arguments must be Comparable"); - - return ((Comparable)arg0).compareTo(arg1); - } - } - - /** - * Returns an Iterator that does not support modification - * of the heap. - */ - @Override - public Iterator iterator() - { - return IteratorUtils.unmodifiableIterator(heap.iterator()); - } - - /** - * This data structure does not support the removal of arbitrary elements. - */ - @Override - public boolean remove(Object o) - { - throw new UnsupportedOperationException(); - } - - /** - * This data structure does not support the removal of arbitrary elements. - */ - @Override - public boolean removeAll(Collection c) - { - throw new UnsupportedOperationException(); - } - - /** - * This data structure does not support the removal of arbitrary elements. - */ - @Override - public boolean retainAll(Collection c) - { - throw new UnsupportedOperationException(); - } - - public T element() throws NoSuchElementException - { - T top = this.peek(); - if (top == null) - throw new NoSuchElementException(); - return top; - } - - public boolean offer(T o) - { - return add(o); - } - - public T poll() - { - T top = this.peek(); - if (top != null) - { - T bottom_elt = heap.lastElement(); - heap.setElementAt(bottom_elt, TOP); - object_indices.put(bottom_elt, new Integer(TOP)); - - heap.setSize(heap.size() - 1); // remove the last element - if (heap.size() > 1) - percolateDown(TOP); - - object_indices.remove(top); - } - return top; - } - - public T remove() - { - T top = this.poll(); - if (top == null) - throw new NoSuchElementException(); - return top; - } - -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/MapSettableTransformer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/MapSettableTransformer.java deleted file mode 100644 index 1aa7d50709..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/MapSettableTransformer.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Created on Aug 5, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.util; - -import java.util.Map; - - -/** - * A SettableTransformer that operates on an underlying Map instance. - * Similar to MapTransformer. - * - * @author Joshua O'Madadhain - */ -public class MapSettableTransformer implements SettableTransformer -{ - protected Map map; - - /** - * Creates an instance based on m. - */ - public MapSettableTransformer(Map m) - { - this.map = m; - } - - public O transform(I input) - { - return map.get(input); - } - - public void set(I input, O output) - { - map.put(input, output); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/SelfLoopEdgePredicate.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/SelfLoopEdgePredicate.java deleted file mode 100644 index a92c3b8d43..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/SelfLoopEdgePredicate.java +++ /dev/null @@ -1,23 +0,0 @@ -package edu.uci.ics.jung.algorithms.util; - -import org.apache.commons.collections15.Predicate; - -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.util.Context; -import edu.uci.ics.jung.graph.util.Pair; - -/** - * A Predicate that returns true if the input edge's - * endpoints in the input graph are identical. (Thus, an edge which connects - * its sole incident vertex to itself). - * - * @param - * @param - */ -public class SelfLoopEdgePredicate implements Predicate,E>> { - - public boolean evaluate(Context,E> context) { - Pair endpoints = context.graph.getEndpoints(context.element); - return endpoints.getFirst().equals(endpoints.getSecond()); - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/SettableTransformer.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/SettableTransformer.java deleted file mode 100644 index 5e5168abf1..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/SettableTransformer.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Created on Aug 5, 2007 - * - * Copyright (c) 2007, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - */ -package edu.uci.ics.jung.algorithms.util; - -import org.apache.commons.collections15.Transformer; - -/** - * An interface for classes that can set the value to be returned (from transform()) - * when invoked on a given input. - * - * @author Joshua O'Madadhain - */ -public interface SettableTransformer extends Transformer -{ - /** - * Sets the value (output) to be returned by a call to - * transform(input)). - * @param input - * @param output - */ - public void set(I input, O output); -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/WeightedChoice.java b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/WeightedChoice.java deleted file mode 100644 index d9590b26a6..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/WeightedChoice.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Copyright (c) 2009, the JUNG Project and the Regents of the University - * of California - * All rights reserved. - * - * This software is open-source under the BSD license; see either - * "license.txt" or - * http://jung.sourceforge.net/license.txt for a description. - * Created on Jan 8, 2009 - * - */ -package edu.uci.ics.jung.algorithms.util; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Random; - -/** - * Selects items according to their probability in an arbitrary probability - * distribution. The distribution is specified by a {@code Map} from - * items (of type {@code T}) to weights of type {@code Number}, supplied - * to the constructor; these weights are normalized internally to act as - * probabilities. - * - *

      This implementation selects items in O(1) time, and requires O(n) space. - * - * @author Joshua O'Madadhain - */ -public class WeightedChoice -{ - private List item_pairs; - private Random random; - - /** - * The default minimum value that is treated as a valid probability - * (as opposed to rounding error from floating-point operations). - */ - public static final double DEFAULT_THRESHOLD = 0.00000000001; - - /** - * Equivalent to {@code this(item_weights, new Random(), DEFAULT_THRESHOLD)}. - * @param item_weights - */ - public WeightedChoice(Map item_weights) - { - this(item_weights, new Random(), DEFAULT_THRESHOLD); - } - - /** - * Equivalent to {@code this(item_weights, new Random(), threshold)}. - */ - public WeightedChoice(Map item_weights, double threshold) - { - this(item_weights, new Random(), threshold); - } - - /** - * Equivalent to {@code this(item_weights, random, DEFAULT_THRESHOLD)}. - */ - public WeightedChoice(Map item_weights, Random random) - { - this(item_weights, random, DEFAULT_THRESHOLD); - } - - /** - * Creates an instance with the specified mapping from items to weights, - * random number generator, and threshold value. - * - *

      The mapping defines the weight for each item to be selected; this - * will be proportional to the probability of its selection. - *

      The random number generator specifies the mechanism which will be - * used to provide uniform integer and double values. - *

      The threshold indicates default minimum value that is treated as a valid - * probability (as opposed to rounding error from floating-point operations). - */ - public WeightedChoice(Map item_weights, Random random, - double threshold) - { - if (item_weights.isEmpty()) - throw new IllegalArgumentException("Item weights must be non-empty"); - - int item_count = item_weights.size(); - item_pairs = new ArrayList(item_count); - - double sum = 0; - for (Map.Entry entry : item_weights.entrySet()) - { - double value = entry.getValue().doubleValue(); - if (value <= 0) - throw new IllegalArgumentException("Weights must be > 0"); - sum += value; - } - double bucket_weight = 1.0 / item_weights.size(); - - Queue light_weights = new LinkedList(); - Queue heavy_weights = new LinkedList(); - for (Map.Entry entry : item_weights.entrySet()) - { - double value = entry.getValue().doubleValue() / sum; - enqueueItem(entry.getKey(), value, bucket_weight, light_weights, heavy_weights); - } - - // repeat until both queues empty - while (!heavy_weights.isEmpty() || !light_weights.isEmpty()) - { - ItemPair heavy_item = heavy_weights.poll(); - ItemPair light_item = light_weights.poll(); - double light_weight = 0; - T light = null; - T heavy = null; - if (light_item != null) - { - light_weight = light_item.weight; - light = light_item.light; - } - if (heavy_item != null) - { - heavy = heavy_item.heavy; - // put the 'left over' weight from the heavy item--what wasn't - // needed to make up the difference between the light weight and - // 1/n--back in the appropriate queue - double new_weight = heavy_item.weight - (bucket_weight - light_weight); - if (new_weight > threshold) - enqueueItem(heavy, new_weight, bucket_weight, light_weights, heavy_weights); - } - light_weight *= item_count; - - item_pairs.add(new ItemPair(light, heavy, light_weight)); - } - - this.random = random; - } - - /** - * Adds key/value to the appropriate queue. Keys with values less than - * the threshold get added to {@code light_weights}, all others get added - * to {@code heavy_weights}. - */ - private void enqueueItem(T key, double value, double threshold, - Queue light_weights, Queue heavy_weights) - { - if (value < threshold) - light_weights.offer(new ItemPair(key, null, value)); - else - heavy_weights.offer(new ItemPair(null, key, value)); - } - - /** - * Sets the seed used by the internal random number generator. - */ - public void setRandomSeed(long seed) - { - this.random.setSeed(seed); - } - - /** - * Retrieves an item with probability proportional to its weight in the - * {@code Map} provided in the input. - */ - public T nextItem() - { - ItemPair item_pair = item_pairs.get(random.nextInt(item_pairs.size())); - if (random.nextDouble() < item_pair.weight) - return item_pair.light; - return item_pair.heavy; - } - - /** - * Manages light object/heavy object/light conditional probability tuples. - */ - private class ItemPair - { - T light; - T heavy; - double weight; - - private ItemPair(T light, T heavy, double weight) - { - this.light = light; - this.heavy = heavy; - this.weight = weight; - } - - @Override - public String toString() - { - return String.format("[L:%s, H:%s, %.3f]", light, heavy, weight); - } - } -} diff --git a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/package.html b/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/package.html deleted file mode 100644 index 58c5f591f0..0000000000 --- a/third-party/net.sf.jung2/src/main/java/edu/uci/ics/jung/algorithms/util/package.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - -Provides general algorithmic utilities. These include: -

        -
      • DiscreteDistribution: calculates statistical measures on -discrete probability distributions represented as double arrays -
      • KMeansClusterer: uses the k-means algorithm to cluster -points in d-dimensional space into k clusters -
      • MapBinaryHeap: a binary heap implementation that permits -efficient element access and update operations -
      • RandomLocationTransformer: a class that randomly assigns -2D coordinates to items (default initializer for iterative Layouts) -
      • SettableTransformer: an extension of Transformer -that allows mutation of the transformation -
      - - - diff --git a/third-party/openflowj/LICENSE b/third-party/openflowj/LICENSE deleted file mode 100644 index ee6da46abe..0000000000 --- a/third-party/openflowj/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior -University - -We are making the OpenFlow specification and associated documentation -(Software) available for public use and benefit with the expectation that -others will use, modify and enhance the Software and contribute those -enhancements back to the community. However, since we would like to make the -Software available for broadest use, with as few restrictions as possible -permission is hereby granted, free of charge, to any person obtaining a copy of -this Software to deal in the Software under the copyrights without restriction, -including without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -The name and trademarks of copyright holder(s) may NOT be used in advertising -or publicity pertaining to the Software or any derivatives without specific, -written prior permission. diff --git a/third-party/openflowj/Makefile b/third-party/openflowj/Makefile deleted file mode 100644 index b803071a3e..0000000000 --- a/third-party/openflowj/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -# Because I am old and crotchety and my fingers can't stop from running -# `make` commands -all: - ant - -run: - ant run - -doc: - ant javadoc - -tests: - ant tests - -count: - @find . -name \*.java | xargs wc -l | sort -n - -clean: - ant clean diff --git a/third-party/openflowj/README b/third-party/openflowj/README deleted file mode 100644 index 6fffebef0b..0000000000 --- a/third-party/openflowj/README +++ /dev/null @@ -1,16 +0,0 @@ -OpenFlow Java - v1.0.0 - -A Java implementation of low-level OpenFlow packet marshalling/unmarshalling -and IO operations. Implements v1.0 of the OpenFlow specification at -http://www.openflow.org. - - - David Erickson (daviderickson@cs.stanford.edu) - - Rob Sherwood (rob.sherwood@stanford.edu) - -Building requires Maven 2.x+ (http://maven.apache.org/). - -To build: - mvn package - -To build javadocs: - mvn javadoc:javadoc diff --git a/third-party/openflowj/eclipse_codestyle.xml b/third-party/openflowj/eclipse_codestyle.xml deleted file mode 100644 index 6b661c671d..0000000000 --- a/third-party/openflowj/eclipse_codestyle.xml +++ /dev/null @@ -1,269 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/third-party/openflowj/lib/commons-cli-1.2.jar b/third-party/openflowj/lib/commons-cli-1.2.jar deleted file mode 100644 index ce4b9fffe4..0000000000 Binary files a/third-party/openflowj/lib/commons-cli-1.2.jar and /dev/null differ diff --git a/third-party/openflowj/lib/junit-4.8.1.jar b/third-party/openflowj/lib/junit-4.8.1.jar deleted file mode 100644 index 524cd65ce5..0000000000 Binary files a/third-party/openflowj/lib/junit-4.8.1.jar and /dev/null differ diff --git a/third-party/openflowj/pom.xml b/third-party/openflowj/pom.xml deleted file mode 100644 index 9e04a70b83..0000000000 --- a/third-party/openflowj/pom.xml +++ /dev/null @@ -1,140 +0,0 @@ - - 4.0.0 - org.opendaylight.controller.thirdparty - org.openflow.openflowj - 1.1.0-SNAPSHOT - OpenFlow Java - A Java implemention of the OpenFlow v1.0 protocol - - - - org.opendaylight.controller - commons.thirdparty - 1.2.0-SNAPSHOT - ../commons/thirdparty - - - - - David Erickson - daviderickson@cs.stanford.edu - - - Rob Sherwood - rob.sherwood@stanford.edu - - - bundle - http://www.openflow.org - - - The OpenFlow License - http://www.openflowswitch.org/wp/legal/ - repo - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - HEAD - - - UTF-8 - - - - - release-sign-artifacts - - - - - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.1 - - - sign-artifacts - verify - - sign - - - - - forked-path - - - - - - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.6 - true - - - - org.openflow.example;version="1.0.1"; - uses:="org.openflow.example.cli, - org.openflow.protocol, - org.openflow.io, - org.openflow.protocol.factory", - org.openflow.io;version="1.0.1"; - uses:="org.openflow.protocol, - org.openflow.protocol.factory", - org.openflow.protocol;version="1.0.1"; - uses:="org.openflow.protocol.statistics, - org.openflow.protocol, - org.openflow.protocol.factory", - org.openflow.protocol.action;version="1.0.1"; - uses:="org.openflow.protocol", - org.openflow.protocol.factory;version="1.0.1"; - uses:="org.openflow.protocol.statistics, - org.openflow.protocol, - org.openflow.protocol.action, - org.openflow.protocol.queue", - org.openflow.protocol.queue;version="1.0.2"; - uses:="org.openflow.protocol, - org.openflow.protocol.factory", - org.openflow.protocol.statistics;version="1.0.1"; - uses:="org.openflow.protocol, - org.openflow.protocol.factory", - org.openflow.util;version="1.0.1" - - - ${project.basedir}/META-INF - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.5.1 - - 1.7 - 1.7 - - - - - - - junit - junit - 4.8.1 - test - - - diff --git a/third-party/openflowj/src/main/java/org/openflow/example/SelectListener.java b/third-party/openflowj/src/main/java/org/openflow/example/SelectListener.java deleted file mode 100644 index 16fa109c82..0000000000 --- a/third-party/openflowj/src/main/java/org/openflow/example/SelectListener.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * - */ -package org.openflow.example; - -import java.io.IOException; -import java.nio.channels.SelectionKey; - -/** - * @author Rob Sherwood (rob.sherwood@stanford.edu) - * - */ -public interface SelectListener { - /** - * Tell the select listener that an event took place on the passed object - * @param key the key used on the select - * @param arg some parameter passed by the caller when registering - * @throws IOException - */ - void handleEvent(SelectionKey key, Object arg) throws IOException; -} diff --git a/third-party/openflowj/src/main/java/org/openflow/example/SelectLoop.java b/third-party/openflowj/src/main/java/org/openflow/example/SelectLoop.java deleted file mode 100644 index b7927d876e..0000000000 --- a/third-party/openflowj/src/main/java/org/openflow/example/SelectLoop.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.openflow.example; - -import java.io.IOException; -import java.nio.channels.CancelledKeyException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.spi.SelectorProvider; -import java.util.Iterator; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -/*** - * Dirt simple SelectLoop for simple java controller - */ - - -public class SelectLoop { - protected SelectListener callback; - protected boolean dontStop; - protected Object registrationLock; - protected int registrationRequests = 0; - protected Queue registrationQueue; - protected Selector selector; - protected long timeout; - - public SelectLoop(SelectListener cb) throws IOException { - callback = cb; - dontStop = true; - selector = SelectorProvider.provider().openSelector(); - registrationLock = new Object(); - registrationQueue = new ConcurrentLinkedQueue(); - timeout = 0; - } - - /** - * Initializes this SelectLoop - * @param cb the callback to call when select returns - * @param timeout the timeout value in milliseconds that select will be - * called with - * @throws IOException - */ - public SelectLoop(SelectListener cb, long timeout) throws IOException { - callback = cb; - dontStop = true; - selector = SelectorProvider.provider().openSelector(); - registrationLock = new Object(); - registrationQueue = new ConcurrentLinkedQueue(); - this.timeout = timeout; - } - - public void register(SelectableChannel ch, int ops, Object arg) - throws ClosedChannelException { - registrationQueue.add(new Object[] {ch, ops, arg}); - } - - /** - * Registers the supplied SelectableChannel with this SelectLoop. Note this - * method blocks until registration proceeds. It is advised that - * SelectLoop is intialized with a timeout value when using this method. - * @param ch the channel - * @param ops interest ops - * @param arg argument that will be returned with the SelectListener - * @return - * @throws ClosedChannelException - */ - public synchronized SelectionKey registerBlocking(SelectableChannel ch, int ops, Object arg) - throws ClosedChannelException { - synchronized (registrationLock) { - registrationRequests++; - } - selector.wakeup(); - SelectionKey key = ch.register(selector, ops, arg); - synchronized (registrationLock) { - registrationRequests--; - registrationLock.notifyAll(); - } - return key; - } - - /**** - * Main top-level IO loop this dispatches all IO events and timer events - * together I believe this is fairly efficient - */ - public void doLoop() throws IOException { - int nEvents; - processRegistrationQueue(); - - while (dontStop) { - nEvents = selector.select(timeout); - if (nEvents > 0) { - for (Iterator i = selector.selectedKeys() - .iterator(); i.hasNext();) { - SelectionKey sk = i.next(); - i.remove(); - - if (!sk.isValid()) - continue; - - Object arg = sk.attachment(); - callback.handleEvent(sk, arg); - } - } - - if (this.registrationQueue.size() > 0) - processRegistrationQueue(); - - if (registrationRequests > 0) { - synchronized (registrationLock) { - while (registrationRequests > 0) { - try { - registrationLock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - } - } - - protected void processRegistrationQueue() { - // add any elements in queue - for (Iterator it = registrationQueue.iterator(); it.hasNext();) { - Object[] args = it.next(); - SelectableChannel ch = (SelectableChannel) args[0]; - try { - ch.register(selector, (Integer) args[1], args[2]); - } catch (CancelledKeyException cke) { - continue; - } catch (ClosedChannelException e) { - } - it.remove(); - } - } - - /** - * Force this select loop to return immediately and re-enter select, useful - * for example if a new item has been added to the select loop while it - * was already blocked. - */ - public void wakeup() { - if (selector != null) { - selector.wakeup(); - } - } - - /** - * Shuts down this select loop, may return before it has fully shutdown - */ - public void shutdown() { - this.dontStop = false; - wakeup(); - } -} diff --git a/third-party/openflowj/src/main/java/org/openflow/example/SimpleController.java b/third-party/openflowj/src/main/java/org/openflow/example/SimpleController.java deleted file mode 100644 index e18e2f5fca..0000000000 --- a/third-party/openflowj/src/main/java/org/openflow/example/SimpleController.java +++ /dev/null @@ -1,321 +0,0 @@ -/** - * - */ -package org.openflow.example; - -import java.io.IOException; -import java.net.InetAddress; -import java.nio.channels.SelectionKey; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.openflow.example.cli.Options; -import org.openflow.example.cli.ParseException; -import org.openflow.example.cli.SimpleCLI; -import org.openflow.io.OFMessageAsyncStream; -import org.openflow.protocol.OFEchoReply; -import org.openflow.protocol.OFFlowMod; -import org.openflow.protocol.OFMatch; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.OFPacketIn; -import org.openflow.protocol.OFPacketOut; -import org.openflow.protocol.OFPort; -import org.openflow.protocol.OFType; -import org.openflow.protocol.action.OFAction; -import org.openflow.protocol.action.OFActionOutput; -import org.openflow.protocol.factory.BasicFactory; -import org.openflow.util.LRULinkedHashMap; -import org.openflow.util.U16; - -/** - * @author Rob Sherwood (rob.sherwood@stanford.edu), David Erickson (daviderickson@cs.stanford.edu) - * - */ -public class SimpleController implements SelectListener { - protected ExecutorService es; - protected BasicFactory factory; - protected SelectLoop listenSelectLoop; - protected ServerSocketChannel listenSock; - protected List switchSelectLoops; - protected Map switchSockets; - protected Integer threadCount; - protected int port; - - protected class OFSwitch { - protected SocketChannel sock; - protected OFMessageAsyncStream stream; - protected Map macTable = - new LRULinkedHashMap(64001, 64000); - - public OFSwitch(SocketChannel sock, OFMessageAsyncStream stream) { - this.sock = sock; - this.stream = stream; - } - - public void handlePacketIn(OFPacketIn pi) { - // Build the Match - OFMatch match = new OFMatch(); - match.loadFromPacket(pi.getPacketData(), pi.getInPort()); - byte[] dlDst = match.getDataLayerDestination(); - Integer dlDstKey = Arrays.hashCode(dlDst); - byte[] dlSrc = match.getDataLayerSource(); - Integer dlSrcKey = Arrays.hashCode(dlSrc); - int bufferId = pi.getBufferId(); - - // if the src is not multicast, learn it - if ((dlSrc[0] & 0x1) == 0) { - if (!macTable.containsKey(dlSrcKey) || - !macTable.get(dlSrcKey).equals(pi.getInPort())) { - macTable.put(dlSrcKey, pi.getInPort()); - } - } - - Short outPort = null; - // if the destination is not multicast, look it up - if ((dlDst[0] & 0x1) == 0) { - outPort = macTable.get(dlDstKey); - } - - // push a flow mod if we know where the packet should be going - if (outPort != null) { - OFFlowMod fm = (OFFlowMod) factory.getMessage(OFType.FLOW_MOD); - fm.setBufferId(bufferId); - fm.setCommand((short) 0); - fm.setCookie(0); - fm.setFlags((short) 0); - fm.setHardTimeout((short) 0); - fm.setIdleTimeout((short) 5); - match.setInputPort(pi.getInPort()); - match.setWildcards(0); - fm.setMatch(match); - fm.setOutPort((short) OFPort.OFPP_NONE.getValue()); - fm.setPriority((short) 0); - OFActionOutput action = new OFActionOutput(); - action.setMaxLength((short) 0); - action.setPort(outPort); - List actions = new ArrayList(); - actions.add(action); - fm.setActions(actions); - fm.setLength(U16.t(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH)); - try { - stream.write(fm); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // Send a packet out - if (outPort == null || pi.getBufferId() == 0xffffffff) { - OFPacketOut po = new OFPacketOut(); - po.setBufferId(bufferId); - po.setInPort(pi.getInPort()); - - // set actions - OFActionOutput action = new OFActionOutput(); - action.setMaxLength((short) 0); - action.setPort((short) ((outPort == null) ? OFPort.OFPP_FLOOD - .getValue() : outPort)); - List actions = new ArrayList(); - actions.add(action); - po.setActions(actions); - po.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH); - - // set data if needed - if (bufferId == 0xffffffff) { - byte[] packetData = pi.getPacketData(); - po.setLength(U16.t(OFPacketOut.MINIMUM_LENGTH - + po.getActionsLength() + packetData.length)); - po.setPacketData(packetData); - } else { - po.setLength(U16.t(OFPacketOut.MINIMUM_LENGTH - + po.getActionsLength())); - } - try { - stream.write(po); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public String toString() { - InetAddress remote = sock.socket().getInetAddress(); - return remote.getHostAddress() + ":" + sock.socket().getPort(); - } - - public OFMessageAsyncStream getStream() { - return stream; - } - } - - public SimpleController(int port) throws IOException{ - listenSock = ServerSocketChannel.open(); - listenSock.configureBlocking(false); - listenSock.socket().bind(new java.net.InetSocketAddress(port)); - listenSock.socket().setReuseAddress(true); - this.port = port; - switchSelectLoops = new ArrayList(); - switchSockets = new ConcurrentHashMap(); - threadCount = 1; - listenSelectLoop = new SelectLoop(this); - // register this connection for accepting - listenSelectLoop.register(listenSock, SelectionKey.OP_ACCEPT, listenSock); - - this.factory = new BasicFactory(); - } - - @Override - public void handleEvent(SelectionKey key, Object arg) throws IOException { - if (arg instanceof ServerSocketChannel) - handleListenEvent(key, (ServerSocketChannel)arg); - else - handleSwitchEvent(key, (SocketChannel) arg); - } - - protected void handleListenEvent(SelectionKey key, ServerSocketChannel ssc) - throws IOException { - SocketChannel sock = listenSock.accept(); - OFMessageAsyncStream stream = new OFMessageAsyncStream(sock, factory); - switchSockets.put(sock, new OFSwitch(sock, stream)); - System.err - .println("Got new connection from " + switchSockets.get(sock)); - List l = new ArrayList(); - l.add(factory.getMessage(OFType.HELLO)); - l.add(factory.getMessage(OFType.FEATURES_REQUEST)); - stream.write(l); - - int ops = SelectionKey.OP_READ; - if (stream.needsFlush()) - ops |= SelectionKey.OP_WRITE; - - // hash this switch into a thread - SelectLoop sl = switchSelectLoops.get(sock.hashCode() - % switchSelectLoops.size()); - sl.register(sock, ops, sock); - // force select to return and re-enter using the new set of keys - sl.wakeup(); - } - - protected void handleSwitchEvent(SelectionKey key, SocketChannel sock) { - OFSwitch sw = switchSockets.get(sock); - OFMessageAsyncStream stream = sw.getStream(); - try { - if (key.isReadable()) { - List msgs = stream.read(); - if (msgs == null) { - key.cancel(); - switchSockets.remove(sock); - return; - } - - for (OFMessage m : msgs) { - switch (m.getType()) { - case PACKET_IN: - sw.handlePacketIn((OFPacketIn) m); - break; - case HELLO: - System.err.println("GOT HELLO from " + sw); - break; - case ECHO_REQUEST: - OFEchoReply reply = (OFEchoReply) stream - .getMessageFactory().getMessage( - OFType.ECHO_REPLY); - reply.setXid(m.getXid()); - stream.write(reply); - break; - default: - System.err.println("Unhandled OF message: " - + m.getType() + " from " - + sock.socket().getInetAddress()); - } - } - } - if (key.isWritable()) { - stream.flush(); - } - - /** - * Only register for interest in R OR W, not both, causes stream - * deadlock after some period of time - */ - if (stream.needsFlush()) - key.interestOps(SelectionKey.OP_WRITE); - else - key.interestOps(SelectionKey.OP_READ); - } catch (IOException e) { - // if we have an exception, disconnect the switch - key.cancel(); - switchSockets.remove(sock); - } - } - - public void run() throws IOException{ - System.err.println("Starting " + this.getClass().getCanonicalName() + - " on port " + this.port + " with " + this.threadCount + " threads"); - // Static number of threads equal to processor cores - es = Executors.newFixedThreadPool(threadCount); - - // Launch one select loop per threadCount and start running - for (int i = 0; i < threadCount; ++i) { - final SelectLoop sl = new SelectLoop(this); - switchSelectLoops.add(sl); - es.execute(new Runnable() { - @Override - public void run() { - try { - sl.doLoop(); - } catch (IOException e) { - e.printStackTrace(); - } - }} - ); - } - - // Start the listen loop - listenSelectLoop.doLoop(); - } - - public static void main(String [] args) throws IOException { - SimpleCLI cmd = parseArgs(args); - int port = Integer.valueOf(cmd.getOptionValue("p")); - SimpleController sc = new SimpleController(port); - sc.threadCount = Integer.valueOf(cmd.getOptionValue("t")); - sc.run(); - } - - public static SimpleCLI parseArgs(String[] args) { - Options options = new Options(); - options.addOption("h", "help", "print help"); - // unused? - // options.addOption("n", true, "the number of packets to send"); - options.addOption("p", "port", 6633, "the port to listen on"); - options.addOption("t", "threads", 1, "the number of threads to run"); - try { - SimpleCLI cmd = SimpleCLI.parse(options, args); - if (cmd.hasOption("h")) { - printUsage(options); - System.exit(0); - } - return cmd; - } catch (ParseException e) { - System.err.println(e); - printUsage(options); - } - - System.exit(-1); - return null; - } - - public static void printUsage(Options options) { - SimpleCLI.printHelp("Usage: " - + SimpleController.class.getCanonicalName() + " [options]", - options); - } -} diff --git a/third-party/openflowj/src/main/java/org/openflow/example/cli/Option.java b/third-party/openflowj/src/main/java/org/openflow/example/cli/Option.java deleted file mode 100644 index acf8446d4b..0000000000 --- a/third-party/openflowj/src/main/java/org/openflow/example/cli/Option.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.openflow.example.cli; - -public class Option { - String shortOpt; - String longOpt; - Object defaultVal; - String val; // current value of this option, string form - boolean specified; // was this option found in the cmdline? - String comment; - - /** - * Option information storrage - * - * @param shortOpt - * Short name for the option, e.g., "-p" - * @param longOpt - * Long name for option, e.g., "--port" - * @param defaultVal - * default value: "6633" or null if no default value - * @param comment - * String to print to explain this option, e.g., a help message - */ - public Option(String shortOpt, String longOpt, Object defaultVal, - String comment) { - super(); - this.shortOpt = shortOpt; - this.longOpt = longOpt; - this.defaultVal = defaultVal; - this.comment = comment; - this.specified = false; - } - - public Option(String shortOpt, String longOpt, String comment) { - this(shortOpt, longOpt, null, comment); - } - - public boolean needsArg() { - return this.defaultVal != null; - } -} diff --git a/third-party/openflowj/src/main/java/org/openflow/example/cli/Options.java b/third-party/openflowj/src/main/java/org/openflow/example/cli/Options.java deleted file mode 100644 index 7f55b50bc6..0000000000 --- a/third-party/openflowj/src/main/java/org/openflow/example/cli/Options.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.openflow.example.cli; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -/** - * Very basic CLI options listing - * - * @author Rob Sherwood (rob.sherwood@stanford.edu) - * - */ - -public class Options { - Map shortOptionsMap; - Map longOptionsMap; - - public Options() { - this.shortOptionsMap = new HashMap(); - this.longOptionsMap = new HashMap(); - } - - public static Options make(Option opts[]) { - Options options = new Options(); - for (int i = 0; i < opts.length; i++) - options.addOption(opts[i]); - return options; - } - - private void addOption(Option option) { - if (option.shortOpt != null) - this.shortOptionsMap.put(option.shortOpt, option); - if (option.longOpt != null) - this.longOptionsMap.put(option.longOpt, option); - } - - protected void addOption(String shortName, String longName, Object o, - String comment) { - Option option = new Option(shortName, longName, o, comment); - addOption(option); - } - - public void addOption(String shortName, String longName, boolean b, - String comment) { - this.addOption(shortName, longName, Boolean.valueOf(b), comment); - } - - public void addOption(String shortName, String longName, int i, - String comment) { - this.addOption(shortName, longName, Integer.valueOf(i), comment); - } - - public Option getOption(String shortName) { - return this.shortOptionsMap.get(shortName); - } - - public Option getOptionByLongName(String longName) { - return this.longOptionsMap.get(longName); - } - - public Collection